blob: e322c0cf252df013c12a1e76c952df5566970db2 [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"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070045#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000046
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000047#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000048#include <windows.h>
49#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000050
Larry Hastings61272b72014-01-07 12:41:53 -080051/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080052class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080053[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080054/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080055
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000056/* --- Globals ------------------------------------------------------------
57
Serhiy Storchaka05997252013-01-26 12:14:02 +020058NOTE: In the interpreter's initialization phase, some globals are currently
59 initialized dynamically as needed. In the process Unicode objects may
60 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061
62*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064
65#ifdef __cplusplus
66extern "C" {
67#endif
68
Victor Stinner8faf8212011-12-08 22:14:11 +010069/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
70#define MAX_UNICODE 0x10ffff
71
Victor Stinner910337b2011-10-03 03:20:16 +020072#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020073# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020074#else
75# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
76#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020077
Victor Stinnere90fe6a2011-10-01 16:48:13 +020078#define _PyUnicode_UTF8(op) \
79 (((PyCompactUnicodeObject*)(op))->utf8)
80#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020081 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020082 assert(PyUnicode_IS_READY(op)), \
83 PyUnicode_IS_COMPACT_ASCII(op) ? \
84 ((char*)((PyASCIIObject*)(op) + 1)) : \
85 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020086#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020087 (((PyCompactUnicodeObject*)(op))->utf8_length)
88#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020089 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020090 assert(PyUnicode_IS_READY(op)), \
91 PyUnicode_IS_COMPACT_ASCII(op) ? \
92 ((PyASCIIObject*)(op))->length : \
93 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020094#define _PyUnicode_WSTR(op) \
95 (((PyASCIIObject*)(op))->wstr)
96#define _PyUnicode_WSTR_LENGTH(op) \
97 (((PyCompactUnicodeObject*)(op))->wstr_length)
98#define _PyUnicode_LENGTH(op) \
99 (((PyASCIIObject *)(op))->length)
100#define _PyUnicode_STATE(op) \
101 (((PyASCIIObject *)(op))->state)
102#define _PyUnicode_HASH(op) \
103 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200104#define _PyUnicode_KIND(op) \
105 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200106 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200107#define _PyUnicode_GET_LENGTH(op) \
108 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200109 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200110#define _PyUnicode_DATA_ANY(op) \
111 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200112
Victor Stinner910337b2011-10-03 03:20:16 +0200113#undef PyUnicode_READY
114#define PyUnicode_READY(op) \
115 (assert(_PyUnicode_CHECK(op)), \
116 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200117 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100118 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200119
Victor Stinnerc379ead2011-10-03 12:52:27 +0200120#define _PyUnicode_SHARE_UTF8(op) \
121 (assert(_PyUnicode_CHECK(op)), \
122 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
123 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
124#define _PyUnicode_SHARE_WSTR(op) \
125 (assert(_PyUnicode_CHECK(op)), \
126 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
127
Victor Stinner829c0ad2011-10-03 01:08:02 +0200128/* true if the Unicode object has an allocated UTF-8 memory block
129 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200130#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200131 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200132 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200133 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
134
Victor Stinner03490912011-10-03 23:45:12 +0200135/* true if the Unicode object has an allocated wstr memory block
136 (not shared with other data) */
137#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200138 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200139 (!PyUnicode_IS_READY(op) || \
140 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
141
Victor Stinner910337b2011-10-03 03:20:16 +0200142/* Generic helper macro to convert characters of different types.
143 from_type and to_type have to be valid type names, begin and end
144 are pointers to the source characters which should be of type
145 "from_type *". to is a pointer of type "to_type *" and points to the
146 buffer where the result characters are written to. */
147#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
148 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100149 to_type *_to = (to_type *)(to); \
150 const from_type *_iter = (from_type *)(begin); \
151 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200152 Py_ssize_t n = (_end) - (_iter); \
153 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200154 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200155 while (_iter < (_unrolled_end)) { \
156 _to[0] = (to_type) _iter[0]; \
157 _to[1] = (to_type) _iter[1]; \
158 _to[2] = (to_type) _iter[2]; \
159 _to[3] = (to_type) _iter[3]; \
160 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200161 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200162 while (_iter < (_end)) \
163 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200164 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200165
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200166#ifdef MS_WINDOWS
167 /* On Windows, overallocate by 50% is the best factor */
168# define OVERALLOCATE_FACTOR 2
169#else
170 /* On Linux, overallocate by 25% is the best factor */
171# define OVERALLOCATE_FACTOR 4
172#endif
173
Walter Dörwald16807132007-05-25 13:52:07 +0000174/* This dictionary holds all interned unicode strings. Note that references
175 to strings in this dictionary are *not* counted in the string's ob_refcnt.
176 When the interned string reaches a refcnt of 0 the string deallocation
177 function will delete the reference from this dictionary.
178
179 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000180 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000181*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200182static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200185static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200186
Serhiy Storchaka678db842013-01-26 12:16:36 +0200187#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 do { \
189 if (unicode_empty != NULL) \
190 Py_INCREF(unicode_empty); \
191 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200192 unicode_empty = PyUnicode_New(0, 0); \
193 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200194 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200195 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
196 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200198 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200#define _Py_RETURN_UNICODE_EMPTY() \
201 do { \
202 _Py_INCREF_UNICODE_EMPTY(); \
203 return unicode_empty; \
204 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000205
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200206/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700207static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200208_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
209
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200210/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200211static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200212
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000213/* Single character Unicode strings in the Latin-1 range are being
214 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000216
Christian Heimes190d79e2008-01-30 11:58:22 +0000217/* Fast detection of the most frequent whitespace characters */
218const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000219 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000220/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000221/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000222/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x000C: * FORM FEED */
224/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000225 0, 1, 1, 1, 1, 1, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000227/* case 0x001C: * FILE SEPARATOR */
228/* case 0x001D: * GROUP SEPARATOR */
229/* case 0x001E: * RECORD SEPARATOR */
230/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000231 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000232/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000233 1, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000237
Benjamin Peterson14339b62009-01-31 16:36:08 +0000238 0, 0, 0, 0, 0, 0, 0, 0,
239 0, 0, 0, 0, 0, 0, 0, 0,
240 0, 0, 0, 0, 0, 0, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
242 0, 0, 0, 0, 0, 0, 0, 0,
243 0, 0, 0, 0, 0, 0, 0, 0,
244 0, 0, 0, 0, 0, 0, 0, 0,
245 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000246};
247
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200248/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200249static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200250static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100251static int unicode_modifiable(PyObject *unicode);
252
Victor Stinnerfe226c02011-10-03 03:52:20 +0200253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100255_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200256static PyObject *
257_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
258static PyObject *
259_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
260
261static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000262unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000263 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100264 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000265 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
266
Alexander Belopolsky40018472011-02-26 01:02:56 +0000267static void
268raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300269 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100270 PyObject *unicode,
271 Py_ssize_t startpos, Py_ssize_t endpos,
272 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000273
Christian Heimes190d79e2008-01-30 11:58:22 +0000274/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200275static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000276 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000277/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000278/* 0x000B, * LINE TABULATION */
279/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000280/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000281 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000282 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000283/* 0x001C, * FILE SEPARATOR */
284/* 0x001D, * GROUP SEPARATOR */
285/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 0, 0, 0, 0, 1, 1, 1, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000291
Benjamin Peterson14339b62009-01-31 16:36:08 +0000292 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,
298 0, 0, 0, 0, 0, 0, 0, 0,
299 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000300};
301
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300302#include "clinic/unicodeobject.c.h"
303
Victor Stinner50149202015-09-22 00:26:54 +0200304typedef enum {
305 _Py_ERROR_UNKNOWN=0,
306 _Py_ERROR_STRICT,
307 _Py_ERROR_SURROGATEESCAPE,
308 _Py_ERROR_REPLACE,
309 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200310 _Py_ERROR_BACKSLASHREPLACE,
311 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200312 _Py_ERROR_XMLCHARREFREPLACE,
313 _Py_ERROR_OTHER
314} _Py_error_handler;
315
316static _Py_error_handler
317get_error_handler(const char *errors)
318{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200319 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200320 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200321 }
322 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200323 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200324 }
325 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200326 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200327 }
328 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200329 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200330 }
331 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200332 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200333 }
334 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200335 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200336 }
337 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200338 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200339 }
Victor Stinner50149202015-09-22 00:26:54 +0200340 return _Py_ERROR_OTHER;
341}
342
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300343/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
344 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000345Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000346PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000347{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000348#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000349 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000350#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000351 /* This is actually an illegal character, so it should
352 not be passed to unichr. */
353 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000354#endif
355}
356
Victor Stinner910337b2011-10-03 03:20:16 +0200357#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200358int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100359_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200360{
361 PyASCIIObject *ascii;
362 unsigned int kind;
363
364 assert(PyUnicode_Check(op));
365
366 ascii = (PyASCIIObject *)op;
367 kind = ascii->state.kind;
368
Victor Stinnera3b334d2011-10-03 13:53:37 +0200369 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200370 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200371 assert(ascii->state.ready == 1);
372 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200373 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200374 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200375 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200376
Victor Stinnera41463c2011-10-04 01:05:08 +0200377 if (ascii->state.compact == 1) {
378 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200379 assert(kind == PyUnicode_1BYTE_KIND
380 || kind == PyUnicode_2BYTE_KIND
381 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200382 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200383 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200384 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100385 }
386 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200387 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
388
389 data = unicode->data.any;
390 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100391 assert(ascii->length == 0);
392 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200393 assert(ascii->state.compact == 0);
394 assert(ascii->state.ascii == 0);
395 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100396 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200397 assert(ascii->wstr != NULL);
398 assert(data == NULL);
399 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200400 }
401 else {
402 assert(kind == PyUnicode_1BYTE_KIND
403 || kind == PyUnicode_2BYTE_KIND
404 || kind == PyUnicode_4BYTE_KIND);
405 assert(ascii->state.compact == 0);
406 assert(ascii->state.ready == 1);
407 assert(data != NULL);
408 if (ascii->state.ascii) {
409 assert (compact->utf8 == data);
410 assert (compact->utf8_length == ascii->length);
411 }
412 else
413 assert (compact->utf8 != data);
414 }
415 }
416 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200417 if (
418#if SIZEOF_WCHAR_T == 2
419 kind == PyUnicode_2BYTE_KIND
420#else
421 kind == PyUnicode_4BYTE_KIND
422#endif
423 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200424 {
425 assert(ascii->wstr == data);
426 assert(compact->wstr_length == ascii->length);
427 } else
428 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200429 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200430
431 if (compact->utf8 == NULL)
432 assert(compact->utf8_length == 0);
433 if (ascii->wstr == NULL)
434 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200435 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200436 /* check that the best kind is used */
437 if (check_content && kind != PyUnicode_WCHAR_KIND)
438 {
439 Py_ssize_t i;
440 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200441 void *data;
442 Py_UCS4 ch;
443
444 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200445 for (i=0; i < ascii->length; i++)
446 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200447 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200448 if (ch > maxchar)
449 maxchar = ch;
450 }
451 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100452 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100454 assert(maxchar <= 255);
455 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200456 else
457 assert(maxchar < 128);
458 }
Victor Stinner77faf692011-11-20 18:56:05 +0100459 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200460 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100461 assert(maxchar <= 0xFFFF);
462 }
463 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200464 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100465 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100466 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200467 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200468 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400469 return 1;
470}
Victor Stinner910337b2011-10-03 03:20:16 +0200471#endif
472
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100473static PyObject*
474unicode_result_wchar(PyObject *unicode)
475{
476#ifndef Py_DEBUG
477 Py_ssize_t len;
478
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100479 len = _PyUnicode_WSTR_LENGTH(unicode);
480 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100481 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200482 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100483 }
484
485 if (len == 1) {
486 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100487 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100488 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
489 Py_DECREF(unicode);
490 return latin1_char;
491 }
492 }
493
494 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200495 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100496 return NULL;
497 }
498#else
Victor Stinneraa771272012-10-04 02:32:58 +0200499 assert(Py_REFCNT(unicode) == 1);
500
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100501 /* don't make the result ready in debug mode to ensure that the caller
502 makes the string ready before using it */
503 assert(_PyUnicode_CheckConsistency(unicode, 1));
504#endif
505 return unicode;
506}
507
508static PyObject*
509unicode_result_ready(PyObject *unicode)
510{
511 Py_ssize_t length;
512
513 length = PyUnicode_GET_LENGTH(unicode);
514 if (length == 0) {
515 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100516 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200517 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100518 }
519 return unicode_empty;
520 }
521
522 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200523 void *data = PyUnicode_DATA(unicode);
524 int kind = PyUnicode_KIND(unicode);
525 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100526 if (ch < 256) {
527 PyObject *latin1_char = unicode_latin1[ch];
528 if (latin1_char != NULL) {
529 if (unicode != latin1_char) {
530 Py_INCREF(latin1_char);
531 Py_DECREF(unicode);
532 }
533 return latin1_char;
534 }
535 else {
536 assert(_PyUnicode_CheckConsistency(unicode, 1));
537 Py_INCREF(unicode);
538 unicode_latin1[ch] = unicode;
539 return unicode;
540 }
541 }
542 }
543
544 assert(_PyUnicode_CheckConsistency(unicode, 1));
545 return unicode;
546}
547
548static PyObject*
549unicode_result(PyObject *unicode)
550{
551 assert(_PyUnicode_CHECK(unicode));
552 if (PyUnicode_IS_READY(unicode))
553 return unicode_result_ready(unicode);
554 else
555 return unicode_result_wchar(unicode);
556}
557
Victor Stinnerc4b49542011-12-11 22:44:26 +0100558static PyObject*
559unicode_result_unchanged(PyObject *unicode)
560{
561 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500562 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100563 return NULL;
564 Py_INCREF(unicode);
565 return unicode;
566 }
567 else
568 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100569 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100570}
571
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200572/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
573 ASCII, Latin1, UTF-8, etc. */
574static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200575backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200576 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
577{
Victor Stinnerad771582015-10-09 12:38:53 +0200578 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200579 Py_UCS4 ch;
580 enum PyUnicode_Kind kind;
581 void *data;
582
583 assert(PyUnicode_IS_READY(unicode));
584 kind = PyUnicode_KIND(unicode);
585 data = PyUnicode_DATA(unicode);
586
587 size = 0;
588 /* determine replacement size */
589 for (i = collstart; i < collend; ++i) {
590 Py_ssize_t incr;
591
592 ch = PyUnicode_READ(kind, data, i);
593 if (ch < 0x100)
594 incr = 2+2;
595 else if (ch < 0x10000)
596 incr = 2+4;
597 else {
598 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200599 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200600 }
601 if (size > PY_SSIZE_T_MAX - incr) {
602 PyErr_SetString(PyExc_OverflowError,
603 "encoded result is too long for a Python string");
604 return NULL;
605 }
606 size += incr;
607 }
608
Victor Stinnerad771582015-10-09 12:38:53 +0200609 str = _PyBytesWriter_Prepare(writer, str, size);
610 if (str == NULL)
611 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200612
613 /* generate replacement */
614 for (i = collstart; i < collend; ++i) {
615 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200616 *str++ = '\\';
617 if (ch >= 0x00010000) {
618 *str++ = 'U';
619 *str++ = Py_hexdigits[(ch>>28)&0xf];
620 *str++ = Py_hexdigits[(ch>>24)&0xf];
621 *str++ = Py_hexdigits[(ch>>20)&0xf];
622 *str++ = Py_hexdigits[(ch>>16)&0xf];
623 *str++ = Py_hexdigits[(ch>>12)&0xf];
624 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200625 }
Victor Stinner797485e2015-10-09 03:17:30 +0200626 else if (ch >= 0x100) {
627 *str++ = 'u';
628 *str++ = Py_hexdigits[(ch>>12)&0xf];
629 *str++ = Py_hexdigits[(ch>>8)&0xf];
630 }
631 else
632 *str++ = 'x';
633 *str++ = Py_hexdigits[(ch>>4)&0xf];
634 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200635 }
636 return str;
637}
638
639/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
640 ASCII, Latin1, UTF-8, etc. */
641static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200642xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200643 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
644{
Victor Stinnerad771582015-10-09 12:38:53 +0200645 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200646 Py_UCS4 ch;
647 enum PyUnicode_Kind kind;
648 void *data;
649
650 assert(PyUnicode_IS_READY(unicode));
651 kind = PyUnicode_KIND(unicode);
652 data = PyUnicode_DATA(unicode);
653
654 size = 0;
655 /* determine replacement size */
656 for (i = collstart; i < collend; ++i) {
657 Py_ssize_t incr;
658
659 ch = PyUnicode_READ(kind, data, i);
660 if (ch < 10)
661 incr = 2+1+1;
662 else if (ch < 100)
663 incr = 2+2+1;
664 else if (ch < 1000)
665 incr = 2+3+1;
666 else if (ch < 10000)
667 incr = 2+4+1;
668 else if (ch < 100000)
669 incr = 2+5+1;
670 else if (ch < 1000000)
671 incr = 2+6+1;
672 else {
673 assert(ch <= MAX_UNICODE);
674 incr = 2+7+1;
675 }
676 if (size > PY_SSIZE_T_MAX - incr) {
677 PyErr_SetString(PyExc_OverflowError,
678 "encoded result is too long for a Python string");
679 return NULL;
680 }
681 size += incr;
682 }
683
Victor Stinnerad771582015-10-09 12:38:53 +0200684 str = _PyBytesWriter_Prepare(writer, str, size);
685 if (str == NULL)
686 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200687
688 /* generate replacement */
689 for (i = collstart; i < collend; ++i) {
690 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
691 }
692 return str;
693}
694
Thomas Wouters477c8d52006-05-27 19:21:47 +0000695/* --- Bloom Filters ----------------------------------------------------- */
696
697/* stuff to implement simple "bloom filters" for Unicode characters.
698 to keep things simple, we use a single bitmask, using the least 5
699 bits from each unicode characters as the bit index. */
700
701/* the linebreak mask is set up by Unicode_Init below */
702
Antoine Pitrouf068f942010-01-13 14:19:12 +0000703#if LONG_BIT >= 128
704#define BLOOM_WIDTH 128
705#elif LONG_BIT >= 64
706#define BLOOM_WIDTH 64
707#elif LONG_BIT >= 32
708#define BLOOM_WIDTH 32
709#else
710#error "LONG_BIT is smaller than 32"
711#endif
712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713#define BLOOM_MASK unsigned long
714
Serhiy Storchaka05997252013-01-26 12:14:02 +0200715static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716
Antoine Pitrouf068f942010-01-13 14:19:12 +0000717#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718
Benjamin Peterson29060642009-01-31 22:14:21 +0000719#define BLOOM_LINEBREAK(ch) \
720 ((ch) < 128U ? ascii_linebreak[(ch)] : \
721 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000722
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700723static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200724make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000725{
Victor Stinnera85af502013-04-09 21:53:54 +0200726#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
727 do { \
728 TYPE *data = (TYPE *)PTR; \
729 TYPE *end = data + LEN; \
730 Py_UCS4 ch; \
731 for (; data != end; data++) { \
732 ch = *data; \
733 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
734 } \
735 break; \
736 } while (0)
737
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738 /* calculate simple bloom-style bitmask for a given unicode string */
739
Antoine Pitrouf068f942010-01-13 14:19:12 +0000740 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741
742 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200743 switch (kind) {
744 case PyUnicode_1BYTE_KIND:
745 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
746 break;
747 case PyUnicode_2BYTE_KIND:
748 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
749 break;
750 case PyUnicode_4BYTE_KIND:
751 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
752 break;
753 default:
754 assert(0);
755 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000756 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200757
758#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000759}
760
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300761static int
762ensure_unicode(PyObject *obj)
763{
764 if (!PyUnicode_Check(obj)) {
765 PyErr_Format(PyExc_TypeError,
766 "must be str, not %.100s",
767 Py_TYPE(obj)->tp_name);
768 return -1;
769 }
770 return PyUnicode_READY(obj);
771}
772
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200773/* Compilation of templated routines */
774
775#include "stringlib/asciilib.h"
776#include "stringlib/fastsearch.h"
777#include "stringlib/partition.h"
778#include "stringlib/split.h"
779#include "stringlib/count.h"
780#include "stringlib/find.h"
781#include "stringlib/find_max_char.h"
782#include "stringlib/localeutil.h"
783#include "stringlib/undef.h"
784
785#include "stringlib/ucs1lib.h"
786#include "stringlib/fastsearch.h"
787#include "stringlib/partition.h"
788#include "stringlib/split.h"
789#include "stringlib/count.h"
790#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300791#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200792#include "stringlib/find_max_char.h"
793#include "stringlib/localeutil.h"
794#include "stringlib/undef.h"
795
796#include "stringlib/ucs2lib.h"
797#include "stringlib/fastsearch.h"
798#include "stringlib/partition.h"
799#include "stringlib/split.h"
800#include "stringlib/count.h"
801#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300802#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200803#include "stringlib/find_max_char.h"
804#include "stringlib/localeutil.h"
805#include "stringlib/undef.h"
806
807#include "stringlib/ucs4lib.h"
808#include "stringlib/fastsearch.h"
809#include "stringlib/partition.h"
810#include "stringlib/split.h"
811#include "stringlib/count.h"
812#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300813#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200814#include "stringlib/find_max_char.h"
815#include "stringlib/localeutil.h"
816#include "stringlib/undef.h"
817
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200818#include "stringlib/unicodedefs.h"
819#include "stringlib/fastsearch.h"
820#include "stringlib/count.h"
821#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100822#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200823
Guido van Rossumd57fd912000-03-10 22:53:23 +0000824/* --- Unicode Object ----------------------------------------------------- */
825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200826static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200827fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200828
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700829static inline Py_ssize_t
830findchar(const void *s, int kind,
831 Py_ssize_t size, Py_UCS4 ch,
832 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200833{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200834 switch (kind) {
835 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200836 if ((Py_UCS1) ch != ch)
837 return -1;
838 if (direction > 0)
839 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
840 else
841 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200842 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200843 if ((Py_UCS2) ch != ch)
844 return -1;
845 if (direction > 0)
846 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
847 else
848 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200849 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200850 if (direction > 0)
851 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
852 else
853 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200854 default:
855 assert(0);
856 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200857 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200858}
859
Victor Stinnerafffce42012-10-03 23:03:17 +0200860#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000861/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200862 earlier.
863
864 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
865 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
866 invalid character in Unicode 6.0. */
867static void
868unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
869{
870 int kind = PyUnicode_KIND(unicode);
871 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
872 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
873 if (length <= old_length)
874 return;
875 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
876}
877#endif
878
Victor Stinnerfe226c02011-10-03 03:52:20 +0200879static PyObject*
880resize_compact(PyObject *unicode, Py_ssize_t length)
881{
882 Py_ssize_t char_size;
883 Py_ssize_t struct_size;
884 Py_ssize_t new_size;
885 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100886 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200887#ifdef Py_DEBUG
888 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
889#endif
890
Victor Stinner79891572012-05-03 13:43:07 +0200891 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200892 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100893 assert(PyUnicode_IS_COMPACT(unicode));
894
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200895 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100896 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200897 struct_size = sizeof(PyASCIIObject);
898 else
899 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200900 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200901
Victor Stinnerfe226c02011-10-03 03:52:20 +0200902 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
903 PyErr_NoMemory();
904 return NULL;
905 }
906 new_size = (struct_size + (length + 1) * char_size);
907
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200908 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
909 PyObject_DEL(_PyUnicode_UTF8(unicode));
910 _PyUnicode_UTF8(unicode) = NULL;
911 _PyUnicode_UTF8_LENGTH(unicode) = 0;
912 }
Victor Stinner84def372011-12-11 20:04:56 +0100913 _Py_DEC_REFTOTAL;
914 _Py_ForgetReference(unicode);
915
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300916 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100917 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100918 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200919 PyErr_NoMemory();
920 return NULL;
921 }
Victor Stinner84def372011-12-11 20:04:56 +0100922 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200923 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100924
Victor Stinnerfe226c02011-10-03 03:52:20 +0200925 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200926 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200927 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100928 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200929 _PyUnicode_WSTR_LENGTH(unicode) = length;
930 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100931 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
932 PyObject_DEL(_PyUnicode_WSTR(unicode));
933 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100934 if (!PyUnicode_IS_ASCII(unicode))
935 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100936 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200937#ifdef Py_DEBUG
938 unicode_fill_invalid(unicode, old_length);
939#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
941 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200942 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200943 return unicode;
944}
945
Alexander Belopolsky40018472011-02-26 01:02:56 +0000946static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200947resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000948{
Victor Stinner95663112011-10-04 01:03:50 +0200949 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100950 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200951 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200952 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000953
Victor Stinnerfe226c02011-10-03 03:52:20 +0200954 if (PyUnicode_IS_READY(unicode)) {
955 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200956 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200957 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200958#ifdef Py_DEBUG
959 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
960#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200961
962 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200963 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200964 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
965 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200966
967 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
968 PyErr_NoMemory();
969 return -1;
970 }
971 new_size = (length + 1) * char_size;
972
Victor Stinner7a9105a2011-12-12 00:13:42 +0100973 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
974 {
975 PyObject_DEL(_PyUnicode_UTF8(unicode));
976 _PyUnicode_UTF8(unicode) = NULL;
977 _PyUnicode_UTF8_LENGTH(unicode) = 0;
978 }
979
Victor Stinnerfe226c02011-10-03 03:52:20 +0200980 data = (PyObject *)PyObject_REALLOC(data, new_size);
981 if (data == NULL) {
982 PyErr_NoMemory();
983 return -1;
984 }
985 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200986 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200987 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200988 _PyUnicode_WSTR_LENGTH(unicode) = length;
989 }
990 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200991 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200992 _PyUnicode_UTF8_LENGTH(unicode) = length;
993 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200994 _PyUnicode_LENGTH(unicode) = length;
995 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200996#ifdef Py_DEBUG
997 unicode_fill_invalid(unicode, old_length);
998#endif
Victor Stinner95663112011-10-04 01:03:50 +0200999 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001000 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001001 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001002 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001003 }
Victor Stinner95663112011-10-04 01:03:50 +02001004 assert(_PyUnicode_WSTR(unicode) != NULL);
1005
1006 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001007 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001008 PyErr_NoMemory();
1009 return -1;
1010 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001011 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001012 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001013 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001014 if (!wstr) {
1015 PyErr_NoMemory();
1016 return -1;
1017 }
1018 _PyUnicode_WSTR(unicode) = wstr;
1019 _PyUnicode_WSTR(unicode)[length] = 0;
1020 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001021 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001022 return 0;
1023}
1024
Victor Stinnerfe226c02011-10-03 03:52:20 +02001025static PyObject*
1026resize_copy(PyObject *unicode, Py_ssize_t length)
1027{
1028 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001029 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001030 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001031
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001032 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001033
1034 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1035 if (copy == NULL)
1036 return NULL;
1037
1038 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001039 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001040 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001041 }
1042 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001043 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001044
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001045 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046 if (w == NULL)
1047 return NULL;
1048 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1049 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001050 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001051 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001052 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001053 }
1054}
1055
Guido van Rossumd57fd912000-03-10 22:53:23 +00001056/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001057 Ux0000 terminated; some code (e.g. new_identifier)
1058 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001059
1060 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001061 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001062
1063*/
1064
Alexander Belopolsky40018472011-02-26 01:02:56 +00001065static PyUnicodeObject *
1066_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001067{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001068 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001069 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001070
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001072 if (length == 0 && unicode_empty != NULL) {
1073 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001074 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001075 }
1076
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001077 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001078 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001079 return (PyUnicodeObject *)PyErr_NoMemory();
1080 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081 if (length < 0) {
1082 PyErr_SetString(PyExc_SystemError,
1083 "Negative size passed to _PyUnicode_New");
1084 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001085 }
1086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1088 if (unicode == NULL)
1089 return NULL;
1090 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001091
1092 _PyUnicode_WSTR_LENGTH(unicode) = length;
1093 _PyUnicode_HASH(unicode) = -1;
1094 _PyUnicode_STATE(unicode).interned = 0;
1095 _PyUnicode_STATE(unicode).kind = 0;
1096 _PyUnicode_STATE(unicode).compact = 0;
1097 _PyUnicode_STATE(unicode).ready = 0;
1098 _PyUnicode_STATE(unicode).ascii = 0;
1099 _PyUnicode_DATA_ANY(unicode) = NULL;
1100 _PyUnicode_LENGTH(unicode) = 0;
1101 _PyUnicode_UTF8(unicode) = NULL;
1102 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001104 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1105 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001106 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001107 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001108 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001109 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110
Jeremy Hyltond8082792003-09-16 19:41:39 +00001111 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001112 * the caller fails before initializing str -- unicode_resize()
1113 * reads str[0], and the Keep-Alive optimization can keep memory
1114 * allocated for str alive across a call to unicode_dealloc(unicode).
1115 * We don't want unicode_resize to read uninitialized memory in
1116 * that case.
1117 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001118 _PyUnicode_WSTR(unicode)[0] = 0;
1119 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001120
Victor Stinner7931d9a2011-11-04 00:22:48 +01001121 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001122 return unicode;
1123}
1124
Victor Stinnerf42dc442011-10-02 23:33:16 +02001125static const char*
1126unicode_kind_name(PyObject *unicode)
1127{
Victor Stinner42dfd712011-10-03 14:41:45 +02001128 /* don't check consistency: unicode_kind_name() is called from
1129 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001130 if (!PyUnicode_IS_COMPACT(unicode))
1131 {
1132 if (!PyUnicode_IS_READY(unicode))
1133 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001134 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001135 {
1136 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001137 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001138 return "legacy ascii";
1139 else
1140 return "legacy latin1";
1141 case PyUnicode_2BYTE_KIND:
1142 return "legacy UCS2";
1143 case PyUnicode_4BYTE_KIND:
1144 return "legacy UCS4";
1145 default:
1146 return "<legacy invalid kind>";
1147 }
1148 }
1149 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001150 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001152 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001153 return "ascii";
1154 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001155 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001156 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001157 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001158 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001159 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001160 default:
1161 return "<invalid compact kind>";
1162 }
1163}
1164
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001165#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166/* Functions wrapping macros for use in debugger */
1167char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001168 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001169}
1170
1171void *_PyUnicode_compact_data(void *unicode) {
1172 return _PyUnicode_COMPACT_DATA(unicode);
1173}
1174void *_PyUnicode_data(void *unicode){
1175 printf("obj %p\n", unicode);
1176 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1177 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1178 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1179 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1180 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1181 return PyUnicode_DATA(unicode);
1182}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001183
1184void
1185_PyUnicode_Dump(PyObject *op)
1186{
1187 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001188 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1189 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1190 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001191
Victor Stinnera849a4b2011-10-03 12:12:11 +02001192 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001193 {
1194 if (ascii->state.ascii)
1195 data = (ascii + 1);
1196 else
1197 data = (compact + 1);
1198 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001199 else
1200 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001201 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1202 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001203
Victor Stinnera849a4b2011-10-03 12:12:11 +02001204 if (ascii->wstr == data)
1205 printf("shared ");
1206 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001207
Victor Stinnera3b334d2011-10-03 13:53:37 +02001208 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001209 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001210 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1211 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001212 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1213 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001214 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001215 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001216}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001217#endif
1218
1219PyObject *
1220PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1221{
1222 PyObject *obj;
1223 PyCompactUnicodeObject *unicode;
1224 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001225 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001226 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001227 Py_ssize_t char_size;
1228 Py_ssize_t struct_size;
1229
1230 /* Optimization for empty strings */
1231 if (size == 0 && unicode_empty != NULL) {
1232 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001233 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001234 }
1235
Victor Stinner9e9d6892011-10-04 01:02:02 +02001236 is_ascii = 0;
1237 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001238 struct_size = sizeof(PyCompactUnicodeObject);
1239 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001240 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001241 char_size = 1;
1242 is_ascii = 1;
1243 struct_size = sizeof(PyASCIIObject);
1244 }
1245 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001246 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001247 char_size = 1;
1248 }
1249 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001250 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 char_size = 2;
1252 if (sizeof(wchar_t) == 2)
1253 is_sharing = 1;
1254 }
1255 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001256 if (maxchar > MAX_UNICODE) {
1257 PyErr_SetString(PyExc_SystemError,
1258 "invalid maximum character passed to PyUnicode_New");
1259 return NULL;
1260 }
Victor Stinner8f825062012-04-27 13:55:39 +02001261 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001262 char_size = 4;
1263 if (sizeof(wchar_t) == 4)
1264 is_sharing = 1;
1265 }
1266
1267 /* Ensure we won't overflow the size. */
1268 if (size < 0) {
1269 PyErr_SetString(PyExc_SystemError,
1270 "Negative size passed to PyUnicode_New");
1271 return NULL;
1272 }
1273 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1274 return PyErr_NoMemory();
1275
1276 /* Duplicated allocation code from _PyObject_New() instead of a call to
1277 * PyObject_New() so we are able to allocate space for the object and
1278 * it's data buffer.
1279 */
1280 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1281 if (obj == NULL)
1282 return PyErr_NoMemory();
1283 obj = PyObject_INIT(obj, &PyUnicode_Type);
1284 if (obj == NULL)
1285 return NULL;
1286
1287 unicode = (PyCompactUnicodeObject *)obj;
1288 if (is_ascii)
1289 data = ((PyASCIIObject*)obj) + 1;
1290 else
1291 data = unicode + 1;
1292 _PyUnicode_LENGTH(unicode) = size;
1293 _PyUnicode_HASH(unicode) = -1;
1294 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001295 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001296 _PyUnicode_STATE(unicode).compact = 1;
1297 _PyUnicode_STATE(unicode).ready = 1;
1298 _PyUnicode_STATE(unicode).ascii = is_ascii;
1299 if (is_ascii) {
1300 ((char*)data)[size] = 0;
1301 _PyUnicode_WSTR(unicode) = NULL;
1302 }
Victor Stinner8f825062012-04-27 13:55:39 +02001303 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 ((char*)data)[size] = 0;
1305 _PyUnicode_WSTR(unicode) = NULL;
1306 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001308 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310 else {
1311 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001312 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001313 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001315 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 ((Py_UCS4*)data)[size] = 0;
1317 if (is_sharing) {
1318 _PyUnicode_WSTR_LENGTH(unicode) = size;
1319 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1320 }
1321 else {
1322 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1323 _PyUnicode_WSTR(unicode) = NULL;
1324 }
1325 }
Victor Stinner8f825062012-04-27 13:55:39 +02001326#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001327 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001328#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001329 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330 return obj;
1331}
1332
1333#if SIZEOF_WCHAR_T == 2
1334/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1335 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001336 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337
1338 This function assumes that unicode can hold one more code point than wstr
1339 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001340static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001341unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001342 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343{
1344 const wchar_t *iter;
1345 Py_UCS4 *ucs4_out;
1346
Victor Stinner910337b2011-10-03 03:20:16 +02001347 assert(unicode != NULL);
1348 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1350 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1351
1352 for (iter = begin; iter < end; ) {
1353 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1354 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001355 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1356 && (iter+1) < end
1357 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001358 {
Victor Stinner551ac952011-11-29 22:58:13 +01001359 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001360 iter += 2;
1361 }
1362 else {
1363 *ucs4_out++ = *iter;
1364 iter++;
1365 }
1366 }
1367 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1368 _PyUnicode_GET_LENGTH(unicode)));
1369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001370}
1371#endif
1372
Victor Stinnercd9950f2011-10-02 00:34:53 +02001373static int
Victor Stinner488fa492011-12-12 00:01:39 +01001374unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001375{
Victor Stinner488fa492011-12-12 00:01:39 +01001376 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001377 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001378 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001379 return -1;
1380 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001381 return 0;
1382}
1383
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001384static int
1385_copy_characters(PyObject *to, Py_ssize_t to_start,
1386 PyObject *from, Py_ssize_t from_start,
1387 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001388{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001389 unsigned int from_kind, to_kind;
1390 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001391
Victor Stinneree4544c2012-05-09 22:24:08 +02001392 assert(0 <= how_many);
1393 assert(0 <= from_start);
1394 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001395 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001396 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001397 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001398
Victor Stinnerd3f08822012-05-29 12:57:52 +02001399 assert(PyUnicode_Check(to));
1400 assert(PyUnicode_IS_READY(to));
1401 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1402
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001403 if (how_many == 0)
1404 return 0;
1405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001407 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001409 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410
Victor Stinnerf1852262012-06-16 16:38:26 +02001411#ifdef Py_DEBUG
1412 if (!check_maxchar
1413 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1414 {
1415 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1416 Py_UCS4 ch;
1417 Py_ssize_t i;
1418 for (i=0; i < how_many; i++) {
1419 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1420 assert(ch <= to_maxchar);
1421 }
1422 }
1423#endif
1424
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001425 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001426 if (check_maxchar
1427 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1428 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001429 /* Writing Latin-1 characters into an ASCII string requires to
1430 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001431 Py_UCS4 max_char;
1432 max_char = ucs1lib_find_max_char(from_data,
1433 (Py_UCS1*)from_data + how_many);
1434 if (max_char >= 128)
1435 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001436 }
Christian Heimesf051e432016-09-13 20:22:02 +02001437 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001438 (char*)from_data + from_kind * from_start,
1439 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001441 else if (from_kind == PyUnicode_1BYTE_KIND
1442 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001443 {
1444 _PyUnicode_CONVERT_BYTES(
1445 Py_UCS1, Py_UCS2,
1446 PyUnicode_1BYTE_DATA(from) + from_start,
1447 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1448 PyUnicode_2BYTE_DATA(to) + to_start
1449 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001450 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001451 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001452 && to_kind == PyUnicode_4BYTE_KIND)
1453 {
1454 _PyUnicode_CONVERT_BYTES(
1455 Py_UCS1, Py_UCS4,
1456 PyUnicode_1BYTE_DATA(from) + from_start,
1457 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1458 PyUnicode_4BYTE_DATA(to) + to_start
1459 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001460 }
1461 else if (from_kind == PyUnicode_2BYTE_KIND
1462 && to_kind == PyUnicode_4BYTE_KIND)
1463 {
1464 _PyUnicode_CONVERT_BYTES(
1465 Py_UCS2, Py_UCS4,
1466 PyUnicode_2BYTE_DATA(from) + from_start,
1467 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1468 PyUnicode_4BYTE_DATA(to) + to_start
1469 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001470 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001471 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001472 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1473
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001474 if (!check_maxchar) {
1475 if (from_kind == PyUnicode_2BYTE_KIND
1476 && to_kind == PyUnicode_1BYTE_KIND)
1477 {
1478 _PyUnicode_CONVERT_BYTES(
1479 Py_UCS2, Py_UCS1,
1480 PyUnicode_2BYTE_DATA(from) + from_start,
1481 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1482 PyUnicode_1BYTE_DATA(to) + to_start
1483 );
1484 }
1485 else if (from_kind == PyUnicode_4BYTE_KIND
1486 && to_kind == PyUnicode_1BYTE_KIND)
1487 {
1488 _PyUnicode_CONVERT_BYTES(
1489 Py_UCS4, Py_UCS1,
1490 PyUnicode_4BYTE_DATA(from) + from_start,
1491 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1492 PyUnicode_1BYTE_DATA(to) + to_start
1493 );
1494 }
1495 else if (from_kind == PyUnicode_4BYTE_KIND
1496 && to_kind == PyUnicode_2BYTE_KIND)
1497 {
1498 _PyUnicode_CONVERT_BYTES(
1499 Py_UCS4, Py_UCS2,
1500 PyUnicode_4BYTE_DATA(from) + from_start,
1501 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1502 PyUnicode_2BYTE_DATA(to) + to_start
1503 );
1504 }
1505 else {
1506 assert(0);
1507 return -1;
1508 }
1509 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001510 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001511 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001512 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001513 Py_ssize_t i;
1514
Victor Stinnera0702ab2011-09-29 14:14:38 +02001515 for (i=0; i < how_many; i++) {
1516 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001517 if (ch > to_maxchar)
1518 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001519 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1520 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001521 }
1522 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001523 return 0;
1524}
1525
Victor Stinnerd3f08822012-05-29 12:57:52 +02001526void
1527_PyUnicode_FastCopyCharacters(
1528 PyObject *to, Py_ssize_t to_start,
1529 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001530{
1531 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1532}
1533
1534Py_ssize_t
1535PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1536 PyObject *from, Py_ssize_t from_start,
1537 Py_ssize_t how_many)
1538{
1539 int err;
1540
1541 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1542 PyErr_BadInternalCall();
1543 return -1;
1544 }
1545
Benjamin Petersonbac79492012-01-14 13:34:47 -05001546 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001547 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001548 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001549 return -1;
1550
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001551 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001552 PyErr_SetString(PyExc_IndexError, "string index out of range");
1553 return -1;
1554 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001555 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001556 PyErr_SetString(PyExc_IndexError, "string index out of range");
1557 return -1;
1558 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001559 if (how_many < 0) {
1560 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1561 return -1;
1562 }
1563 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001564 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1565 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001566 "Cannot write %zi characters at %zi "
1567 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001568 how_many, to_start, PyUnicode_GET_LENGTH(to));
1569 return -1;
1570 }
1571
1572 if (how_many == 0)
1573 return 0;
1574
Victor Stinner488fa492011-12-12 00:01:39 +01001575 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001576 return -1;
1577
1578 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1579 if (err) {
1580 PyErr_Format(PyExc_SystemError,
1581 "Cannot copy %s characters "
1582 "into a string of %s characters",
1583 unicode_kind_name(from),
1584 unicode_kind_name(to));
1585 return -1;
1586 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001587 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588}
1589
Victor Stinner17222162011-09-28 22:15:37 +02001590/* Find the maximum code point and count the number of surrogate pairs so a
1591 correct string length can be computed before converting a string to UCS4.
1592 This function counts single surrogates as a character and not as a pair.
1593
1594 Return 0 on success, or -1 on error. */
1595static int
1596find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1597 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598{
1599 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001600 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001601
Victor Stinnerc53be962011-10-02 21:33:54 +02001602 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001603 *num_surrogates = 0;
1604 *maxchar = 0;
1605
1606 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001607#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001608 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1609 && (iter+1) < end
1610 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1611 {
1612 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1613 ++(*num_surrogates);
1614 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 }
1616 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001618 {
1619 ch = *iter;
1620 iter++;
1621 }
1622 if (ch > *maxchar) {
1623 *maxchar = ch;
1624 if (*maxchar > MAX_UNICODE) {
1625 PyErr_Format(PyExc_ValueError,
1626 "character U+%x is not in range [U+0000; U+10ffff]",
1627 ch);
1628 return -1;
1629 }
1630 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001631 }
1632 return 0;
1633}
1634
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001635int
1636_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001637{
1638 wchar_t *end;
1639 Py_UCS4 maxchar = 0;
1640 Py_ssize_t num_surrogates;
1641#if SIZEOF_WCHAR_T == 2
1642 Py_ssize_t length_wo_surrogates;
1643#endif
1644
Georg Brandl7597add2011-10-05 16:36:47 +02001645 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001646 strings were created using _PyObject_New() and where no canonical
1647 representation (the str field) has been set yet aka strings
1648 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001649 assert(_PyUnicode_CHECK(unicode));
1650 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001651 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001652 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001653 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001654 /* Actually, it should neither be interned nor be anything else: */
1655 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001656
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001658 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001659 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001660 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661
1662 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001663 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1664 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001665 PyErr_NoMemory();
1666 return -1;
1667 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001668 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 _PyUnicode_WSTR(unicode), end,
1670 PyUnicode_1BYTE_DATA(unicode));
1671 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1672 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1673 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1674 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001675 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001676 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001677 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001678 }
1679 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001680 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001681 _PyUnicode_UTF8(unicode) = NULL;
1682 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001683 }
1684 PyObject_FREE(_PyUnicode_WSTR(unicode));
1685 _PyUnicode_WSTR(unicode) = NULL;
1686 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1687 }
1688 /* In this case we might have to convert down from 4-byte native
1689 wchar_t to 2-byte unicode. */
1690 else if (maxchar < 65536) {
1691 assert(num_surrogates == 0 &&
1692 "FindMaxCharAndNumSurrogatePairs() messed up");
1693
Victor Stinner506f5922011-09-28 22:34:18 +02001694#if SIZEOF_WCHAR_T == 2
1695 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001696 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001697 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1698 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1699 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001700 _PyUnicode_UTF8(unicode) = NULL;
1701 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001702#else
1703 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001704 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001705 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001706 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001707 PyErr_NoMemory();
1708 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001709 }
Victor Stinner506f5922011-09-28 22:34:18 +02001710 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1711 _PyUnicode_WSTR(unicode), end,
1712 PyUnicode_2BYTE_DATA(unicode));
1713 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1714 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1715 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001716 _PyUnicode_UTF8(unicode) = NULL;
1717 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001718 PyObject_FREE(_PyUnicode_WSTR(unicode));
1719 _PyUnicode_WSTR(unicode) = NULL;
1720 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1721#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001722 }
1723 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1724 else {
1725#if SIZEOF_WCHAR_T == 2
1726 /* in case the native representation is 2-bytes, we need to allocate a
1727 new normalized 4-byte version. */
1728 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001729 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1730 PyErr_NoMemory();
1731 return -1;
1732 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001733 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1734 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001735 PyErr_NoMemory();
1736 return -1;
1737 }
1738 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1739 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001740 _PyUnicode_UTF8(unicode) = NULL;
1741 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001742 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1743 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001744 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001745 PyObject_FREE(_PyUnicode_WSTR(unicode));
1746 _PyUnicode_WSTR(unicode) = NULL;
1747 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1748#else
1749 assert(num_surrogates == 0);
1750
Victor Stinnerc3c74152011-10-02 20:39:55 +02001751 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001753 _PyUnicode_UTF8(unicode) = NULL;
1754 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001755 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1756#endif
1757 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1758 }
1759 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001760 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001761 return 0;
1762}
1763
Alexander Belopolsky40018472011-02-26 01:02:56 +00001764static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001765unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001766{
Walter Dörwald16807132007-05-25 13:52:07 +00001767 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001768 case SSTATE_NOT_INTERNED:
1769 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001770
Benjamin Peterson29060642009-01-31 22:14:21 +00001771 case SSTATE_INTERNED_MORTAL:
1772 /* revive dead object temporarily for DelItem */
1773 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001774 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001775 Py_FatalError(
1776 "deletion of interned string failed");
1777 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001778
Benjamin Peterson29060642009-01-31 22:14:21 +00001779 case SSTATE_INTERNED_IMMORTAL:
1780 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001781
Benjamin Peterson29060642009-01-31 22:14:21 +00001782 default:
1783 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001784 }
1785
Victor Stinner03490912011-10-03 23:45:12 +02001786 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001788 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001789 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001790 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1791 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001792
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001793 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001794}
1795
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001796#ifdef Py_DEBUG
1797static int
1798unicode_is_singleton(PyObject *unicode)
1799{
1800 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1801 if (unicode == unicode_empty)
1802 return 1;
1803 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1804 {
1805 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1806 if (ch < 256 && unicode_latin1[ch] == unicode)
1807 return 1;
1808 }
1809 return 0;
1810}
1811#endif
1812
Alexander Belopolsky40018472011-02-26 01:02:56 +00001813static int
Victor Stinner488fa492011-12-12 00:01:39 +01001814unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001815{
Victor Stinner488fa492011-12-12 00:01:39 +01001816 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001817 if (Py_REFCNT(unicode) != 1)
1818 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001819 if (_PyUnicode_HASH(unicode) != -1)
1820 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001821 if (PyUnicode_CHECK_INTERNED(unicode))
1822 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001823 if (!PyUnicode_CheckExact(unicode))
1824 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001825#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001826 /* singleton refcount is greater than 1 */
1827 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001828#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001829 return 1;
1830}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001831
Victor Stinnerfe226c02011-10-03 03:52:20 +02001832static int
1833unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1834{
1835 PyObject *unicode;
1836 Py_ssize_t old_length;
1837
1838 assert(p_unicode != NULL);
1839 unicode = *p_unicode;
1840
1841 assert(unicode != NULL);
1842 assert(PyUnicode_Check(unicode));
1843 assert(0 <= length);
1844
Victor Stinner910337b2011-10-03 03:20:16 +02001845 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001846 old_length = PyUnicode_WSTR_LENGTH(unicode);
1847 else
1848 old_length = PyUnicode_GET_LENGTH(unicode);
1849 if (old_length == length)
1850 return 0;
1851
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001852 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001853 _Py_INCREF_UNICODE_EMPTY();
1854 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001855 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001856 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001857 return 0;
1858 }
1859
Victor Stinner488fa492011-12-12 00:01:39 +01001860 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001861 PyObject *copy = resize_copy(unicode, length);
1862 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001863 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001864 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001865 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001866 }
1867
Victor Stinnerfe226c02011-10-03 03:52:20 +02001868 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001869 PyObject *new_unicode = resize_compact(unicode, length);
1870 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001871 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001872 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001873 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001874 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001875 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001876}
1877
Alexander Belopolsky40018472011-02-26 01:02:56 +00001878int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001879PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001880{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001881 PyObject *unicode;
1882 if (p_unicode == NULL) {
1883 PyErr_BadInternalCall();
1884 return -1;
1885 }
1886 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001887 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001888 {
1889 PyErr_BadInternalCall();
1890 return -1;
1891 }
1892 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001893}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001894
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001895/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001896
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001897 WARNING: The function doesn't copy the terminating null character and
1898 doesn't check the maximum character (may write a latin1 character in an
1899 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001900static void
1901unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1902 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001903{
1904 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1905 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001906 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001907
1908 switch (kind) {
1909 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001910 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001911#ifdef Py_DEBUG
1912 if (PyUnicode_IS_ASCII(unicode)) {
1913 Py_UCS4 maxchar = ucs1lib_find_max_char(
1914 (const Py_UCS1*)str,
1915 (const Py_UCS1*)str + len);
1916 assert(maxchar < 128);
1917 }
1918#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001919 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001920 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001921 }
1922 case PyUnicode_2BYTE_KIND: {
1923 Py_UCS2 *start = (Py_UCS2 *)data + index;
1924 Py_UCS2 *ucs2 = start;
1925 assert(index <= PyUnicode_GET_LENGTH(unicode));
1926
Victor Stinner184252a2012-06-16 02:57:41 +02001927 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001928 *ucs2 = (Py_UCS2)*str;
1929
1930 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001931 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001932 }
1933 default: {
1934 Py_UCS4 *start = (Py_UCS4 *)data + index;
1935 Py_UCS4 *ucs4 = start;
1936 assert(kind == PyUnicode_4BYTE_KIND);
1937 assert(index <= PyUnicode_GET_LENGTH(unicode));
1938
Victor Stinner184252a2012-06-16 02:57:41 +02001939 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001940 *ucs4 = (Py_UCS4)*str;
1941
1942 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001943 }
1944 }
1945}
1946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001947static PyObject*
1948get_latin1_char(unsigned char ch)
1949{
Victor Stinnera464fc12011-10-02 20:39:30 +02001950 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001951 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001952 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 if (!unicode)
1954 return NULL;
1955 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001956 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001957 unicode_latin1[ch] = unicode;
1958 }
1959 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001960 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001961}
1962
Victor Stinner985a82a2014-01-03 12:53:47 +01001963static PyObject*
1964unicode_char(Py_UCS4 ch)
1965{
1966 PyObject *unicode;
1967
1968 assert(ch <= MAX_UNICODE);
1969
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001970 if (ch < 256)
1971 return get_latin1_char(ch);
1972
Victor Stinner985a82a2014-01-03 12:53:47 +01001973 unicode = PyUnicode_New(1, ch);
1974 if (unicode == NULL)
1975 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001976
1977 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1978 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01001979 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001980 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01001981 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1982 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1983 }
1984 assert(_PyUnicode_CheckConsistency(unicode, 1));
1985 return unicode;
1986}
1987
Alexander Belopolsky40018472011-02-26 01:02:56 +00001988PyObject *
1989PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001990{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02001991 if (u == NULL)
1992 return (PyObject*)_PyUnicode_New(size);
1993
1994 if (size < 0) {
1995 PyErr_BadInternalCall();
1996 return NULL;
1997 }
1998
1999 return PyUnicode_FromWideChar(u, size);
2000}
2001
2002PyObject *
2003PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2004{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002005 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002006 Py_UCS4 maxchar = 0;
2007 Py_ssize_t num_surrogates;
2008
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002009 if (u == NULL && size != 0) {
2010 PyErr_BadInternalCall();
2011 return NULL;
2012 }
2013
2014 if (size == -1) {
2015 size = wcslen(u);
2016 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002017
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002018 /* If the Unicode data is known at construction time, we can apply
2019 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002020
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002021 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002022 if (size == 0)
2023 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002025 /* Single character Unicode objects in the Latin-1 range are
2026 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002027 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002028 return get_latin1_char((unsigned char)*u);
2029
2030 /* If not empty and not single character, copy the Unicode data
2031 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002032 if (find_maxchar_surrogates(u, u + size,
2033 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 return NULL;
2035
Victor Stinner8faf8212011-12-08 22:14:11 +01002036 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002037 if (!unicode)
2038 return NULL;
2039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002040 switch (PyUnicode_KIND(unicode)) {
2041 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002042 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002043 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2044 break;
2045 case PyUnicode_2BYTE_KIND:
2046#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002047 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002049 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2051#endif
2052 break;
2053 case PyUnicode_4BYTE_KIND:
2054#if SIZEOF_WCHAR_T == 2
2055 /* This is the only case which has to process surrogates, thus
2056 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002057 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002058#else
2059 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002060 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002061#endif
2062 break;
2063 default:
2064 assert(0 && "Impossible state");
2065 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002066
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002067 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002068}
2069
Alexander Belopolsky40018472011-02-26 01:02:56 +00002070PyObject *
2071PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002072{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002073 if (size < 0) {
2074 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002075 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002076 return NULL;
2077 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002078 if (u != NULL)
2079 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2080 else
2081 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002082}
2083
Alexander Belopolsky40018472011-02-26 01:02:56 +00002084PyObject *
2085PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002086{
2087 size_t size = strlen(u);
2088 if (size > PY_SSIZE_T_MAX) {
2089 PyErr_SetString(PyExc_OverflowError, "input too long");
2090 return NULL;
2091 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002092 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002093}
2094
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002095PyObject *
2096_PyUnicode_FromId(_Py_Identifier *id)
2097{
2098 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002099 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2100 strlen(id->string),
2101 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002102 if (!id->object)
2103 return NULL;
2104 PyUnicode_InternInPlace(&id->object);
2105 assert(!id->next);
2106 id->next = static_strings;
2107 static_strings = id;
2108 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002109 return id->object;
2110}
2111
2112void
2113_PyUnicode_ClearStaticStrings()
2114{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002115 _Py_Identifier *tmp, *s = static_strings;
2116 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002117 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002118 tmp = s->next;
2119 s->next = NULL;
2120 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002121 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002122 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002123}
2124
Benjamin Peterson0df54292012-03-26 14:50:32 -04002125/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002126
Victor Stinnerd3f08822012-05-29 12:57:52 +02002127PyObject*
2128_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002129{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002130 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002131 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002132 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002133#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002134 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002135#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002136 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002137 }
Victor Stinner785938e2011-12-11 20:09:03 +01002138 unicode = PyUnicode_New(size, 127);
2139 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002140 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002141 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2142 assert(_PyUnicode_CheckConsistency(unicode, 1));
2143 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002144}
2145
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002146static Py_UCS4
2147kind_maxchar_limit(unsigned int kind)
2148{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002149 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002150 case PyUnicode_1BYTE_KIND:
2151 return 0x80;
2152 case PyUnicode_2BYTE_KIND:
2153 return 0x100;
2154 case PyUnicode_4BYTE_KIND:
2155 return 0x10000;
2156 default:
2157 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002158 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002159 }
2160}
2161
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -07002162static inline Py_UCS4
Victor Stinnere6abb482012-05-02 01:15:40 +02002163align_maxchar(Py_UCS4 maxchar)
2164{
2165 if (maxchar <= 127)
2166 return 127;
2167 else if (maxchar <= 255)
2168 return 255;
2169 else if (maxchar <= 65535)
2170 return 65535;
2171 else
2172 return MAX_UNICODE;
2173}
2174
Victor Stinner702c7342011-10-05 13:50:52 +02002175static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002176_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002177{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002178 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002179 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002180
Serhiy Storchaka678db842013-01-26 12:16:36 +02002181 if (size == 0)
2182 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002183 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002184 if (size == 1)
2185 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002186
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002187 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002188 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002189 if (!res)
2190 return NULL;
2191 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002192 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002193 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002194}
2195
Victor Stinnere57b1c02011-09-28 22:20:48 +02002196static PyObject*
2197_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198{
2199 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002200 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002201
Serhiy Storchaka678db842013-01-26 12:16:36 +02002202 if (size == 0)
2203 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002204 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002205 if (size == 1)
2206 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002207
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002208 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002209 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002210 if (!res)
2211 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002212 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002213 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002214 else {
2215 _PyUnicode_CONVERT_BYTES(
2216 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2217 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002218 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002219 return res;
2220}
2221
Victor Stinnere57b1c02011-09-28 22:20:48 +02002222static PyObject*
2223_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002224{
2225 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002226 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002227
Serhiy Storchaka678db842013-01-26 12:16:36 +02002228 if (size == 0)
2229 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002230 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002231 if (size == 1)
2232 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002233
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002234 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002235 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002236 if (!res)
2237 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002238 if (max_char < 256)
2239 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2240 PyUnicode_1BYTE_DATA(res));
2241 else if (max_char < 0x10000)
2242 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2243 PyUnicode_2BYTE_DATA(res));
2244 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002245 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002246 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247 return res;
2248}
2249
2250PyObject*
2251PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2252{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002253 if (size < 0) {
2254 PyErr_SetString(PyExc_ValueError, "size must be positive");
2255 return NULL;
2256 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002257 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002258 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002259 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002260 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002261 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002262 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002263 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002264 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002265 PyErr_SetString(PyExc_SystemError, "invalid kind");
2266 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002268}
2269
Victor Stinnerece58de2012-04-23 23:36:38 +02002270Py_UCS4
2271_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2272{
2273 enum PyUnicode_Kind kind;
2274 void *startptr, *endptr;
2275
2276 assert(PyUnicode_IS_READY(unicode));
2277 assert(0 <= start);
2278 assert(end <= PyUnicode_GET_LENGTH(unicode));
2279 assert(start <= end);
2280
2281 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2282 return PyUnicode_MAX_CHAR_VALUE(unicode);
2283
2284 if (start == end)
2285 return 127;
2286
Victor Stinner94d558b2012-04-27 22:26:58 +02002287 if (PyUnicode_IS_ASCII(unicode))
2288 return 127;
2289
Victor Stinnerece58de2012-04-23 23:36:38 +02002290 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002291 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002292 endptr = (char *)startptr + end * kind;
2293 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002294 switch(kind) {
2295 case PyUnicode_1BYTE_KIND:
2296 return ucs1lib_find_max_char(startptr, endptr);
2297 case PyUnicode_2BYTE_KIND:
2298 return ucs2lib_find_max_char(startptr, endptr);
2299 case PyUnicode_4BYTE_KIND:
2300 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002301 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002302 assert(0);
2303 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002304 }
2305}
2306
Victor Stinner25a4b292011-10-06 12:31:55 +02002307/* Ensure that a string uses the most efficient storage, if it is not the
2308 case: create a new string with of the right kind. Write NULL into *p_unicode
2309 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002310static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002311unicode_adjust_maxchar(PyObject **p_unicode)
2312{
2313 PyObject *unicode, *copy;
2314 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002315 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002316 unsigned int kind;
2317
2318 assert(p_unicode != NULL);
2319 unicode = *p_unicode;
2320 assert(PyUnicode_IS_READY(unicode));
2321 if (PyUnicode_IS_ASCII(unicode))
2322 return;
2323
2324 len = PyUnicode_GET_LENGTH(unicode);
2325 kind = PyUnicode_KIND(unicode);
2326 if (kind == PyUnicode_1BYTE_KIND) {
2327 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002328 max_char = ucs1lib_find_max_char(u, u + len);
2329 if (max_char >= 128)
2330 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002331 }
2332 else if (kind == PyUnicode_2BYTE_KIND) {
2333 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002334 max_char = ucs2lib_find_max_char(u, u + len);
2335 if (max_char >= 256)
2336 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002337 }
2338 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002339 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002340 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002341 max_char = ucs4lib_find_max_char(u, u + len);
2342 if (max_char >= 0x10000)
2343 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002344 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002345 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002346 if (copy != NULL)
2347 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002348 Py_DECREF(unicode);
2349 *p_unicode = copy;
2350}
2351
Victor Stinner034f6cf2011-09-30 02:26:44 +02002352PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002353_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002354{
Victor Stinner87af4f22011-11-21 23:03:47 +01002355 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002356 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002357
Victor Stinner034f6cf2011-09-30 02:26:44 +02002358 if (!PyUnicode_Check(unicode)) {
2359 PyErr_BadInternalCall();
2360 return NULL;
2361 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002362 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002363 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002364
Victor Stinner87af4f22011-11-21 23:03:47 +01002365 length = PyUnicode_GET_LENGTH(unicode);
2366 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002367 if (!copy)
2368 return NULL;
2369 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2370
Christian Heimesf051e432016-09-13 20:22:02 +02002371 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002372 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002373 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002374 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002375}
2376
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002377
Victor Stinnerbc603d12011-10-02 01:00:40 +02002378/* Widen Unicode objects to larger buffers. Don't write terminating null
2379 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002380
2381void*
2382_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2383{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002384 Py_ssize_t len;
2385 void *result;
2386 unsigned int skind;
2387
Benjamin Petersonbac79492012-01-14 13:34:47 -05002388 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002389 return NULL;
2390
2391 len = PyUnicode_GET_LENGTH(s);
2392 skind = PyUnicode_KIND(s);
2393 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002394 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002395 return NULL;
2396 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002397 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002398 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002399 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002400 if (!result)
2401 return PyErr_NoMemory();
2402 assert(skind == PyUnicode_1BYTE_KIND);
2403 _PyUnicode_CONVERT_BYTES(
2404 Py_UCS1, Py_UCS2,
2405 PyUnicode_1BYTE_DATA(s),
2406 PyUnicode_1BYTE_DATA(s) + len,
2407 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002408 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002409 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002410 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002411 if (!result)
2412 return PyErr_NoMemory();
2413 if (skind == PyUnicode_2BYTE_KIND) {
2414 _PyUnicode_CONVERT_BYTES(
2415 Py_UCS2, Py_UCS4,
2416 PyUnicode_2BYTE_DATA(s),
2417 PyUnicode_2BYTE_DATA(s) + len,
2418 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002419 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002420 else {
2421 assert(skind == PyUnicode_1BYTE_KIND);
2422 _PyUnicode_CONVERT_BYTES(
2423 Py_UCS1, Py_UCS4,
2424 PyUnicode_1BYTE_DATA(s),
2425 PyUnicode_1BYTE_DATA(s) + len,
2426 result);
2427 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002428 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002429 default:
2430 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 }
Victor Stinner01698042011-10-04 00:04:26 +02002432 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 return NULL;
2434}
2435
2436static Py_UCS4*
2437as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2438 int copy_null)
2439{
2440 int kind;
2441 void *data;
2442 Py_ssize_t len, targetlen;
2443 if (PyUnicode_READY(string) == -1)
2444 return NULL;
2445 kind = PyUnicode_KIND(string);
2446 data = PyUnicode_DATA(string);
2447 len = PyUnicode_GET_LENGTH(string);
2448 targetlen = len;
2449 if (copy_null)
2450 targetlen++;
2451 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002452 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002453 if (!target) {
2454 PyErr_NoMemory();
2455 return NULL;
2456 }
2457 }
2458 else {
2459 if (targetsize < targetlen) {
2460 PyErr_Format(PyExc_SystemError,
2461 "string is longer than the buffer");
2462 if (copy_null && 0 < targetsize)
2463 target[0] = 0;
2464 return NULL;
2465 }
2466 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002467 if (kind == PyUnicode_1BYTE_KIND) {
2468 Py_UCS1 *start = (Py_UCS1 *) data;
2469 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002470 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002471 else if (kind == PyUnicode_2BYTE_KIND) {
2472 Py_UCS2 *start = (Py_UCS2 *) data;
2473 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2474 }
2475 else {
2476 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002477 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002479 if (copy_null)
2480 target[len] = 0;
2481 return target;
2482}
2483
2484Py_UCS4*
2485PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2486 int copy_null)
2487{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002488 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 PyErr_BadInternalCall();
2490 return NULL;
2491 }
2492 return as_ucs4(string, target, targetsize, copy_null);
2493}
2494
2495Py_UCS4*
2496PyUnicode_AsUCS4Copy(PyObject *string)
2497{
2498 return as_ucs4(string, NULL, 0, 1);
2499}
2500
Victor Stinner15a11362012-10-06 23:48:20 +02002501/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002502 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2503 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2504#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002505
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002506static int
2507unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2508 Py_ssize_t width, Py_ssize_t precision)
2509{
2510 Py_ssize_t length, fill, arglen;
2511 Py_UCS4 maxchar;
2512
2513 if (PyUnicode_READY(str) == -1)
2514 return -1;
2515
2516 length = PyUnicode_GET_LENGTH(str);
2517 if ((precision == -1 || precision >= length)
2518 && width <= length)
2519 return _PyUnicodeWriter_WriteStr(writer, str);
2520
2521 if (precision != -1)
2522 length = Py_MIN(precision, length);
2523
2524 arglen = Py_MAX(length, width);
2525 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2526 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2527 else
2528 maxchar = writer->maxchar;
2529
2530 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2531 return -1;
2532
2533 if (width > length) {
2534 fill = width - length;
2535 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2536 return -1;
2537 writer->pos += fill;
2538 }
2539
2540 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2541 str, 0, length);
2542 writer->pos += length;
2543 return 0;
2544}
2545
2546static int
2547unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2548 Py_ssize_t width, Py_ssize_t precision)
2549{
2550 /* UTF-8 */
2551 Py_ssize_t length;
2552 PyObject *unicode;
2553 int res;
2554
2555 length = strlen(str);
2556 if (precision != -1)
2557 length = Py_MIN(length, precision);
2558 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2559 if (unicode == NULL)
2560 return -1;
2561
2562 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2563 Py_DECREF(unicode);
2564 return res;
2565}
2566
Victor Stinner96865452011-03-01 23:44:09 +00002567static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002568unicode_fromformat_arg(_PyUnicodeWriter *writer,
2569 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002570{
Victor Stinnere215d962012-10-06 23:03:36 +02002571 const char *p;
2572 Py_ssize_t len;
2573 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002574 Py_ssize_t width;
2575 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002576 int longflag;
2577 int longlongflag;
2578 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002579 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002580
2581 p = f;
2582 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002583 zeropad = 0;
2584 if (*f == '0') {
2585 zeropad = 1;
2586 f++;
2587 }
Victor Stinner96865452011-03-01 23:44:09 +00002588
2589 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002590 width = -1;
2591 if (Py_ISDIGIT((unsigned)*f)) {
2592 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002593 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002594 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002596 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002597 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002598 return NULL;
2599 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002600 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002601 f++;
2602 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002603 }
2604 precision = -1;
2605 if (*f == '.') {
2606 f++;
2607 if (Py_ISDIGIT((unsigned)*f)) {
2608 precision = (*f - '0');
2609 f++;
2610 while (Py_ISDIGIT((unsigned)*f)) {
2611 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2612 PyErr_SetString(PyExc_ValueError,
2613 "precision too big");
2614 return NULL;
2615 }
2616 precision = (precision * 10) + (*f - '0');
2617 f++;
2618 }
2619 }
Victor Stinner96865452011-03-01 23:44:09 +00002620 if (*f == '%') {
2621 /* "%.3%s" => f points to "3" */
2622 f--;
2623 }
2624 }
2625 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002626 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002627 f--;
2628 }
Victor Stinner96865452011-03-01 23:44:09 +00002629
2630 /* Handle %ld, %lu, %lld and %llu. */
2631 longflag = 0;
2632 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002633 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002634 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002635 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002636 longflag = 1;
2637 ++f;
2638 }
Victor Stinner96865452011-03-01 23:44:09 +00002639 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002640 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002641 longlongflag = 1;
2642 f += 2;
2643 }
Victor Stinner96865452011-03-01 23:44:09 +00002644 }
2645 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002646 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002647 size_tflag = 1;
2648 ++f;
2649 }
Victor Stinnere215d962012-10-06 23:03:36 +02002650
2651 if (f[1] == '\0')
2652 writer->overallocate = 0;
2653
2654 switch (*f) {
2655 case 'c':
2656 {
2657 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002658 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002659 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002660 "character argument not in range(0x110000)");
2661 return NULL;
2662 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002663 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002664 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002665 break;
2666 }
2667
2668 case 'i':
2669 case 'd':
2670 case 'u':
2671 case 'x':
2672 {
2673 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002674 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002675 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002676
2677 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002678 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002679 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002680 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002681 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002682 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002683 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002684 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002685 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002686 va_arg(*vargs, size_t));
2687 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002688 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002689 va_arg(*vargs, unsigned int));
2690 }
2691 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002692 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002693 }
2694 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002695 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002696 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002697 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002698 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002699 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002700 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002701 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002702 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002703 va_arg(*vargs, Py_ssize_t));
2704 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002705 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002706 va_arg(*vargs, int));
2707 }
2708 assert(len >= 0);
2709
Victor Stinnere215d962012-10-06 23:03:36 +02002710 if (precision < len)
2711 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002712
2713 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002714 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2715 return NULL;
2716
Victor Stinnere215d962012-10-06 23:03:36 +02002717 if (width > precision) {
2718 Py_UCS4 fillchar;
2719 fill = width - precision;
2720 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002721 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2722 return NULL;
2723 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002724 }
Victor Stinner15a11362012-10-06 23:48:20 +02002725 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002726 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002727 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2728 return NULL;
2729 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002730 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002731
Victor Stinner4a587072013-11-19 12:54:53 +01002732 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2733 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002734 break;
2735 }
2736
2737 case 'p':
2738 {
2739 char number[MAX_LONG_LONG_CHARS];
2740
2741 len = sprintf(number, "%p", va_arg(*vargs, void*));
2742 assert(len >= 0);
2743
2744 /* %p is ill-defined: ensure leading 0x. */
2745 if (number[1] == 'X')
2746 number[1] = 'x';
2747 else if (number[1] != 'x') {
2748 memmove(number + 2, number,
2749 strlen(number) + 1);
2750 number[0] = '0';
2751 number[1] = 'x';
2752 len += 2;
2753 }
2754
Victor Stinner4a587072013-11-19 12:54:53 +01002755 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002756 return NULL;
2757 break;
2758 }
2759
2760 case 's':
2761 {
2762 /* UTF-8 */
2763 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002764 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002765 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002766 break;
2767 }
2768
2769 case 'U':
2770 {
2771 PyObject *obj = va_arg(*vargs, PyObject *);
2772 assert(obj && _PyUnicode_CHECK(obj));
2773
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002774 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002775 return NULL;
2776 break;
2777 }
2778
2779 case 'V':
2780 {
2781 PyObject *obj = va_arg(*vargs, PyObject *);
2782 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002783 if (obj) {
2784 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002785 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002786 return NULL;
2787 }
2788 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002789 assert(str != NULL);
2790 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002791 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002792 }
2793 break;
2794 }
2795
2796 case 'S':
2797 {
2798 PyObject *obj = va_arg(*vargs, PyObject *);
2799 PyObject *str;
2800 assert(obj);
2801 str = PyObject_Str(obj);
2802 if (!str)
2803 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002804 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002805 Py_DECREF(str);
2806 return NULL;
2807 }
2808 Py_DECREF(str);
2809 break;
2810 }
2811
2812 case 'R':
2813 {
2814 PyObject *obj = va_arg(*vargs, PyObject *);
2815 PyObject *repr;
2816 assert(obj);
2817 repr = PyObject_Repr(obj);
2818 if (!repr)
2819 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002820 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002821 Py_DECREF(repr);
2822 return NULL;
2823 }
2824 Py_DECREF(repr);
2825 break;
2826 }
2827
2828 case 'A':
2829 {
2830 PyObject *obj = va_arg(*vargs, PyObject *);
2831 PyObject *ascii;
2832 assert(obj);
2833 ascii = PyObject_ASCII(obj);
2834 if (!ascii)
2835 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002836 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002837 Py_DECREF(ascii);
2838 return NULL;
2839 }
2840 Py_DECREF(ascii);
2841 break;
2842 }
2843
2844 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002845 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002846 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002847 break;
2848
2849 default:
2850 /* if we stumble upon an unknown formatting code, copy the rest
2851 of the format string to the output string. (we cannot just
2852 skip the code, since there's no way to know what's in the
2853 argument list) */
2854 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002855 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002856 return NULL;
2857 f = p+len;
2858 return f;
2859 }
2860
2861 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002862 return f;
2863}
2864
Walter Dörwaldd2034312007-05-18 16:29:38 +00002865PyObject *
2866PyUnicode_FromFormatV(const char *format, va_list vargs)
2867{
Victor Stinnere215d962012-10-06 23:03:36 +02002868 va_list vargs2;
2869 const char *f;
2870 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002871
Victor Stinner8f674cc2013-04-17 23:02:17 +02002872 _PyUnicodeWriter_Init(&writer);
2873 writer.min_length = strlen(format) + 100;
2874 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002875
Benjamin Peterson0c212142016-09-20 20:39:33 -07002876 // Copy varags to be able to pass a reference to a subfunction.
2877 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002878
2879 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002880 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002881 f = unicode_fromformat_arg(&writer, f, &vargs2);
2882 if (f == NULL)
2883 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002884 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002885 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002886 const char *p;
2887 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002888
Victor Stinnere215d962012-10-06 23:03:36 +02002889 p = f;
2890 do
2891 {
2892 if ((unsigned char)*p > 127) {
2893 PyErr_Format(PyExc_ValueError,
2894 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2895 "string, got a non-ASCII byte: 0x%02x",
2896 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002897 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002898 }
2899 p++;
2900 }
2901 while (*p != '\0' && *p != '%');
2902 len = p - f;
2903
2904 if (*p == '\0')
2905 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002906
2907 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002908 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002909
2910 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002911 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002912 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002913 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002914 return _PyUnicodeWriter_Finish(&writer);
2915
2916 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002917 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002918 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002919 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002920}
2921
Walter Dörwaldd2034312007-05-18 16:29:38 +00002922PyObject *
2923PyUnicode_FromFormat(const char *format, ...)
2924{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002925 PyObject* ret;
2926 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002927
2928#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002929 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002930#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002931 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002932#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002933 ret = PyUnicode_FromFormatV(format, vargs);
2934 va_end(vargs);
2935 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002936}
2937
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002938#ifdef HAVE_WCHAR_H
2939
Victor Stinner5593d8a2010-10-02 11:11:27 +00002940/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2941 convert a Unicode object to a wide character string.
2942
Victor Stinnerd88d9832011-09-06 02:00:05 +02002943 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002944 character) required to convert the unicode object. Ignore size argument.
2945
Victor Stinnerd88d9832011-09-06 02:00:05 +02002946 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002947 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002948 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002949static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002950unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002951 wchar_t *w,
2952 Py_ssize_t size)
2953{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002954 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002955 const wchar_t *wstr;
2956
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002957 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002958 if (wstr == NULL)
2959 return -1;
2960
Victor Stinner5593d8a2010-10-02 11:11:27 +00002961 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002962 if (size > res)
2963 size = res + 1;
2964 else
2965 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002966 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002967 return res;
2968 }
2969 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002970 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002971}
2972
2973Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002974PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002975 wchar_t *w,
2976 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002977{
2978 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002979 PyErr_BadInternalCall();
2980 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002981 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002982 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002983}
2984
Victor Stinner137c34c2010-09-29 10:25:54 +00002985wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002986PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002987 Py_ssize_t *size)
2988{
2989 wchar_t* buffer;
2990 Py_ssize_t buflen;
2991
2992 if (unicode == NULL) {
2993 PyErr_BadInternalCall();
2994 return NULL;
2995 }
2996
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002997 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002998 if (buflen == -1)
2999 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003000 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00003001 if (buffer == NULL) {
3002 PyErr_NoMemory();
3003 return NULL;
3004 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003005 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02003006 if (buflen == -1) {
3007 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003008 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02003009 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00003010 if (size != NULL)
3011 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003012 return buffer;
3013}
3014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003015#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003016
Alexander Belopolsky40018472011-02-26 01:02:56 +00003017PyObject *
3018PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003019{
Victor Stinner8faf8212011-12-08 22:14:11 +01003020 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003021 PyErr_SetString(PyExc_ValueError,
3022 "chr() arg not in range(0x110000)");
3023 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003024 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003025
Victor Stinner985a82a2014-01-03 12:53:47 +01003026 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003027}
3028
Alexander Belopolsky40018472011-02-26 01:02:56 +00003029PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003030PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003031{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003032 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003033 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003034 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003035 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003036 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003037 Py_INCREF(obj);
3038 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003039 }
3040 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003041 /* For a Unicode subtype that's not a Unicode object,
3042 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003043 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003044 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003045 PyErr_Format(PyExc_TypeError,
3046 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003047 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003048 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003049}
3050
Alexander Belopolsky40018472011-02-26 01:02:56 +00003051PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003052PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003053 const char *encoding,
3054 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003055{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003056 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003057 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003058
Guido van Rossumd57fd912000-03-10 22:53:23 +00003059 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003060 PyErr_BadInternalCall();
3061 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003062 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003063
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003064 /* Decoding bytes objects is the most common case and should be fast */
3065 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003066 if (PyBytes_GET_SIZE(obj) == 0)
3067 _Py_RETURN_UNICODE_EMPTY();
3068 v = PyUnicode_Decode(
3069 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3070 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003071 return v;
3072 }
3073
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003074 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003075 PyErr_SetString(PyExc_TypeError,
3076 "decoding str is not supported");
3077 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003078 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003079
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003080 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3081 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3082 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003083 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003084 Py_TYPE(obj)->tp_name);
3085 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003086 }
Tim Petersced69f82003-09-16 20:30:58 +00003087
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003088 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003089 PyBuffer_Release(&buffer);
3090 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003091 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003092
Serhiy Storchaka05997252013-01-26 12:14:02 +02003093 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003094 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003095 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003096}
3097
Victor Stinnerebe17e02016-10-12 13:57:45 +02003098/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3099 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3100 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003101int
3102_Py_normalize_encoding(const char *encoding,
3103 char *lower,
3104 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003105{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003106 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003107 char *l;
3108 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003109 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003110
Victor Stinner942889a2016-09-05 15:40:10 -07003111 assert(encoding != NULL);
3112
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003113 e = encoding;
3114 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003115 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003116 punct = 0;
3117 while (1) {
3118 char c = *e;
3119 if (c == 0) {
3120 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003121 }
Victor Stinner942889a2016-09-05 15:40:10 -07003122
3123 if (Py_ISALNUM(c) || c == '.') {
3124 if (punct && l != lower) {
3125 if (l == l_end) {
3126 return 0;
3127 }
3128 *l++ = '_';
3129 }
3130 punct = 0;
3131
3132 if (l == l_end) {
3133 return 0;
3134 }
3135 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003136 }
3137 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003138 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003139 }
Victor Stinner942889a2016-09-05 15:40:10 -07003140
3141 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003142 }
3143 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003144 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003145}
3146
Alexander Belopolsky40018472011-02-26 01:02:56 +00003147PyObject *
3148PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003149 Py_ssize_t size,
3150 const char *encoding,
3151 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003152{
3153 PyObject *buffer = NULL, *unicode;
3154 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003155 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3156
3157 if (encoding == NULL) {
3158 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3159 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003160
Fred Drakee4315f52000-05-09 19:53:39 +00003161 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003162 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3163 char *lower = buflower;
3164
3165 /* Fast paths */
3166 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3167 lower += 3;
3168 if (*lower == '_') {
3169 /* Match "utf8" and "utf_8" */
3170 lower++;
3171 }
3172
3173 if (lower[0] == '8' && lower[1] == 0) {
3174 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3175 }
3176 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3177 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3178 }
3179 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3180 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3181 }
3182 }
3183 else {
3184 if (strcmp(lower, "ascii") == 0
3185 || strcmp(lower, "us_ascii") == 0) {
3186 return PyUnicode_DecodeASCII(s, size, errors);
3187 }
Steve Dowercc16be82016-09-08 10:35:16 -07003188 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003189 else if (strcmp(lower, "mbcs") == 0) {
3190 return PyUnicode_DecodeMBCS(s, size, errors);
3191 }
3192 #endif
3193 else if (strcmp(lower, "latin1") == 0
3194 || strcmp(lower, "latin_1") == 0
3195 || strcmp(lower, "iso_8859_1") == 0
3196 || strcmp(lower, "iso8859_1") == 0) {
3197 return PyUnicode_DecodeLatin1(s, size, errors);
3198 }
3199 }
Victor Stinner37296e82010-06-10 13:36:23 +00003200 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003201
3202 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003203 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003204 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003205 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003206 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003207 if (buffer == NULL)
3208 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003209 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003210 if (unicode == NULL)
3211 goto onError;
3212 if (!PyUnicode_Check(unicode)) {
3213 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003214 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3215 "use codecs.decode() to decode to arbitrary types",
3216 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003217 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003218 Py_DECREF(unicode);
3219 goto onError;
3220 }
3221 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003222 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003223
Benjamin Peterson29060642009-01-31 22:14:21 +00003224 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003225 Py_XDECREF(buffer);
3226 return NULL;
3227}
3228
Alexander Belopolsky40018472011-02-26 01:02:56 +00003229PyObject *
3230PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003231 const char *encoding,
3232 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003233{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003234 if (!PyUnicode_Check(unicode)) {
3235 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003236 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003237 }
3238
Serhiy Storchaka00939072016-10-27 21:05:49 +03003239 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3240 "PyUnicode_AsDecodedObject() is deprecated; "
3241 "use PyCodec_Decode() to decode from str", 1) < 0)
3242 return NULL;
3243
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003244 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003245 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003246
3247 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003248 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003249}
3250
Alexander Belopolsky40018472011-02-26 01:02:56 +00003251PyObject *
3252PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003253 const char *encoding,
3254 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003255{
3256 PyObject *v;
3257
3258 if (!PyUnicode_Check(unicode)) {
3259 PyErr_BadArgument();
3260 goto onError;
3261 }
3262
Serhiy Storchaka00939072016-10-27 21:05:49 +03003263 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3264 "PyUnicode_AsDecodedUnicode() is deprecated; "
3265 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3266 return NULL;
3267
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003268 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003269 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003270
3271 /* Decode via the codec registry */
3272 v = PyCodec_Decode(unicode, encoding, errors);
3273 if (v == NULL)
3274 goto onError;
3275 if (!PyUnicode_Check(v)) {
3276 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003277 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3278 "use codecs.decode() to decode to arbitrary types",
3279 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003280 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003281 Py_DECREF(v);
3282 goto onError;
3283 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003284 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003285
Benjamin Peterson29060642009-01-31 22:14:21 +00003286 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003287 return NULL;
3288}
3289
Alexander Belopolsky40018472011-02-26 01:02:56 +00003290PyObject *
3291PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003292 Py_ssize_t size,
3293 const char *encoding,
3294 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003295{
3296 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003297
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003298 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003299 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003300 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003301 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3302 Py_DECREF(unicode);
3303 return v;
3304}
3305
Alexander Belopolsky40018472011-02-26 01:02:56 +00003306PyObject *
3307PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003308 const char *encoding,
3309 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003310{
3311 PyObject *v;
3312
3313 if (!PyUnicode_Check(unicode)) {
3314 PyErr_BadArgument();
3315 goto onError;
3316 }
3317
Serhiy Storchaka00939072016-10-27 21:05:49 +03003318 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3319 "PyUnicode_AsEncodedObject() is deprecated; "
3320 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3321 "or PyCodec_Encode() for generic encoding", 1) < 0)
3322 return NULL;
3323
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003324 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003325 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003326
3327 /* Encode via the codec registry */
3328 v = PyCodec_Encode(unicode, encoding, errors);
3329 if (v == NULL)
3330 goto onError;
3331 return v;
3332
Benjamin Peterson29060642009-01-31 22:14:21 +00003333 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003334 return NULL;
3335}
3336
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003337static size_t
3338wcstombs_errorpos(const wchar_t *wstr)
3339{
3340 size_t len;
3341#if SIZEOF_WCHAR_T == 2
3342 wchar_t buf[3];
3343#else
3344 wchar_t buf[2];
3345#endif
3346 char outbuf[MB_LEN_MAX];
3347 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003348
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003349#if SIZEOF_WCHAR_T == 2
3350 buf[2] = 0;
3351#else
3352 buf[1] = 0;
3353#endif
3354 start = wstr;
3355 while (*wstr != L'\0')
3356 {
3357 previous = wstr;
3358#if SIZEOF_WCHAR_T == 2
3359 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3360 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3361 {
3362 buf[0] = wstr[0];
3363 buf[1] = wstr[1];
3364 wstr += 2;
3365 }
3366 else {
3367 buf[0] = *wstr;
3368 buf[1] = 0;
3369 wstr++;
3370 }
3371#else
3372 buf[0] = *wstr;
3373 wstr++;
3374#endif
3375 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003376 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003377 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003378 }
3379
3380 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003381 return 0;
3382}
3383
Victor Stinner1b579672011-12-17 05:47:23 +01003384static int
3385locale_error_handler(const char *errors, int *surrogateescape)
3386{
Victor Stinner50149202015-09-22 00:26:54 +02003387 _Py_error_handler error_handler = get_error_handler(errors);
3388 switch (error_handler)
3389 {
3390 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003391 *surrogateescape = 0;
3392 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003393 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003394 *surrogateescape = 1;
3395 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003396 default:
3397 PyErr_Format(PyExc_ValueError,
3398 "only 'strict' and 'surrogateescape' error handlers "
3399 "are supported, not '%s'",
3400 errors);
3401 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003402 }
Victor Stinner1b579672011-12-17 05:47:23 +01003403}
3404
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003405PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003406PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003407{
3408 Py_ssize_t wlen, wlen2;
3409 wchar_t *wstr;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003410 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003411 PyObject *bytes, *reason, *exc;
3412 size_t error_pos, errlen;
Victor Stinner1b579672011-12-17 05:47:23 +01003413 int surrogateescape;
3414
3415 if (locale_error_handler(errors, &surrogateescape) < 0)
3416 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003417
3418 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3419 if (wstr == NULL)
3420 return NULL;
3421
3422 wlen2 = wcslen(wstr);
3423 if (wlen2 != wlen) {
3424 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003425 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003426 return NULL;
3427 }
3428
3429 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003430 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003431 char *str;
3432
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003433 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003434 if (str == NULL) {
3435 if (error_pos == (size_t)-1) {
3436 PyErr_NoMemory();
3437 PyMem_Free(wstr);
3438 return NULL;
3439 }
3440 else {
3441 goto encode_error;
3442 }
3443 }
3444 PyMem_Free(wstr);
3445
3446 bytes = PyBytes_FromString(str);
3447 PyMem_Free(str);
3448 }
3449 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003450 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003451 size_t len, len2;
3452
3453 len = wcstombs(NULL, wstr, 0);
3454 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003455 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003456 goto encode_error;
3457 }
3458
3459 bytes = PyBytes_FromStringAndSize(NULL, len);
3460 if (bytes == NULL) {
3461 PyMem_Free(wstr);
3462 return NULL;
3463 }
3464
3465 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3466 if (len2 == (size_t)-1 || len2 > len) {
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003467 Py_DECREF(bytes);
Victor Stinner2f197072011-12-17 07:08:30 +01003468 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003469 goto encode_error;
3470 }
3471 PyMem_Free(wstr);
3472 }
3473 return bytes;
3474
3475encode_error:
3476 errmsg = strerror(errno);
3477 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003478
3479 if (error_pos == (size_t)-1)
3480 error_pos = wcstombs_errorpos(wstr);
3481
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003482 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003483
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003484 wstr = Py_DecodeLocale(errmsg, &errlen);
3485 if (wstr != NULL) {
3486 reason = PyUnicode_FromWideChar(wstr, errlen);
3487 PyMem_RawFree(wstr);
3488 } else {
3489 errmsg = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003490 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003491
Victor Stinner2f197072011-12-17 07:08:30 +01003492 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003493 reason = PyUnicode_FromString(
3494 "wcstombs() encountered an unencodable "
3495 "wide character");
3496 if (reason == NULL)
3497 return NULL;
3498
3499 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3500 "locale", unicode,
3501 (Py_ssize_t)error_pos,
3502 (Py_ssize_t)(error_pos+1),
3503 reason);
3504 Py_DECREF(reason);
3505 if (exc != NULL) {
3506 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003507 Py_DECREF(exc);
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003508 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003509 return NULL;
3510}
3511
Victor Stinnerad158722010-10-27 00:25:46 +00003512PyObject *
3513PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003514{
Steve Dowercc16be82016-09-08 10:35:16 -07003515#if defined(__APPLE__)
3516 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003517#else
Victor Stinner793b5312011-04-27 00:24:21 +02003518 PyInterpreterState *interp = PyThreadState_GET()->interp;
3519 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3520 cannot use it to encode and decode filenames before it is loaded. Load
3521 the Python codec requires to encode at least its own filename. Use the C
3522 version of the locale codec until the codec registry is initialized and
3523 the Python codec is loaded.
3524
3525 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3526 cannot only rely on it: check also interp->fscodec_initialized for
3527 subinterpreters. */
3528 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003529 return PyUnicode_AsEncodedString(unicode,
3530 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003531 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003532 }
3533 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003534 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003535 }
Victor Stinnerad158722010-10-27 00:25:46 +00003536#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003537}
3538
Alexander Belopolsky40018472011-02-26 01:02:56 +00003539PyObject *
3540PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003541 const char *encoding,
3542 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003543{
3544 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003545 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003546
Guido van Rossumd57fd912000-03-10 22:53:23 +00003547 if (!PyUnicode_Check(unicode)) {
3548 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003549 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003550 }
Fred Drakee4315f52000-05-09 19:53:39 +00003551
Victor Stinner942889a2016-09-05 15:40:10 -07003552 if (encoding == NULL) {
3553 return _PyUnicode_AsUTF8String(unicode, errors);
3554 }
3555
Fred Drakee4315f52000-05-09 19:53:39 +00003556 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003557 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3558 char *lower = buflower;
3559
3560 /* Fast paths */
3561 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3562 lower += 3;
3563 if (*lower == '_') {
3564 /* Match "utf8" and "utf_8" */
3565 lower++;
3566 }
3567
3568 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003569 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003570 }
3571 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3572 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3573 }
3574 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3575 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3576 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003577 }
Victor Stinner942889a2016-09-05 15:40:10 -07003578 else {
3579 if (strcmp(lower, "ascii") == 0
3580 || strcmp(lower, "us_ascii") == 0) {
3581 return _PyUnicode_AsASCIIString(unicode, errors);
3582 }
Steve Dowercc16be82016-09-08 10:35:16 -07003583#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003584 else if (strcmp(lower, "mbcs") == 0) {
3585 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3586 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003587#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003588 else if (strcmp(lower, "latin1") == 0 ||
3589 strcmp(lower, "latin_1") == 0 ||
3590 strcmp(lower, "iso_8859_1") == 0 ||
3591 strcmp(lower, "iso8859_1") == 0) {
3592 return _PyUnicode_AsLatin1String(unicode, errors);
3593 }
3594 }
Victor Stinner37296e82010-06-10 13:36:23 +00003595 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003596
3597 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003598 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003599 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003600 return NULL;
3601
3602 /* The normal path */
3603 if (PyBytes_Check(v))
3604 return v;
3605
3606 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003607 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003608 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003609 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003610
3611 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003612 "encoder %s returned bytearray instead of bytes; "
3613 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003614 encoding);
3615 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003616 Py_DECREF(v);
3617 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003618 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003619
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003620 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3621 Py_DECREF(v);
3622 return b;
3623 }
3624
3625 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003626 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3627 "use codecs.encode() to encode to arbitrary types",
3628 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003629 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003630 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003631 return NULL;
3632}
3633
Alexander Belopolsky40018472011-02-26 01:02:56 +00003634PyObject *
3635PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003636 const char *encoding,
3637 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003638{
3639 PyObject *v;
3640
3641 if (!PyUnicode_Check(unicode)) {
3642 PyErr_BadArgument();
3643 goto onError;
3644 }
3645
Serhiy Storchaka00939072016-10-27 21:05:49 +03003646 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3647 "PyUnicode_AsEncodedUnicode() is deprecated; "
3648 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3649 return NULL;
3650
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003651 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003652 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003653
3654 /* Encode via the codec registry */
3655 v = PyCodec_Encode(unicode, encoding, errors);
3656 if (v == NULL)
3657 goto onError;
3658 if (!PyUnicode_Check(v)) {
3659 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003660 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3661 "use codecs.encode() to encode to arbitrary types",
3662 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003663 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003664 Py_DECREF(v);
3665 goto onError;
3666 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003667 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003668
Benjamin Peterson29060642009-01-31 22:14:21 +00003669 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003670 return NULL;
3671}
3672
Victor Stinner2f197072011-12-17 07:08:30 +01003673static size_t
3674mbstowcs_errorpos(const char *str, size_t len)
3675{
3676#ifdef HAVE_MBRTOWC
3677 const char *start = str;
3678 mbstate_t mbs;
3679 size_t converted;
3680 wchar_t ch;
3681
3682 memset(&mbs, 0, sizeof mbs);
3683 while (len)
3684 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003685 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003686 if (converted == 0)
3687 /* Reached end of string */
3688 break;
3689 if (converted == (size_t)-1 || converted == (size_t)-2) {
3690 /* Conversion error or incomplete character */
3691 return str - start;
3692 }
3693 else {
3694 str += converted;
3695 len -= converted;
3696 }
3697 }
3698 /* failed to find the undecodable byte sequence */
3699 return 0;
3700#endif
3701 return 0;
3702}
3703
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003704PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003705PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003706 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003707{
3708 wchar_t smallbuf[256];
3709 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3710 wchar_t *wstr;
3711 size_t wlen, wlen2;
3712 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003713 int surrogateescape;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003714 size_t error_pos, errlen;
Victor Stinner2f197072011-12-17 07:08:30 +01003715 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003716 PyObject *exc, *reason = NULL; /* initialize to prevent gcc warning */
Victor Stinner1b579672011-12-17 05:47:23 +01003717
3718 if (locale_error_handler(errors, &surrogateescape) < 0)
3719 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003720
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003721 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3722 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003723 return NULL;
3724 }
3725
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003726 if (surrogateescape) {
3727 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003728 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003729 if (wstr == NULL) {
3730 if (wlen == (size_t)-1)
3731 PyErr_NoMemory();
3732 else
3733 PyErr_SetFromErrno(PyExc_OSError);
3734 return NULL;
3735 }
3736
3737 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003738 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003739 }
3740 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003741 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003742#ifndef HAVE_BROKEN_MBSTOWCS
3743 wlen = mbstowcs(NULL, str, 0);
3744#else
3745 wlen = len;
3746#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003747 if (wlen == (size_t)-1)
3748 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003749 if (wlen+1 <= smallbuf_len) {
3750 wstr = smallbuf;
3751 }
3752 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003753 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003754 if (!wstr)
3755 return PyErr_NoMemory();
3756 }
3757
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003758 wlen2 = mbstowcs(wstr, str, wlen+1);
3759 if (wlen2 == (size_t)-1) {
3760 if (wstr != smallbuf)
3761 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003762 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003763 }
3764#ifdef HAVE_BROKEN_MBSTOWCS
3765 assert(wlen2 == wlen);
3766#endif
3767 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3768 if (wstr != smallbuf)
3769 PyMem_Free(wstr);
3770 }
3771 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003772
3773decode_error:
3774 errmsg = strerror(errno);
3775 assert(errmsg != NULL);
3776
3777 error_pos = mbstowcs_errorpos(str, len);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003778 wstr = Py_DecodeLocale(errmsg, &errlen);
3779 if (wstr != NULL) {
3780 reason = PyUnicode_FromWideChar(wstr, errlen);
3781 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003782 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003783
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003784 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003785 reason = PyUnicode_FromString(
3786 "mbstowcs() encountered an invalid multibyte sequence");
3787 if (reason == NULL)
3788 return NULL;
3789
3790 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3791 "locale", str, len,
3792 (Py_ssize_t)error_pos,
3793 (Py_ssize_t)(error_pos+1),
3794 reason);
3795 Py_DECREF(reason);
3796 if (exc != NULL) {
3797 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003798 Py_DECREF(exc);
Victor Stinner2f197072011-12-17 07:08:30 +01003799 }
3800 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003801}
3802
3803PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003804PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003805{
3806 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003807 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003808}
3809
3810
3811PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003812PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003813 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003814 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3815}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003816
Christian Heimes5894ba72007-11-04 11:43:14 +00003817PyObject*
3818PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3819{
Steve Dowercc16be82016-09-08 10:35:16 -07003820#if defined(__APPLE__)
3821 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003822#else
Victor Stinner793b5312011-04-27 00:24:21 +02003823 PyInterpreterState *interp = PyThreadState_GET()->interp;
3824 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3825 cannot use it to encode and decode filenames before it is loaded. Load
3826 the Python codec requires to encode at least its own filename. Use the C
3827 version of the locale codec until the codec registry is initialized and
3828 the Python codec is loaded.
3829
3830 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3831 cannot only rely on it: check also interp->fscodec_initialized for
3832 subinterpreters. */
3833 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003834 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003835 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003836 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003837 }
3838 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003839 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003840 }
Victor Stinnerad158722010-10-27 00:25:46 +00003841#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003842}
3843
Martin v. Löwis011e8422009-05-05 04:43:17 +00003844
3845int
3846PyUnicode_FSConverter(PyObject* arg, void* addr)
3847{
Brett Cannonec6ce872016-09-06 15:50:29 -07003848 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003849 PyObject *output = NULL;
3850 Py_ssize_t size;
3851 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003852 if (arg == NULL) {
3853 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003854 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003855 return 1;
3856 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003857 path = PyOS_FSPath(arg);
3858 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003859 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003860 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003861 if (PyBytes_Check(path)) {
3862 output = path;
3863 }
3864 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3865 output = PyUnicode_EncodeFSDefault(path);
3866 Py_DECREF(path);
3867 if (!output) {
3868 return 0;
3869 }
3870 assert(PyBytes_Check(output));
3871 }
3872
Victor Stinner0ea2a462010-04-30 00:22:08 +00003873 size = PyBytes_GET_SIZE(output);
3874 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003875 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003876 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003877 Py_DECREF(output);
3878 return 0;
3879 }
3880 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003881 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003882}
3883
3884
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003885int
3886PyUnicode_FSDecoder(PyObject* arg, void* addr)
3887{
Brett Cannona5711202016-09-06 19:36:01 -07003888 int is_buffer = 0;
3889 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003890 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003891 if (arg == NULL) {
3892 Py_DECREF(*(PyObject**)addr);
3893 return 1;
3894 }
Brett Cannona5711202016-09-06 19:36:01 -07003895
3896 is_buffer = PyObject_CheckBuffer(arg);
3897 if (!is_buffer) {
3898 path = PyOS_FSPath(arg);
3899 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003900 return 0;
3901 }
Brett Cannona5711202016-09-06 19:36:01 -07003902 }
3903 else {
3904 path = arg;
3905 Py_INCREF(arg);
3906 }
3907
3908 if (PyUnicode_Check(path)) {
3909 if (PyUnicode_READY(path) == -1) {
3910 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003911 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003912 }
3913 output = path;
3914 }
3915 else if (PyBytes_Check(path) || is_buffer) {
3916 PyObject *path_bytes = NULL;
3917
3918 if (!PyBytes_Check(path) &&
3919 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3920 "path should be string, bytes, or os.PathLike, not %.200s",
3921 Py_TYPE(arg)->tp_name)) {
3922 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003923 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003924 }
3925 path_bytes = PyBytes_FromObject(path);
3926 Py_DECREF(path);
3927 if (!path_bytes) {
3928 return 0;
3929 }
3930 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3931 PyBytes_GET_SIZE(path_bytes));
3932 Py_DECREF(path_bytes);
3933 if (!output) {
3934 return 0;
3935 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003936 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003937 else {
3938 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003939 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003940 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003941 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003942 return 0;
3943 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003944 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003945 Py_DECREF(output);
3946 return 0;
3947 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003948 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003949 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003950 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003951 Py_DECREF(output);
3952 return 0;
3953 }
3954 *(PyObject**)addr = output;
3955 return Py_CLEANUP_SUPPORTED;
3956}
3957
3958
Martin v. Löwis5b222132007-06-10 09:51:05 +00003959char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003960PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003961{
Christian Heimesf3863112007-11-22 07:46:41 +00003962 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003963
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003964 if (!PyUnicode_Check(unicode)) {
3965 PyErr_BadArgument();
3966 return NULL;
3967 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003968 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003969 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003970
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003971 if (PyUnicode_UTF8(unicode) == NULL) {
3972 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003973 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974 if (bytes == NULL)
3975 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003976 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3977 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003978 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003979 Py_DECREF(bytes);
3980 return NULL;
3981 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003982 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003983 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003984 PyBytes_AS_STRING(bytes),
3985 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003986 Py_DECREF(bytes);
3987 }
3988
3989 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003990 *psize = PyUnicode_UTF8_LENGTH(unicode);
3991 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003992}
3993
3994char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003995PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003996{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003997 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3998}
3999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004000Py_UNICODE *
4001PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4002{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003 const unsigned char *one_byte;
4004#if SIZEOF_WCHAR_T == 4
4005 const Py_UCS2 *two_bytes;
4006#else
4007 const Py_UCS4 *four_bytes;
4008 const Py_UCS4 *ucs4_end;
4009 Py_ssize_t num_surrogates;
4010#endif
4011 wchar_t *w;
4012 wchar_t *wchar_end;
4013
4014 if (!PyUnicode_Check(unicode)) {
4015 PyErr_BadArgument();
4016 return NULL;
4017 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004018 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004019 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004020 assert(_PyUnicode_KIND(unicode) != 0);
4021 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004022
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004023 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004025 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4026 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004027 num_surrogates = 0;
4028
4029 for (; four_bytes < ucs4_end; ++four_bytes) {
4030 if (*four_bytes > 0xFFFF)
4031 ++num_surrogates;
4032 }
4033
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004034 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4035 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4036 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004037 PyErr_NoMemory();
4038 return NULL;
4039 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004040 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004041
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004042 w = _PyUnicode_WSTR(unicode);
4043 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4044 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004045 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4046 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004047 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004048 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004049 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4050 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004051 }
4052 else
4053 *w = *four_bytes;
4054
4055 if (w > wchar_end) {
4056 assert(0 && "Miscalculated string end");
4057 }
4058 }
4059 *w = 0;
4060#else
4061 /* sizeof(wchar_t) == 4 */
4062 Py_FatalError("Impossible unicode object state, wstr and str "
4063 "should share memory already.");
4064 return NULL;
4065#endif
4066 }
4067 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004068 if ((size_t)_PyUnicode_LENGTH(unicode) >
4069 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4070 PyErr_NoMemory();
4071 return NULL;
4072 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004073 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4074 (_PyUnicode_LENGTH(unicode) + 1));
4075 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004076 PyErr_NoMemory();
4077 return NULL;
4078 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004079 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4080 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4081 w = _PyUnicode_WSTR(unicode);
4082 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004083
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004084 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4085 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004086 for (; w < wchar_end; ++one_byte, ++w)
4087 *w = *one_byte;
4088 /* null-terminate the wstr */
4089 *w = 0;
4090 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004091 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004092#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004093 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004094 for (; w < wchar_end; ++two_bytes, ++w)
4095 *w = *two_bytes;
4096 /* null-terminate the wstr */
4097 *w = 0;
4098#else
4099 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004100 PyObject_FREE(_PyUnicode_WSTR(unicode));
4101 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004102 Py_FatalError("Impossible unicode object state, wstr "
4103 "and str should share memory already.");
4104 return NULL;
4105#endif
4106 }
4107 else {
4108 assert(0 && "This should never happen.");
4109 }
4110 }
4111 }
4112 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004113 *size = PyUnicode_WSTR_LENGTH(unicode);
4114 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004115}
4116
Alexander Belopolsky40018472011-02-26 01:02:56 +00004117Py_UNICODE *
4118PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004119{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004120 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004121}
4122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004123
Alexander Belopolsky40018472011-02-26 01:02:56 +00004124Py_ssize_t
4125PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004126{
4127 if (!PyUnicode_Check(unicode)) {
4128 PyErr_BadArgument();
4129 goto onError;
4130 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004131 if (_PyUnicode_WSTR(unicode) == NULL) {
4132 if (PyUnicode_AsUnicode(unicode) == NULL)
4133 goto onError;
4134 }
4135 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004136
Benjamin Peterson29060642009-01-31 22:14:21 +00004137 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004138 return -1;
4139}
4140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004141Py_ssize_t
4142PyUnicode_GetLength(PyObject *unicode)
4143{
Victor Stinner07621332012-06-16 04:53:46 +02004144 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004145 PyErr_BadArgument();
4146 return -1;
4147 }
Victor Stinner07621332012-06-16 04:53:46 +02004148 if (PyUnicode_READY(unicode) == -1)
4149 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004150 return PyUnicode_GET_LENGTH(unicode);
4151}
4152
4153Py_UCS4
4154PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4155{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004156 void *data;
4157 int kind;
4158
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004159 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4160 PyErr_BadArgument();
4161 return (Py_UCS4)-1;
4162 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004163 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004164 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004165 return (Py_UCS4)-1;
4166 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004167 data = PyUnicode_DATA(unicode);
4168 kind = PyUnicode_KIND(unicode);
4169 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004170}
4171
4172int
4173PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4174{
4175 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004176 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004177 return -1;
4178 }
Victor Stinner488fa492011-12-12 00:01:39 +01004179 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004180 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004181 PyErr_SetString(PyExc_IndexError, "string index out of range");
4182 return -1;
4183 }
Victor Stinner488fa492011-12-12 00:01:39 +01004184 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004185 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004186 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4187 PyErr_SetString(PyExc_ValueError, "character out of range");
4188 return -1;
4189 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004190 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4191 index, ch);
4192 return 0;
4193}
4194
Alexander Belopolsky40018472011-02-26 01:02:56 +00004195const char *
4196PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004197{
Victor Stinner42cb4622010-09-01 19:39:01 +00004198 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004199}
4200
Victor Stinner554f3f02010-06-16 23:33:54 +00004201/* create or adjust a UnicodeDecodeError */
4202static void
4203make_decode_exception(PyObject **exceptionObject,
4204 const char *encoding,
4205 const char *input, Py_ssize_t length,
4206 Py_ssize_t startpos, Py_ssize_t endpos,
4207 const char *reason)
4208{
4209 if (*exceptionObject == NULL) {
4210 *exceptionObject = PyUnicodeDecodeError_Create(
4211 encoding, input, length, startpos, endpos, reason);
4212 }
4213 else {
4214 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4215 goto onError;
4216 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4217 goto onError;
4218 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4219 goto onError;
4220 }
4221 return;
4222
4223onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004224 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004225}
4226
Steve Dowercc16be82016-09-08 10:35:16 -07004227#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004228/* error handling callback helper:
4229 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004230 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004231 and adjust various state variables.
4232 return 0 on success, -1 on error
4233*/
4234
Alexander Belopolsky40018472011-02-26 01:02:56 +00004235static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004236unicode_decode_call_errorhandler_wchar(
4237 const char *errors, PyObject **errorHandler,
4238 const char *encoding, const char *reason,
4239 const char **input, const char **inend, Py_ssize_t *startinpos,
4240 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4241 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004242{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004243 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004244
4245 PyObject *restuple = NULL;
4246 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004247 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004248 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004249 Py_ssize_t requiredsize;
4250 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004251 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004252 wchar_t *repwstr;
4253 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004254
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004255 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4256 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004257
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004258 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004259 *errorHandler = PyCodec_LookupError(errors);
4260 if (*errorHandler == NULL)
4261 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004262 }
4263
Victor Stinner554f3f02010-06-16 23:33:54 +00004264 make_decode_exception(exceptionObject,
4265 encoding,
4266 *input, *inend - *input,
4267 *startinpos, *endinpos,
4268 reason);
4269 if (*exceptionObject == NULL)
4270 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004271
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004272 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004273 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004274 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004275 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004276 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004277 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004278 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004279 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004280 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004281
4282 /* Copy back the bytes variables, which might have been modified by the
4283 callback */
4284 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4285 if (!inputobj)
4286 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004287 *input = PyBytes_AS_STRING(inputobj);
4288 insize = PyBytes_GET_SIZE(inputobj);
4289 *inend = *input + insize;
4290 /* we can DECREF safely, as the exception has another reference,
4291 so the object won't go away. */
4292 Py_DECREF(inputobj);
4293
4294 if (newpos<0)
4295 newpos = insize+newpos;
4296 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004297 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004298 goto onError;
4299 }
4300
4301 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4302 if (repwstr == NULL)
4303 goto onError;
4304 /* need more space? (at least enough for what we
4305 have+the replacement+the rest of the string (starting
4306 at the new input position), so we won't have to check space
4307 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004308 requiredsize = *outpos;
4309 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4310 goto overflow;
4311 requiredsize += repwlen;
4312 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4313 goto overflow;
4314 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004315 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004316 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004317 requiredsize = 2*outsize;
4318 if (unicode_resize(output, requiredsize) < 0)
4319 goto onError;
4320 }
4321 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4322 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004323 *endinpos = newpos;
4324 *inptr = *input + newpos;
4325
4326 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004327 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004328 return 0;
4329
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004330 overflow:
4331 PyErr_SetString(PyExc_OverflowError,
4332 "decoded result is too long for a Python string");
4333
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004334 onError:
4335 Py_XDECREF(restuple);
4336 return -1;
4337}
Steve Dowercc16be82016-09-08 10:35:16 -07004338#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004339
4340static int
4341unicode_decode_call_errorhandler_writer(
4342 const char *errors, PyObject **errorHandler,
4343 const char *encoding, const char *reason,
4344 const char **input, const char **inend, Py_ssize_t *startinpos,
4345 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4346 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4347{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004348 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004349
4350 PyObject *restuple = NULL;
4351 PyObject *repunicode = NULL;
4352 Py_ssize_t insize;
4353 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004354 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004355 PyObject *inputobj = NULL;
4356
4357 if (*errorHandler == NULL) {
4358 *errorHandler = PyCodec_LookupError(errors);
4359 if (*errorHandler == NULL)
4360 goto onError;
4361 }
4362
4363 make_decode_exception(exceptionObject,
4364 encoding,
4365 *input, *inend - *input,
4366 *startinpos, *endinpos,
4367 reason);
4368 if (*exceptionObject == NULL)
4369 goto onError;
4370
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004371 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004372 if (restuple == NULL)
4373 goto onError;
4374 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004375 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004376 goto onError;
4377 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004378 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004379 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004380
4381 /* Copy back the bytes variables, which might have been modified by the
4382 callback */
4383 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4384 if (!inputobj)
4385 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004386 *input = PyBytes_AS_STRING(inputobj);
4387 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004388 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004389 /* we can DECREF safely, as the exception has another reference,
4390 so the object won't go away. */
4391 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004392
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004393 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004394 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004395 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004396 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004397 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004398 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004399
Victor Stinner170ca6f2013-04-18 00:25:28 +02004400 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004401 if (replen > 1) {
4402 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004403 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004404 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4405 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4406 goto onError;
4407 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004408 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004409 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004410
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004411 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004412 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004413
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004414 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004415 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004416 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004417
Benjamin Peterson29060642009-01-31 22:14:21 +00004418 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004419 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004420 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004421}
4422
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004423/* --- UTF-7 Codec -------------------------------------------------------- */
4424
Antoine Pitrou244651a2009-05-04 18:56:13 +00004425/* See RFC2152 for details. We encode conservatively and decode liberally. */
4426
4427/* Three simple macros defining base-64. */
4428
4429/* Is c a base-64 character? */
4430
4431#define IS_BASE64(c) \
4432 (((c) >= 'A' && (c) <= 'Z') || \
4433 ((c) >= 'a' && (c) <= 'z') || \
4434 ((c) >= '0' && (c) <= '9') || \
4435 (c) == '+' || (c) == '/')
4436
4437/* given that c is a base-64 character, what is its base-64 value? */
4438
4439#define FROM_BASE64(c) \
4440 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4441 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4442 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4443 (c) == '+' ? 62 : 63)
4444
4445/* What is the base-64 character of the bottom 6 bits of n? */
4446
4447#define TO_BASE64(n) \
4448 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4449
4450/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4451 * decoded as itself. We are permissive on decoding; the only ASCII
4452 * byte not decoding to itself is the + which begins a base64
4453 * string. */
4454
4455#define DECODE_DIRECT(c) \
4456 ((c) <= 127 && (c) != '+')
4457
4458/* The UTF-7 encoder treats ASCII characters differently according to
4459 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4460 * the above). See RFC2152. This array identifies these different
4461 * sets:
4462 * 0 : "Set D"
4463 * alphanumeric and '(),-./:?
4464 * 1 : "Set O"
4465 * !"#$%&*;<=>@[]^_`{|}
4466 * 2 : "whitespace"
4467 * ht nl cr sp
4468 * 3 : special (must be base64 encoded)
4469 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4470 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471
Tim Petersced69f82003-09-16 20:30:58 +00004472static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004473char utf7_category[128] = {
4474/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4475 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4476/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4477 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4478/* sp ! " # $ % & ' ( ) * + , - . / */
4479 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4480/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4481 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4482/* @ A B C D E F G H I J K L M N O */
4483 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4484/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4485 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4486/* ` a b c d e f g h i j k l m n o */
4487 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4488/* p q r s t u v w x y z { | } ~ del */
4489 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490};
4491
Antoine Pitrou244651a2009-05-04 18:56:13 +00004492/* ENCODE_DIRECT: this character should be encoded as itself. The
4493 * answer depends on whether we are encoding set O as itself, and also
4494 * on whether we are encoding whitespace as itself. RFC2152 makes it
4495 * clear that the answers to these questions vary between
4496 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004497
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498#define ENCODE_DIRECT(c, directO, directWS) \
4499 ((c) < 128 && (c) > 0 && \
4500 ((utf7_category[(c)] == 0) || \
4501 (directWS && (utf7_category[(c)] == 2)) || \
4502 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004503
Alexander Belopolsky40018472011-02-26 01:02:56 +00004504PyObject *
4505PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004506 Py_ssize_t size,
4507 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004508{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004509 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4510}
4511
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512/* The decoder. The only state we preserve is our read position,
4513 * i.e. how many characters we have consumed. So if we end in the
4514 * middle of a shift sequence we have to back off the read position
4515 * and the output to the beginning of the sequence, otherwise we lose
4516 * all the shift state (seen bits, number of bits seen, high
4517 * surrogate). */
4518
Alexander Belopolsky40018472011-02-26 01:02:56 +00004519PyObject *
4520PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004521 Py_ssize_t size,
4522 const char *errors,
4523 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004524{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004525 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004526 Py_ssize_t startinpos;
4527 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004528 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004529 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004530 const char *errmsg = "";
4531 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004532 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004533 unsigned int base64bits = 0;
4534 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004535 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004536 PyObject *errorHandler = NULL;
4537 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004539 if (size == 0) {
4540 if (consumed)
4541 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004542 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004543 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004545 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004546 _PyUnicodeWriter_Init(&writer);
4547 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004548
4549 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550 e = s + size;
4551
4552 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004553 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004554 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004555 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004556
Antoine Pitrou244651a2009-05-04 18:56:13 +00004557 if (inShift) { /* in a base-64 section */
4558 if (IS_BASE64(ch)) { /* consume a base-64 character */
4559 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4560 base64bits += 6;
4561 s++;
4562 if (base64bits >= 16) {
4563 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004564 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004565 base64bits -= 16;
4566 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004567 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004568 if (surrogate) {
4569 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004570 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4571 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004572 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004573 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004575 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004576 }
4577 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004578 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004579 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 }
4582 }
Victor Stinner551ac952011-11-29 22:58:13 +01004583 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 /* first surrogate */
4585 surrogate = outCh;
4586 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004587 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004588 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004589 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004590 }
4591 }
4592 }
4593 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004594 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004595 if (base64bits > 0) { /* left-over bits */
4596 if (base64bits >= 6) {
4597 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004598 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004599 errmsg = "partial character in shift sequence";
4600 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004601 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602 else {
4603 /* Some bits remain; they should be zero */
4604 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004605 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004606 errmsg = "non-zero padding bits in shift sequence";
4607 goto utf7Error;
4608 }
4609 }
4610 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004611 if (surrogate && DECODE_DIRECT(ch)) {
4612 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4613 goto onError;
4614 }
4615 surrogate = 0;
4616 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004617 /* '-' is absorbed; other terminating
4618 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004619 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004620 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004621 }
4622 }
4623 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004624 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004625 s++; /* consume '+' */
4626 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004627 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004628 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004629 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004630 }
4631 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004632 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004633 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004634 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004635 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004636 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004637 }
4638 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004639 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004640 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004641 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004642 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004643 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004644 else {
4645 startinpos = s-starts;
4646 s++;
4647 errmsg = "unexpected special character";
4648 goto utf7Error;
4649 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004650 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004651utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004652 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004653 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004654 errors, &errorHandler,
4655 "utf7", errmsg,
4656 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004657 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004658 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004659 }
4660
Antoine Pitrou244651a2009-05-04 18:56:13 +00004661 /* end of string */
4662
4663 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4664 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004665 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004666 if (surrogate ||
4667 (base64bits >= 6) ||
4668 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004669 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004670 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004671 errors, &errorHandler,
4672 "utf7", "unterminated shift sequence",
4673 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004674 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004675 goto onError;
4676 if (s < e)
4677 goto restart;
4678 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004679 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004680
4681 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004682 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004683 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004684 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004685 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004686 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004687 writer.kind, writer.data, shiftOutStart);
4688 Py_XDECREF(errorHandler);
4689 Py_XDECREF(exc);
4690 _PyUnicodeWriter_Dealloc(&writer);
4691 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004692 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004693 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004694 }
4695 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004696 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004697 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004698 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004699
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004700 Py_XDECREF(errorHandler);
4701 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004702 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004703
Benjamin Peterson29060642009-01-31 22:14:21 +00004704 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004705 Py_XDECREF(errorHandler);
4706 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004707 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004708 return NULL;
4709}
4710
4711
Alexander Belopolsky40018472011-02-26 01:02:56 +00004712PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004713_PyUnicode_EncodeUTF7(PyObject *str,
4714 int base64SetO,
4715 int base64WhiteSpace,
4716 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004717{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004718 int kind;
4719 void *data;
4720 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004721 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004722 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004723 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004724 unsigned int base64bits = 0;
4725 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004726 char * out;
4727 char * start;
4728
Benjamin Petersonbac79492012-01-14 13:34:47 -05004729 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004730 return NULL;
4731 kind = PyUnicode_KIND(str);
4732 data = PyUnicode_DATA(str);
4733 len = PyUnicode_GET_LENGTH(str);
4734
4735 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004736 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004737
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004738 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004739 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004740 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004741 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004742 if (v == NULL)
4743 return NULL;
4744
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004745 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004746 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004747 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004748
Antoine Pitrou244651a2009-05-04 18:56:13 +00004749 if (inShift) {
4750 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4751 /* shifting out */
4752 if (base64bits) { /* output remaining bits */
4753 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4754 base64buffer = 0;
4755 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004756 }
4757 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004758 /* Characters not in the BASE64 set implicitly unshift the sequence
4759 so no '-' is required, except if the character is itself a '-' */
4760 if (IS_BASE64(ch) || ch == '-') {
4761 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004762 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004763 *out++ = (char) ch;
4764 }
4765 else {
4766 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004767 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004768 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004769 else { /* not in a shift sequence */
4770 if (ch == '+') {
4771 *out++ = '+';
4772 *out++ = '-';
4773 }
4774 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4775 *out++ = (char) ch;
4776 }
4777 else {
4778 *out++ = '+';
4779 inShift = 1;
4780 goto encode_char;
4781 }
4782 }
4783 continue;
4784encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004785 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004786 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004787
Antoine Pitrou244651a2009-05-04 18:56:13 +00004788 /* code first surrogate */
4789 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004790 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004791 while (base64bits >= 6) {
4792 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4793 base64bits -= 6;
4794 }
4795 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004796 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004797 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004798 base64bits += 16;
4799 base64buffer = (base64buffer << 16) | ch;
4800 while (base64bits >= 6) {
4801 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4802 base64bits -= 6;
4803 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004804 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004805 if (base64bits)
4806 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4807 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004808 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004809 if (_PyBytes_Resize(&v, out - start) < 0)
4810 return NULL;
4811 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004812}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004813PyObject *
4814PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4815 Py_ssize_t size,
4816 int base64SetO,
4817 int base64WhiteSpace,
4818 const char *errors)
4819{
4820 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004821 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004822 if (tmp == NULL)
4823 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004824 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004825 base64WhiteSpace, errors);
4826 Py_DECREF(tmp);
4827 return result;
4828}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004829
Antoine Pitrou244651a2009-05-04 18:56:13 +00004830#undef IS_BASE64
4831#undef FROM_BASE64
4832#undef TO_BASE64
4833#undef DECODE_DIRECT
4834#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004835
Guido van Rossumd57fd912000-03-10 22:53:23 +00004836/* --- UTF-8 Codec -------------------------------------------------------- */
4837
Alexander Belopolsky40018472011-02-26 01:02:56 +00004838PyObject *
4839PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004840 Py_ssize_t size,
4841 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004842{
Walter Dörwald69652032004-09-07 20:24:22 +00004843 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4844}
4845
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004846#include "stringlib/asciilib.h"
4847#include "stringlib/codecs.h"
4848#include "stringlib/undef.h"
4849
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004850#include "stringlib/ucs1lib.h"
4851#include "stringlib/codecs.h"
4852#include "stringlib/undef.h"
4853
4854#include "stringlib/ucs2lib.h"
4855#include "stringlib/codecs.h"
4856#include "stringlib/undef.h"
4857
4858#include "stringlib/ucs4lib.h"
4859#include "stringlib/codecs.h"
4860#include "stringlib/undef.h"
4861
Antoine Pitrouab868312009-01-10 15:40:25 +00004862/* Mask to quickly check whether a C 'long' contains a
4863 non-ASCII, UTF8-encoded char. */
4864#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004865# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004866#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004867# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004868#else
4869# error C 'long' size should be either 4 or 8!
4870#endif
4871
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004872static Py_ssize_t
4873ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004874{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004875 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004876 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004877
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004878 /*
4879 * Issue #17237: m68k is a bit different from most architectures in
4880 * that objects do not use "natural alignment" - for example, int and
4881 * long are only aligned at 2-byte boundaries. Therefore the assert()
4882 * won't work; also, tests have shown that skipping the "optimised
4883 * version" will even speed up m68k.
4884 */
4885#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004886#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004887 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4888 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004889 /* Fast path, see in STRINGLIB(utf8_decode) for
4890 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004891 /* Help allocation */
4892 const char *_p = p;
4893 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004894 while (_p < aligned_end) {
4895 unsigned long value = *(const unsigned long *) _p;
4896 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004897 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004898 *((unsigned long *)q) = value;
4899 _p += SIZEOF_LONG;
4900 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004901 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004902 p = _p;
4903 while (p < end) {
4904 if ((unsigned char)*p & 0x80)
4905 break;
4906 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004907 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004908 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004909 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004910#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004911#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004912 while (p < end) {
4913 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4914 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004915 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004916 /* Help allocation */
4917 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004918 while (_p < aligned_end) {
4919 unsigned long value = *(unsigned long *) _p;
4920 if (value & ASCII_CHAR_MASK)
4921 break;
4922 _p += SIZEOF_LONG;
4923 }
4924 p = _p;
4925 if (_p == end)
4926 break;
4927 }
4928 if ((unsigned char)*p & 0x80)
4929 break;
4930 ++p;
4931 }
4932 memcpy(dest, start, p - start);
4933 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004934}
Antoine Pitrouab868312009-01-10 15:40:25 +00004935
Victor Stinner785938e2011-12-11 20:09:03 +01004936PyObject *
4937PyUnicode_DecodeUTF8Stateful(const char *s,
4938 Py_ssize_t size,
4939 const char *errors,
4940 Py_ssize_t *consumed)
4941{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004942 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004943 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004944 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004945
4946 Py_ssize_t startinpos;
4947 Py_ssize_t endinpos;
4948 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004949 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004950 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004951 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004952
4953 if (size == 0) {
4954 if (consumed)
4955 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004956 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004957 }
4958
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004959 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4960 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004961 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004962 *consumed = 1;
4963 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004964 }
4965
Victor Stinner8f674cc2013-04-17 23:02:17 +02004966 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004967 writer.min_length = size;
4968 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004969 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004970
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004971 writer.pos = ascii_decode(s, end, writer.data);
4972 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004973 while (s < end) {
4974 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004975 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004976
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004977 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004978 if (PyUnicode_IS_ASCII(writer.buffer))
4979 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004980 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004981 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004982 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004983 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004984 } else {
4985 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004986 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004987 }
4988
4989 switch (ch) {
4990 case 0:
4991 if (s == end || consumed)
4992 goto End;
4993 errmsg = "unexpected end of data";
4994 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004995 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004996 break;
4997 case 1:
4998 errmsg = "invalid start byte";
4999 startinpos = s - starts;
5000 endinpos = startinpos + 1;
5001 break;
5002 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005003 case 3:
5004 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005005 errmsg = "invalid continuation byte";
5006 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005007 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005008 break;
5009 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005010 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005011 goto onError;
5012 continue;
5013 }
5014
Victor Stinner1d65d912015-10-05 13:43:50 +02005015 if (error_handler == _Py_ERROR_UNKNOWN)
5016 error_handler = get_error_handler(errors);
5017
5018 switch (error_handler) {
5019 case _Py_ERROR_IGNORE:
5020 s += (endinpos - startinpos);
5021 break;
5022
5023 case _Py_ERROR_REPLACE:
5024 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5025 goto onError;
5026 s += (endinpos - startinpos);
5027 break;
5028
5029 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005030 {
5031 Py_ssize_t i;
5032
Victor Stinner1d65d912015-10-05 13:43:50 +02005033 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5034 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005035 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005036 ch = (Py_UCS4)(unsigned char)(starts[i]);
5037 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5038 ch + 0xdc00);
5039 writer.pos++;
5040 }
5041 s += (endinpos - startinpos);
5042 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005043 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005044
5045 default:
5046 if (unicode_decode_call_errorhandler_writer(
5047 errors, &error_handler_obj,
5048 "utf-8", errmsg,
5049 &starts, &end, &startinpos, &endinpos, &exc, &s,
5050 &writer))
5051 goto onError;
5052 }
Victor Stinner785938e2011-12-11 20:09:03 +01005053 }
5054
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005055End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005056 if (consumed)
5057 *consumed = s - starts;
5058
Victor Stinner1d65d912015-10-05 13:43:50 +02005059 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005060 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005061 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005062
5063onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005064 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005065 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005066 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005067 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005068}
5069
Xavier de Gaye76febd02016-12-15 20:59:58 +01005070#if defined(__APPLE__) || defined(__ANDROID__)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005071
5072/* Simplified UTF-8 decoder using surrogateescape error handler,
Xavier de Gaye76febd02016-12-15 20:59:58 +01005073 used to decode the command line arguments on Mac OS X and Android.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005074
5075 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005076 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005077
5078wchar_t*
5079_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5080{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005081 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005082 wchar_t *unicode;
5083 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005084
5085 /* Note: size will always be longer than the resulting Unicode
5086 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005087 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005088 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005089 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005090 if (!unicode)
5091 return NULL;
5092
5093 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005094 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005095 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005096 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005097 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005098#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005099 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005100#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005101 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005102#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005103 if (ch > 0xFF) {
5104#if SIZEOF_WCHAR_T == 4
5105 assert(0);
5106#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005107 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005108 /* compute and append the two surrogates: */
5109 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5110 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5111#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005112 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005113 else {
5114 if (!ch && s == e)
5115 break;
5116 /* surrogateescape */
5117 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5118 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005119 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005120 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005121 return unicode;
5122}
5123
Xavier de Gaye76febd02016-12-15 20:59:58 +01005124#endif /* __APPLE__ or __ANDROID__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005126/* Primary internal function which creates utf8 encoded bytes objects.
5127
5128 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005129 and allocate exactly as much space needed at the end. Else allocate the
5130 maximum possible needed (4 result bytes per Unicode character), and return
5131 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005132*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005133PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005134_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005135{
Victor Stinner6099a032011-12-18 14:22:26 +01005136 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005137 void *data;
5138 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005140 if (!PyUnicode_Check(unicode)) {
5141 PyErr_BadArgument();
5142 return NULL;
5143 }
5144
5145 if (PyUnicode_READY(unicode) == -1)
5146 return NULL;
5147
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005148 if (PyUnicode_UTF8(unicode))
5149 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5150 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005151
5152 kind = PyUnicode_KIND(unicode);
5153 data = PyUnicode_DATA(unicode);
5154 size = PyUnicode_GET_LENGTH(unicode);
5155
Benjamin Petersonead6b532011-12-20 17:23:42 -06005156 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005157 default:
5158 assert(0);
5159 case PyUnicode_1BYTE_KIND:
5160 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5161 assert(!PyUnicode_IS_ASCII(unicode));
5162 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5163 case PyUnicode_2BYTE_KIND:
5164 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5165 case PyUnicode_4BYTE_KIND:
5166 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005167 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005168}
5169
Alexander Belopolsky40018472011-02-26 01:02:56 +00005170PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005171PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5172 Py_ssize_t size,
5173 const char *errors)
5174{
5175 PyObject *v, *unicode;
5176
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005177 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005178 if (unicode == NULL)
5179 return NULL;
5180 v = _PyUnicode_AsUTF8String(unicode, errors);
5181 Py_DECREF(unicode);
5182 return v;
5183}
5184
5185PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005186PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005187{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005188 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005189}
5190
Walter Dörwald41980ca2007-08-16 21:55:45 +00005191/* --- UTF-32 Codec ------------------------------------------------------- */
5192
5193PyObject *
5194PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005195 Py_ssize_t size,
5196 const char *errors,
5197 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005198{
5199 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5200}
5201
5202PyObject *
5203PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005204 Py_ssize_t size,
5205 const char *errors,
5206 int *byteorder,
5207 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005208{
5209 const char *starts = s;
5210 Py_ssize_t startinpos;
5211 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005212 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005213 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005214 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005215 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005216 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005217 PyObject *errorHandler = NULL;
5218 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005219
Walter Dörwald41980ca2007-08-16 21:55:45 +00005220 q = (unsigned char *)s;
5221 e = q + size;
5222
5223 if (byteorder)
5224 bo = *byteorder;
5225
5226 /* Check for BOM marks (U+FEFF) in the input and adjust current
5227 byte order setting accordingly. In native mode, the leading BOM
5228 mark is skipped, in all other modes, it is copied to the output
5229 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005230 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005231 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005232 if (bom == 0x0000FEFF) {
5233 bo = -1;
5234 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005235 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005236 else if (bom == 0xFFFE0000) {
5237 bo = 1;
5238 q += 4;
5239 }
5240 if (byteorder)
5241 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005242 }
5243
Victor Stinnere64322e2012-10-30 23:12:47 +01005244 if (q == e) {
5245 if (consumed)
5246 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005247 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005248 }
5249
Victor Stinnere64322e2012-10-30 23:12:47 +01005250#ifdef WORDS_BIGENDIAN
5251 le = bo < 0;
5252#else
5253 le = bo <= 0;
5254#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005255 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005256
Victor Stinner8f674cc2013-04-17 23:02:17 +02005257 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005258 writer.min_length = (e - q + 3) / 4;
5259 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005260 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005261
Victor Stinnere64322e2012-10-30 23:12:47 +01005262 while (1) {
5263 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005264 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005265
Victor Stinnere64322e2012-10-30 23:12:47 +01005266 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005267 enum PyUnicode_Kind kind = writer.kind;
5268 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005269 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005270 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005271 if (le) {
5272 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005273 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005274 if (ch > maxch)
5275 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005276 if (kind != PyUnicode_1BYTE_KIND &&
5277 Py_UNICODE_IS_SURROGATE(ch))
5278 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005279 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005280 q += 4;
5281 } while (q <= last);
5282 }
5283 else {
5284 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005285 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005286 if (ch > maxch)
5287 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005288 if (kind != PyUnicode_1BYTE_KIND &&
5289 Py_UNICODE_IS_SURROGATE(ch))
5290 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005291 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005292 q += 4;
5293 } while (q <= last);
5294 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005295 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005296 }
5297
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005298 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005299 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005300 startinpos = ((const char *)q) - starts;
5301 endinpos = startinpos + 4;
5302 }
5303 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005304 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005305 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005306 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005307 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005308 startinpos = ((const char *)q) - starts;
5309 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005310 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005311 else {
5312 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005313 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005314 goto onError;
5315 q += 4;
5316 continue;
5317 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005318 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005319 startinpos = ((const char *)q) - starts;
5320 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005321 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005322
5323 /* The remaining input chars are ignored if the callback
5324 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005325 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005326 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005327 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005328 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005329 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005330 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005331 }
5332
Walter Dörwald41980ca2007-08-16 21:55:45 +00005333 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005334 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005335
Walter Dörwald41980ca2007-08-16 21:55:45 +00005336 Py_XDECREF(errorHandler);
5337 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005338 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005339
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005341 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005342 Py_XDECREF(errorHandler);
5343 Py_XDECREF(exc);
5344 return NULL;
5345}
5346
5347PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005348_PyUnicode_EncodeUTF32(PyObject *str,
5349 const char *errors,
5350 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005351{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005352 enum PyUnicode_Kind kind;
5353 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005354 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005355 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005356 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005357#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005358 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005359#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005360 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005361#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005362 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005363 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005364 PyObject *errorHandler = NULL;
5365 PyObject *exc = NULL;
5366 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005367
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005368 if (!PyUnicode_Check(str)) {
5369 PyErr_BadArgument();
5370 return NULL;
5371 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005372 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005373 return NULL;
5374 kind = PyUnicode_KIND(str);
5375 data = PyUnicode_DATA(str);
5376 len = PyUnicode_GET_LENGTH(str);
5377
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005378 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005379 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005380 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005381 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005382 if (v == NULL)
5383 return NULL;
5384
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005385 /* output buffer is 4-bytes aligned */
5386 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005387 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005388 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005389 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005390 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005391 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005392
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005393 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005394 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005395 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005396 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005397 else
5398 encoding = "utf-32";
5399
5400 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005401 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5402 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005403 }
5404
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005405 pos = 0;
5406 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005407 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005408
5409 if (kind == PyUnicode_2BYTE_KIND) {
5410 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5411 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005412 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005413 else {
5414 assert(kind == PyUnicode_4BYTE_KIND);
5415 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5416 &out, native_ordering);
5417 }
5418 if (pos == len)
5419 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005420
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005421 rep = unicode_encode_call_errorhandler(
5422 errors, &errorHandler,
5423 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005424 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005425 if (!rep)
5426 goto error;
5427
5428 if (PyBytes_Check(rep)) {
5429 repsize = PyBytes_GET_SIZE(rep);
5430 if (repsize & 3) {
5431 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005432 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005433 "surrogates not allowed");
5434 goto error;
5435 }
5436 moreunits = repsize / 4;
5437 }
5438 else {
5439 assert(PyUnicode_Check(rep));
5440 if (PyUnicode_READY(rep) < 0)
5441 goto error;
5442 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5443 if (!PyUnicode_IS_ASCII(rep)) {
5444 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005445 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005446 "surrogates not allowed");
5447 goto error;
5448 }
5449 }
5450
5451 /* four bytes are reserved for each surrogate */
5452 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005453 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005454 Py_ssize_t morebytes = 4 * (moreunits - 1);
5455 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5456 /* integer overflow */
5457 PyErr_NoMemory();
5458 goto error;
5459 }
5460 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5461 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005462 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005463 }
5464
5465 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005466 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005467 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005468 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005470 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5471 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005472 }
5473
5474 Py_CLEAR(rep);
5475 }
5476
5477 /* Cut back to size actually needed. This is necessary for, for example,
5478 encoding of a string containing isolated surrogates and the 'ignore'
5479 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005480 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005481 if (nsize != PyBytes_GET_SIZE(v))
5482 _PyBytes_Resize(&v, nsize);
5483 Py_XDECREF(errorHandler);
5484 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005485 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005486 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005487 error:
5488 Py_XDECREF(rep);
5489 Py_XDECREF(errorHandler);
5490 Py_XDECREF(exc);
5491 Py_XDECREF(v);
5492 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005493}
5494
Alexander Belopolsky40018472011-02-26 01:02:56 +00005495PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005496PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5497 Py_ssize_t size,
5498 const char *errors,
5499 int byteorder)
5500{
5501 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005502 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005503 if (tmp == NULL)
5504 return NULL;
5505 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5506 Py_DECREF(tmp);
5507 return result;
5508}
5509
5510PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005511PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005512{
Victor Stinnerb960b342011-11-20 19:12:52 +01005513 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005514}
5515
Guido van Rossumd57fd912000-03-10 22:53:23 +00005516/* --- UTF-16 Codec ------------------------------------------------------- */
5517
Tim Peters772747b2001-08-09 22:21:55 +00005518PyObject *
5519PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005520 Py_ssize_t size,
5521 const char *errors,
5522 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005523{
Walter Dörwald69652032004-09-07 20:24:22 +00005524 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5525}
5526
5527PyObject *
5528PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005529 Py_ssize_t size,
5530 const char *errors,
5531 int *byteorder,
5532 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005533{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005534 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005535 Py_ssize_t startinpos;
5536 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005537 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005538 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005539 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005540 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005541 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005542 PyObject *errorHandler = NULL;
5543 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005544 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545
Tim Peters772747b2001-08-09 22:21:55 +00005546 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005547 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005548
5549 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005550 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005551
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005552 /* Check for BOM marks (U+FEFF) in the input and adjust current
5553 byte order setting accordingly. In native mode, the leading BOM
5554 mark is skipped, in all other modes, it is copied to the output
5555 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005556 if (bo == 0 && size >= 2) {
5557 const Py_UCS4 bom = (q[1] << 8) | q[0];
5558 if (bom == 0xFEFF) {
5559 q += 2;
5560 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005561 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005562 else if (bom == 0xFFFE) {
5563 q += 2;
5564 bo = 1;
5565 }
5566 if (byteorder)
5567 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005568 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005569
Antoine Pitrou63065d72012-05-15 23:48:04 +02005570 if (q == e) {
5571 if (consumed)
5572 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005573 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005574 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005575
Christian Heimes743e0cd2012-10-17 23:52:17 +02005576#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005577 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005578 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005579#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005580 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005581 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005582#endif
Tim Peters772747b2001-08-09 22:21:55 +00005583
Antoine Pitrou63065d72012-05-15 23:48:04 +02005584 /* Note: size will always be longer than the resulting Unicode
5585 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005586 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005587 writer.min_length = (e - q + 1) / 2;
5588 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005589 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005590
Antoine Pitrou63065d72012-05-15 23:48:04 +02005591 while (1) {
5592 Py_UCS4 ch = 0;
5593 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005594 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005595 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005596 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005597 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005598 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005599 native_ordering);
5600 else
5601 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005602 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005603 native_ordering);
5604 } else if (kind == PyUnicode_2BYTE_KIND) {
5605 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005606 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005607 native_ordering);
5608 } else {
5609 assert(kind == PyUnicode_4BYTE_KIND);
5610 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005611 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005612 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005613 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005614 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005615
Antoine Pitrou63065d72012-05-15 23:48:04 +02005616 switch (ch)
5617 {
5618 case 0:
5619 /* remaining byte at the end? (size should be even) */
5620 if (q == e || consumed)
5621 goto End;
5622 errmsg = "truncated data";
5623 startinpos = ((const char *)q) - starts;
5624 endinpos = ((const char *)e) - starts;
5625 break;
5626 /* The remaining input chars are ignored if the callback
5627 chooses to skip the input */
5628 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005629 q -= 2;
5630 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005631 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005632 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005633 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005634 endinpos = ((const char *)e) - starts;
5635 break;
5636 case 2:
5637 errmsg = "illegal encoding";
5638 startinpos = ((const char *)q) - 2 - starts;
5639 endinpos = startinpos + 2;
5640 break;
5641 case 3:
5642 errmsg = "illegal UTF-16 surrogate";
5643 startinpos = ((const char *)q) - 4 - starts;
5644 endinpos = startinpos + 2;
5645 break;
5646 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005647 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005648 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005649 continue;
5650 }
5651
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005652 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005653 errors,
5654 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005655 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005656 &starts,
5657 (const char **)&e,
5658 &startinpos,
5659 &endinpos,
5660 &exc,
5661 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005662 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005663 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005664 }
5665
Antoine Pitrou63065d72012-05-15 23:48:04 +02005666End:
Walter Dörwald69652032004-09-07 20:24:22 +00005667 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005668 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005669
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005670 Py_XDECREF(errorHandler);
5671 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005672 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673
Benjamin Peterson29060642009-01-31 22:14:21 +00005674 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005675 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005676 Py_XDECREF(errorHandler);
5677 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005678 return NULL;
5679}
5680
Tim Peters772747b2001-08-09 22:21:55 +00005681PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005682_PyUnicode_EncodeUTF16(PyObject *str,
5683 const char *errors,
5684 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005685{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005686 enum PyUnicode_Kind kind;
5687 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005688 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005689 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005690 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005691 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005692#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005693 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005694#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005695 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005696#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005697 const char *encoding;
5698 Py_ssize_t nsize, pos;
5699 PyObject *errorHandler = NULL;
5700 PyObject *exc = NULL;
5701 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005702
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005703 if (!PyUnicode_Check(str)) {
5704 PyErr_BadArgument();
5705 return NULL;
5706 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005707 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005708 return NULL;
5709 kind = PyUnicode_KIND(str);
5710 data = PyUnicode_DATA(str);
5711 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005712
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005713 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005714 if (kind == PyUnicode_4BYTE_KIND) {
5715 const Py_UCS4 *in = (const Py_UCS4 *)data;
5716 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005717 while (in < end) {
5718 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005719 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005720 }
5721 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005722 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005723 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005724 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005725 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005726 nsize = len + pairs + (byteorder == 0);
5727 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005728 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005730 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005732 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005733 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005734 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005735 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005736 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005737 }
5738 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005739 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005740 }
Tim Peters772747b2001-08-09 22:21:55 +00005741
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005742 if (kind == PyUnicode_1BYTE_KIND) {
5743 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5744 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005745 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005746
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005747 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005748 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005749 }
5750 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005751 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005752 }
5753 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005754 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005755 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005756
5757 pos = 0;
5758 while (pos < len) {
5759 Py_ssize_t repsize, moreunits;
5760
5761 if (kind == PyUnicode_2BYTE_KIND) {
5762 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5763 &out, native_ordering);
5764 }
5765 else {
5766 assert(kind == PyUnicode_4BYTE_KIND);
5767 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5768 &out, native_ordering);
5769 }
5770 if (pos == len)
5771 break;
5772
5773 rep = unicode_encode_call_errorhandler(
5774 errors, &errorHandler,
5775 encoding, "surrogates not allowed",
5776 str, &exc, pos, pos + 1, &pos);
5777 if (!rep)
5778 goto error;
5779
5780 if (PyBytes_Check(rep)) {
5781 repsize = PyBytes_GET_SIZE(rep);
5782 if (repsize & 1) {
5783 raise_encode_exception(&exc, encoding,
5784 str, pos - 1, pos,
5785 "surrogates not allowed");
5786 goto error;
5787 }
5788 moreunits = repsize / 2;
5789 }
5790 else {
5791 assert(PyUnicode_Check(rep));
5792 if (PyUnicode_READY(rep) < 0)
5793 goto error;
5794 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5795 if (!PyUnicode_IS_ASCII(rep)) {
5796 raise_encode_exception(&exc, encoding,
5797 str, pos - 1, pos,
5798 "surrogates not allowed");
5799 goto error;
5800 }
5801 }
5802
5803 /* two bytes are reserved for each surrogate */
5804 if (moreunits > 1) {
5805 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5806 Py_ssize_t morebytes = 2 * (moreunits - 1);
5807 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5808 /* integer overflow */
5809 PyErr_NoMemory();
5810 goto error;
5811 }
5812 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5813 goto error;
5814 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5815 }
5816
5817 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005818 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005819 out += moreunits;
5820 } else /* rep is unicode */ {
5821 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5822 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5823 &out, native_ordering);
5824 }
5825
5826 Py_CLEAR(rep);
5827 }
5828
5829 /* Cut back to size actually needed. This is necessary for, for example,
5830 encoding of a string containing isolated surrogates and the 'ignore' handler
5831 is used. */
5832 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5833 if (nsize != PyBytes_GET_SIZE(v))
5834 _PyBytes_Resize(&v, nsize);
5835 Py_XDECREF(errorHandler);
5836 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005837 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005838 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005839 error:
5840 Py_XDECREF(rep);
5841 Py_XDECREF(errorHandler);
5842 Py_XDECREF(exc);
5843 Py_XDECREF(v);
5844 return NULL;
5845#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005846}
5847
Alexander Belopolsky40018472011-02-26 01:02:56 +00005848PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005849PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5850 Py_ssize_t size,
5851 const char *errors,
5852 int byteorder)
5853{
5854 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005855 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005856 if (tmp == NULL)
5857 return NULL;
5858 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5859 Py_DECREF(tmp);
5860 return result;
5861}
5862
5863PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005864PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005865{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005866 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005867}
5868
5869/* --- Unicode Escape Codec ----------------------------------------------- */
5870
Fredrik Lundh06d12682001-01-24 07:59:11 +00005871static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005872
Alexander Belopolsky40018472011-02-26 01:02:56 +00005873PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005874_PyUnicode_DecodeUnicodeEscape(const char *s,
5875 Py_ssize_t size,
5876 const char *errors,
5877 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005879 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005880 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005882 PyObject *errorHandler = NULL;
5883 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005884
Eric V. Smith42454af2016-10-31 09:22:08 -04005885 // so we can remember if we've seen an invalid escape char or not
5886 *first_invalid_escape = NULL;
5887
Victor Stinner62ec3312016-09-06 17:04:34 -07005888 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005889 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005890 }
5891 /* Escaped strings will always be longer than the resulting
5892 Unicode string, so we start with size here and then reduce the
5893 length after conversion to the true value.
5894 (but if the error callback returns a long replacement string
5895 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005896 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005897 writer.min_length = size;
5898 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5899 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005900 }
5901
Guido van Rossumd57fd912000-03-10 22:53:23 +00005902 end = s + size;
5903 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005904 unsigned char c = (unsigned char) *s++;
5905 Py_UCS4 ch;
5906 int count;
5907 Py_ssize_t startinpos;
5908 Py_ssize_t endinpos;
5909 const char *message;
5910
5911#define WRITE_ASCII_CHAR(ch) \
5912 do { \
5913 assert(ch <= 127); \
5914 assert(writer.pos < writer.size); \
5915 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5916 } while(0)
5917
5918#define WRITE_CHAR(ch) \
5919 do { \
5920 if (ch <= writer.maxchar) { \
5921 assert(writer.pos < writer.size); \
5922 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5923 } \
5924 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5925 goto onError; \
5926 } \
5927 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928
5929 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005930 if (c != '\\') {
5931 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932 continue;
5933 }
5934
Victor Stinner62ec3312016-09-06 17:04:34 -07005935 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005936 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005937 if (s >= end) {
5938 message = "\\ at end of string";
5939 goto error;
5940 }
5941 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005942
Victor Stinner62ec3312016-09-06 17:04:34 -07005943 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005944 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005945
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005947 case '\n': continue;
5948 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5949 case '\'': WRITE_ASCII_CHAR('\''); continue;
5950 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5951 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005952 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005953 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5954 case 't': WRITE_ASCII_CHAR('\t'); continue;
5955 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5956 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005957 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005958 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005959 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005960 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005961
Benjamin Peterson29060642009-01-31 22:14:21 +00005962 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005963 case '0': case '1': case '2': case '3':
5964 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005965 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005966 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005967 ch = (ch<<3) + *s++ - '0';
5968 if (s < end && '0' <= *s && *s <= '7') {
5969 ch = (ch<<3) + *s++ - '0';
5970 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005972 WRITE_CHAR(ch);
5973 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974
Benjamin Peterson29060642009-01-31 22:14:21 +00005975 /* hex escapes */
5976 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005978 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005979 message = "truncated \\xXX escape";
5980 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005981
Benjamin Peterson29060642009-01-31 22:14:21 +00005982 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005984 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005985 message = "truncated \\uXXXX escape";
5986 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987
Benjamin Peterson29060642009-01-31 22:14:21 +00005988 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005989 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005990 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005991 message = "truncated \\UXXXXXXXX escape";
5992 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07005993 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02005994 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07005995 ch <<= 4;
5996 if (c >= '0' && c <= '9') {
5997 ch += c - '0';
5998 }
5999 else if (c >= 'a' && c <= 'f') {
6000 ch += c - ('a' - 10);
6001 }
6002 else if (c >= 'A' && c <= 'F') {
6003 ch += c - ('A' - 10);
6004 }
6005 else {
6006 break;
6007 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006008 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006009 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006010 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006011 }
6012
6013 /* when we get here, ch is a 32-bit unicode character */
6014 if (ch > MAX_UNICODE) {
6015 message = "illegal Unicode character";
6016 goto error;
6017 }
6018
6019 WRITE_CHAR(ch);
6020 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006021
Benjamin Peterson29060642009-01-31 22:14:21 +00006022 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006023 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006024 if (ucnhash_CAPI == NULL) {
6025 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006026 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6027 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006028 if (ucnhash_CAPI == NULL) {
6029 PyErr_SetString(
6030 PyExc_UnicodeError,
6031 "\\N escapes not supported (can't load unicodedata module)"
6032 );
6033 goto onError;
6034 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006035 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006036
6037 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006038 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006039 const char *start = ++s;
6040 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006041 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006042 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006043 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006044 namelen = s - start;
6045 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006046 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006047 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006048 ch = 0xffffffff; /* in case 'getcode' messes up */
6049 if (namelen <= INT_MAX &&
6050 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6051 &ch, 0)) {
6052 assert(ch <= MAX_UNICODE);
6053 WRITE_CHAR(ch);
6054 continue;
6055 }
6056 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006057 }
6058 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006059 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006060
6061 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006062 if (*first_invalid_escape == NULL) {
6063 *first_invalid_escape = s-1; /* Back up one char, since we've
6064 already incremented s. */
6065 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006066 WRITE_ASCII_CHAR('\\');
6067 WRITE_CHAR(c);
6068 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006069 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006070
6071 error:
6072 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006073 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006074 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006075 errors, &errorHandler,
6076 "unicodeescape", message,
6077 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006078 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006079 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006080 }
6081 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6082 goto onError;
6083 }
6084
6085#undef WRITE_ASCII_CHAR
6086#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006087 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006088
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006089 Py_XDECREF(errorHandler);
6090 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006091 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006092
Benjamin Peterson29060642009-01-31 22:14:21 +00006093 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006094 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006095 Py_XDECREF(errorHandler);
6096 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006097 return NULL;
6098}
6099
Eric V. Smith42454af2016-10-31 09:22:08 -04006100PyObject *
6101PyUnicode_DecodeUnicodeEscape(const char *s,
6102 Py_ssize_t size,
6103 const char *errors)
6104{
6105 const char *first_invalid_escape;
6106 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6107 &first_invalid_escape);
6108 if (result == NULL)
6109 return NULL;
6110 if (first_invalid_escape != NULL) {
6111 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6112 "invalid escape sequence '\\%c'",
6113 *first_invalid_escape) < 0) {
6114 Py_DECREF(result);
6115 return NULL;
6116 }
6117 }
6118 return result;
6119}
6120
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006121/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006122
Alexander Belopolsky40018472011-02-26 01:02:56 +00006123PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006124PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006125{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006126 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006127 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006128 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006129 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006130 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006131 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006132
Ezio Melottie7f90372012-10-05 03:33:31 +03006133 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006134 escape.
6135
Ezio Melottie7f90372012-10-05 03:33:31 +03006136 For UCS1 strings it's '\xxx', 4 bytes per source character.
6137 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6138 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006139 */
6140
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006141 if (!PyUnicode_Check(unicode)) {
6142 PyErr_BadArgument();
6143 return NULL;
6144 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006145 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006146 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006147 }
Victor Stinner358af132015-10-12 22:36:57 +02006148
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006149 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006150 if (len == 0) {
6151 return PyBytes_FromStringAndSize(NULL, 0);
6152 }
6153
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006154 kind = PyUnicode_KIND(unicode);
6155 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006156 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6157 bytes, and 1 byte characters 4. */
6158 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006159 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006160 return PyErr_NoMemory();
6161 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006162 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006163 if (repr == NULL) {
6164 return NULL;
6165 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006166
Victor Stinner62ec3312016-09-06 17:04:34 -07006167 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006168 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006169 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006170
Victor Stinner62ec3312016-09-06 17:04:34 -07006171 /* U+0000-U+00ff range */
6172 if (ch < 0x100) {
6173 if (ch >= ' ' && ch < 127) {
6174 if (ch != '\\') {
6175 /* Copy printable US ASCII as-is */
6176 *p++ = (char) ch;
6177 }
6178 /* Escape backslashes */
6179 else {
6180 *p++ = '\\';
6181 *p++ = '\\';
6182 }
6183 }
Victor Stinner358af132015-10-12 22:36:57 +02006184
Victor Stinner62ec3312016-09-06 17:04:34 -07006185 /* Map special whitespace to '\t', \n', '\r' */
6186 else if (ch == '\t') {
6187 *p++ = '\\';
6188 *p++ = 't';
6189 }
6190 else if (ch == '\n') {
6191 *p++ = '\\';
6192 *p++ = 'n';
6193 }
6194 else if (ch == '\r') {
6195 *p++ = '\\';
6196 *p++ = 'r';
6197 }
6198
6199 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6200 else {
6201 *p++ = '\\';
6202 *p++ = 'x';
6203 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6204 *p++ = Py_hexdigits[ch & 0x000F];
6205 }
Tim Petersced69f82003-09-16 20:30:58 +00006206 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006207 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006208 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209 *p++ = '\\';
6210 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006211 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6212 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6213 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6214 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006215 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006216 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6217 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006218
Victor Stinner62ec3312016-09-06 17:04:34 -07006219 /* Make sure that the first two digits are zero */
6220 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006221 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006222 *p++ = 'U';
6223 *p++ = '0';
6224 *p++ = '0';
6225 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6226 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6227 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6228 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6229 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6230 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006231 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233
Victor Stinner62ec3312016-09-06 17:04:34 -07006234 assert(p - PyBytes_AS_STRING(repr) > 0);
6235 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6236 return NULL;
6237 }
6238 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239}
6240
Alexander Belopolsky40018472011-02-26 01:02:56 +00006241PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006242PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6243 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006245 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006246 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006247 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006248 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006249 }
6250
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006251 result = PyUnicode_AsUnicodeEscapeString(tmp);
6252 Py_DECREF(tmp);
6253 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254}
6255
6256/* --- Raw Unicode Escape Codec ------------------------------------------- */
6257
Alexander Belopolsky40018472011-02-26 01:02:56 +00006258PyObject *
6259PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006260 Py_ssize_t size,
6261 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006262{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006263 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006264 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006265 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006266 PyObject *errorHandler = NULL;
6267 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006268
Victor Stinner62ec3312016-09-06 17:04:34 -07006269 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006270 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006271 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006272
Guido van Rossumd57fd912000-03-10 22:53:23 +00006273 /* Escaped strings will always be longer than the resulting
6274 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006275 length after conversion to the true value. (But decoding error
6276 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006277 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006278 writer.min_length = size;
6279 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6280 goto onError;
6281 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006282
Guido van Rossumd57fd912000-03-10 22:53:23 +00006283 end = s + size;
6284 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006285 unsigned char c = (unsigned char) *s++;
6286 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006287 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006288 Py_ssize_t startinpos;
6289 Py_ssize_t endinpos;
6290 const char *message;
6291
6292#define WRITE_CHAR(ch) \
6293 do { \
6294 if (ch <= writer.maxchar) { \
6295 assert(writer.pos < writer.size); \
6296 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6297 } \
6298 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6299 goto onError; \
6300 } \
6301 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006302
Benjamin Peterson29060642009-01-31 22:14:21 +00006303 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006304 if (c != '\\' || s >= end) {
6305 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006306 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006307 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006308
Victor Stinner62ec3312016-09-06 17:04:34 -07006309 c = (unsigned char) *s++;
6310 if (c == 'u') {
6311 count = 4;
6312 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006313 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006314 else if (c == 'U') {
6315 count = 8;
6316 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006317 }
6318 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006319 assert(writer.pos < writer.size);
6320 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6321 WRITE_CHAR(c);
6322 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006323 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006324 startinpos = s - starts - 2;
6325
6326 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6327 for (ch = 0; count && s < end; ++s, --count) {
6328 c = (unsigned char)*s;
6329 ch <<= 4;
6330 if (c >= '0' && c <= '9') {
6331 ch += c - '0';
6332 }
6333 else if (c >= 'a' && c <= 'f') {
6334 ch += c - ('a' - 10);
6335 }
6336 else if (c >= 'A' && c <= 'F') {
6337 ch += c - ('A' - 10);
6338 }
6339 else {
6340 break;
6341 }
6342 }
6343 if (!count) {
6344 if (ch <= MAX_UNICODE) {
6345 WRITE_CHAR(ch);
6346 continue;
6347 }
6348 message = "\\Uxxxxxxxx out of range";
6349 }
6350
6351 endinpos = s-starts;
6352 writer.min_length = end - s + writer.pos;
6353 if (unicode_decode_call_errorhandler_writer(
6354 errors, &errorHandler,
6355 "rawunicodeescape", message,
6356 &starts, &end, &startinpos, &endinpos, &exc, &s,
6357 &writer)) {
6358 goto onError;
6359 }
6360 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6361 goto onError;
6362 }
6363
6364#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006365 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006366 Py_XDECREF(errorHandler);
6367 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006368 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006369
Benjamin Peterson29060642009-01-31 22:14:21 +00006370 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006371 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006372 Py_XDECREF(errorHandler);
6373 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006374 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006375
Guido van Rossumd57fd912000-03-10 22:53:23 +00006376}
6377
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006378
Alexander Belopolsky40018472011-02-26 01:02:56 +00006379PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006380PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006381{
Victor Stinner62ec3312016-09-06 17:04:34 -07006382 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006383 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006384 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006385 int kind;
6386 void *data;
6387 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006388
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006389 if (!PyUnicode_Check(unicode)) {
6390 PyErr_BadArgument();
6391 return NULL;
6392 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006393 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006394 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006395 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006396 kind = PyUnicode_KIND(unicode);
6397 data = PyUnicode_DATA(unicode);
6398 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006399 if (kind == PyUnicode_1BYTE_KIND) {
6400 return PyBytes_FromStringAndSize(data, len);
6401 }
Victor Stinner0e368262011-11-10 20:12:49 +01006402
Victor Stinner62ec3312016-09-06 17:04:34 -07006403 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6404 bytes, and 1 byte characters 4. */
6405 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006406
Victor Stinner62ec3312016-09-06 17:04:34 -07006407 if (len > PY_SSIZE_T_MAX / expandsize) {
6408 return PyErr_NoMemory();
6409 }
6410 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6411 if (repr == NULL) {
6412 return NULL;
6413 }
6414 if (len == 0) {
6415 return repr;
6416 }
6417
6418 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006419 for (pos = 0; pos < len; pos++) {
6420 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006421
Victor Stinner62ec3312016-09-06 17:04:34 -07006422 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6423 if (ch < 0x100) {
6424 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006425 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006426 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6427 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006428 *p++ = '\\';
6429 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006430 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6431 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6432 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6433 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006434 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006435 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6436 else {
6437 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6438 *p++ = '\\';
6439 *p++ = 'U';
6440 *p++ = '0';
6441 *p++ = '0';
6442 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6443 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6444 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6445 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6446 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6447 *p++ = Py_hexdigits[ch & 15];
6448 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006449 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006450
Victor Stinner62ec3312016-09-06 17:04:34 -07006451 assert(p > PyBytes_AS_STRING(repr));
6452 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6453 return NULL;
6454 }
6455 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006456}
6457
Alexander Belopolsky40018472011-02-26 01:02:56 +00006458PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006459PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6460 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006461{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006462 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006463 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006464 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006465 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006466 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6467 Py_DECREF(tmp);
6468 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006469}
6470
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006471/* --- Unicode Internal Codec ------------------------------------------- */
6472
Alexander Belopolsky40018472011-02-26 01:02:56 +00006473PyObject *
6474_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006475 Py_ssize_t size,
6476 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006477{
6478 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006479 Py_ssize_t startinpos;
6480 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006481 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006482 const char *end;
6483 const char *reason;
6484 PyObject *errorHandler = NULL;
6485 PyObject *exc = NULL;
6486
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006487 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006488 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006489 1))
6490 return NULL;
6491
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006492 if (size == 0)
6493 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006494
Victor Stinner8f674cc2013-04-17 23:02:17 +02006495 _PyUnicodeWriter_Init(&writer);
6496 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6497 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006499 }
6500 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006501
Victor Stinner8f674cc2013-04-17 23:02:17 +02006502 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006503 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006504 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006505 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006506 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006507 endinpos = end-starts;
6508 reason = "truncated input";
6509 goto error;
6510 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006511 /* We copy the raw representation one byte at a time because the
6512 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006513 ((char *) &uch)[0] = s[0];
6514 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006515#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006516 ((char *) &uch)[2] = s[2];
6517 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006518#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006519 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006520#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006521 /* We have to sanity check the raw data, otherwise doom looms for
6522 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006523 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006524 endinpos = s - starts + Py_UNICODE_SIZE;
6525 reason = "illegal code point (> 0x10FFFF)";
6526 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006527 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006528#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006529 s += Py_UNICODE_SIZE;
6530#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006531 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006532 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006533 Py_UNICODE uch2;
6534 ((char *) &uch2)[0] = s[0];
6535 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006536 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006537 {
Victor Stinner551ac952011-11-29 22:58:13 +01006538 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006539 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006540 }
6541 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006542#endif
6543
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006544 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006545 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006546 continue;
6547
6548 error:
6549 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006550 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006551 errors, &errorHandler,
6552 "unicode_internal", reason,
6553 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006554 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006555 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006556 }
6557
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006558 Py_XDECREF(errorHandler);
6559 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006560 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006561
Benjamin Peterson29060642009-01-31 22:14:21 +00006562 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006563 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006564 Py_XDECREF(errorHandler);
6565 Py_XDECREF(exc);
6566 return NULL;
6567}
6568
Guido van Rossumd57fd912000-03-10 22:53:23 +00006569/* --- Latin-1 Codec ------------------------------------------------------ */
6570
Alexander Belopolsky40018472011-02-26 01:02:56 +00006571PyObject *
6572PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006573 Py_ssize_t size,
6574 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006575{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006576 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006577 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006578}
6579
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006580/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006581static void
6582make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006583 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006584 PyObject *unicode,
6585 Py_ssize_t startpos, Py_ssize_t endpos,
6586 const char *reason)
6587{
6588 if (*exceptionObject == NULL) {
6589 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006590 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006591 encoding, unicode, startpos, endpos, reason);
6592 }
6593 else {
6594 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6595 goto onError;
6596 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6597 goto onError;
6598 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6599 goto onError;
6600 return;
6601 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006602 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006603 }
6604}
6605
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006606/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006607static void
6608raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006609 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006610 PyObject *unicode,
6611 Py_ssize_t startpos, Py_ssize_t endpos,
6612 const char *reason)
6613{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006614 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006615 encoding, unicode, startpos, endpos, reason);
6616 if (*exceptionObject != NULL)
6617 PyCodec_StrictErrors(*exceptionObject);
6618}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006619
6620/* error handling callback helper:
6621 build arguments, call the callback and check the arguments,
6622 put the result into newpos and return the replacement string, which
6623 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006624static PyObject *
6625unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006626 PyObject **errorHandler,
6627 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006628 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006629 Py_ssize_t startpos, Py_ssize_t endpos,
6630 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006631{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006632 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006633 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006634 PyObject *restuple;
6635 PyObject *resunicode;
6636
6637 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006638 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006639 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006640 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006641 }
6642
Benjamin Petersonbac79492012-01-14 13:34:47 -05006643 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006644 return NULL;
6645 len = PyUnicode_GET_LENGTH(unicode);
6646
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006647 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006648 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006649 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006650 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006651
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006652 restuple = PyObject_CallFunctionObjArgs(
6653 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006654 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006655 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006656 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006657 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006658 Py_DECREF(restuple);
6659 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006660 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006661 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006662 &resunicode, newpos)) {
6663 Py_DECREF(restuple);
6664 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006665 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006666 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6667 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6668 Py_DECREF(restuple);
6669 return NULL;
6670 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006671 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006672 *newpos = len + *newpos;
6673 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006674 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006675 Py_DECREF(restuple);
6676 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006677 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006678 Py_INCREF(resunicode);
6679 Py_DECREF(restuple);
6680 return resunicode;
6681}
6682
Alexander Belopolsky40018472011-02-26 01:02:56 +00006683static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006684unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006685 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006686 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006687{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006688 /* input state */
6689 Py_ssize_t pos=0, size;
6690 int kind;
6691 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006692 /* pointer into the output */
6693 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006694 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6695 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006696 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006698 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006699 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006700 /* output object */
6701 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006702
Benjamin Petersonbac79492012-01-14 13:34:47 -05006703 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006704 return NULL;
6705 size = PyUnicode_GET_LENGTH(unicode);
6706 kind = PyUnicode_KIND(unicode);
6707 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006708 /* allocate enough for a simple encoding without
6709 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006710 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006711 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006712
6713 _PyBytesWriter_Init(&writer);
6714 str = _PyBytesWriter_Alloc(&writer, size);
6715 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006716 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006717
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006718 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006719 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006720
Benjamin Peterson29060642009-01-31 22:14:21 +00006721 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006722 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006723 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006724 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006725 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006726 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006728 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006730 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006731 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006732 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006733
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006734 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006736
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006737 /* Only overallocate the buffer if it's not the last write */
6738 writer.overallocate = (collend < size);
6739
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006741 if (error_handler == _Py_ERROR_UNKNOWN)
6742 error_handler = get_error_handler(errors);
6743
6744 switch (error_handler) {
6745 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006746 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006747 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006748
6749 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006750 memset(str, '?', collend - collstart);
6751 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006752 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006753 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006754 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 break;
Victor Stinner50149202015-09-22 00:26:54 +02006756
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006757 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006758 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006759 writer.min_size -= (collend - collstart);
6760 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006761 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006762 if (str == NULL)
6763 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006764 pos = collend;
6765 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006766
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006767 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006768 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006769 writer.min_size -= (collend - collstart);
6770 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006771 unicode, collstart, collend);
6772 if (str == NULL)
6773 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006774 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006775 break;
Victor Stinner50149202015-09-22 00:26:54 +02006776
Victor Stinnerc3713e92015-09-29 12:32:13 +02006777 case _Py_ERROR_SURROGATEESCAPE:
6778 for (i = collstart; i < collend; ++i) {
6779 ch = PyUnicode_READ(kind, data, i);
6780 if (ch < 0xdc80 || 0xdcff < ch) {
6781 /* Not a UTF-8b surrogate */
6782 break;
6783 }
6784 *str++ = (char)(ch - 0xdc00);
6785 ++pos;
6786 }
6787 if (i >= collend)
6788 break;
6789 collstart = pos;
6790 assert(collstart != collend);
6791 /* fallback to general error handling */
6792
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006794 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6795 encoding, reason, unicode, &exc,
6796 collstart, collend, &newpos);
6797 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006798 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006799
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006800 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006801 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006802
Victor Stinner6bd525b2015-10-09 13:10:05 +02006803 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006804 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006805 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006806 PyBytes_AS_STRING(rep),
6807 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006808 if (str == NULL)
6809 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006810 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006811 else {
6812 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006813
Victor Stinner6bd525b2015-10-09 13:10:05 +02006814 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006815 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006816
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006817 if (limit == 256 ?
6818 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6819 !PyUnicode_IS_ASCII(rep))
6820 {
6821 /* Not all characters are smaller than limit */
6822 raise_encode_exception(&exc, encoding, unicode,
6823 collstart, collend, reason);
6824 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006825 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006826 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6827 str = _PyBytesWriter_WriteBytes(&writer, str,
6828 PyUnicode_DATA(rep),
6829 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006830 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006831 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006832 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006833 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006834
6835 /* If overallocation was disabled, ensure that it was the last
6836 write. Otherwise, we missed an optimization */
6837 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006838 }
6839 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006840
Victor Stinner50149202015-09-22 00:26:54 +02006841 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006842 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006843 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006844
6845 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006846 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006847 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006848 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006849 Py_XDECREF(exc);
6850 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006851}
6852
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006853/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006854PyObject *
6855PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006856 Py_ssize_t size,
6857 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006858{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006859 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006860 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006861 if (unicode == NULL)
6862 return NULL;
6863 result = unicode_encode_ucs1(unicode, errors, 256);
6864 Py_DECREF(unicode);
6865 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006866}
6867
Alexander Belopolsky40018472011-02-26 01:02:56 +00006868PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006869_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006870{
6871 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006872 PyErr_BadArgument();
6873 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006874 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006875 if (PyUnicode_READY(unicode) == -1)
6876 return NULL;
6877 /* Fast path: if it is a one-byte string, construct
6878 bytes object directly. */
6879 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6880 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6881 PyUnicode_GET_LENGTH(unicode));
6882 /* Non-Latin-1 characters present. Defer to above function to
6883 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006884 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006885}
6886
6887PyObject*
6888PyUnicode_AsLatin1String(PyObject *unicode)
6889{
6890 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006891}
6892
6893/* --- 7-bit ASCII Codec -------------------------------------------------- */
6894
Alexander Belopolsky40018472011-02-26 01:02:56 +00006895PyObject *
6896PyUnicode_DecodeASCII(const char *s,
6897 Py_ssize_t size,
6898 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006899{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006900 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006901 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006902 int kind;
6903 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006904 Py_ssize_t startinpos;
6905 Py_ssize_t endinpos;
6906 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006907 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006908 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006909 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006910 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006911
Guido van Rossumd57fd912000-03-10 22:53:23 +00006912 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006913 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006914
Guido van Rossumd57fd912000-03-10 22:53:23 +00006915 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006916 if (size == 1 && (unsigned char)s[0] < 128)
6917 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006918
Victor Stinner8f674cc2013-04-17 23:02:17 +02006919 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006920 writer.min_length = size;
6921 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006922 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006923
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006924 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006925 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006926 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006927 writer.pos = outpos;
6928 if (writer.pos == size)
6929 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006930
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006931 s += writer.pos;
6932 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006933 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006934 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006935 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006936 PyUnicode_WRITE(kind, data, writer.pos, c);
6937 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006938 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006939 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006940 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006941
6942 /* byte outsize range 0x00..0x7f: call the error handler */
6943
6944 if (error_handler == _Py_ERROR_UNKNOWN)
6945 error_handler = get_error_handler(errors);
6946
6947 switch (error_handler)
6948 {
6949 case _Py_ERROR_REPLACE:
6950 case _Py_ERROR_SURROGATEESCAPE:
6951 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006952 but we may switch to UCS2 at the first write */
6953 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6954 goto onError;
6955 kind = writer.kind;
6956 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006957
6958 if (error_handler == _Py_ERROR_REPLACE)
6959 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6960 else
6961 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6962 writer.pos++;
6963 ++s;
6964 break;
6965
6966 case _Py_ERROR_IGNORE:
6967 ++s;
6968 break;
6969
6970 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006971 startinpos = s-starts;
6972 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006973 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006974 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006975 "ascii", "ordinal not in range(128)",
6976 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006977 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006978 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006979 kind = writer.kind;
6980 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006981 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006982 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006983 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006984 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006985 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006986
Benjamin Peterson29060642009-01-31 22:14:21 +00006987 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006988 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006989 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006990 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006991 return NULL;
6992}
6993
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006994/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006995PyObject *
6996PyUnicode_EncodeASCII(const Py_UNICODE *p,
6997 Py_ssize_t size,
6998 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006999{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007000 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007001 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007002 if (unicode == NULL)
7003 return NULL;
7004 result = unicode_encode_ucs1(unicode, errors, 128);
7005 Py_DECREF(unicode);
7006 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007007}
7008
Alexander Belopolsky40018472011-02-26 01:02:56 +00007009PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007010_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007011{
7012 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007013 PyErr_BadArgument();
7014 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007015 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007016 if (PyUnicode_READY(unicode) == -1)
7017 return NULL;
7018 /* Fast path: if it is an ASCII-only string, construct bytes object
7019 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007020 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007021 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7022 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007023 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007024}
7025
7026PyObject *
7027PyUnicode_AsASCIIString(PyObject *unicode)
7028{
7029 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007030}
7031
Steve Dowercc16be82016-09-08 10:35:16 -07007032#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007033
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007034/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007035
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007036#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007037#define NEED_RETRY
7038#endif
7039
Victor Stinner3a50e702011-10-18 21:21:00 +02007040#ifndef WC_ERR_INVALID_CHARS
7041# define WC_ERR_INVALID_CHARS 0x0080
7042#endif
7043
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007044static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007045code_page_name(UINT code_page, PyObject **obj)
7046{
7047 *obj = NULL;
7048 if (code_page == CP_ACP)
7049 return "mbcs";
7050 if (code_page == CP_UTF7)
7051 return "CP_UTF7";
7052 if (code_page == CP_UTF8)
7053 return "CP_UTF8";
7054
7055 *obj = PyBytes_FromFormat("cp%u", code_page);
7056 if (*obj == NULL)
7057 return NULL;
7058 return PyBytes_AS_STRING(*obj);
7059}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007060
Victor Stinner3a50e702011-10-18 21:21:00 +02007061static DWORD
7062decode_code_page_flags(UINT code_page)
7063{
7064 if (code_page == CP_UTF7) {
7065 /* The CP_UTF7 decoder only supports flags=0 */
7066 return 0;
7067 }
7068 else
7069 return MB_ERR_INVALID_CHARS;
7070}
7071
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007072/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007073 * Decode a byte string from a Windows code page into unicode object in strict
7074 * mode.
7075 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007076 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7077 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007078 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007079static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007080decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007081 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 const char *in,
7083 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007084{
Victor Stinner3a50e702011-10-18 21:21:00 +02007085 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007086 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007087 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007088
7089 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007090 assert(insize > 0);
7091 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7092 if (outsize <= 0)
7093 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007094
7095 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007096 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007097 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007098 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007099 if (*v == NULL)
7100 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007101 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007102 }
7103 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007104 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007105 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007106 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007107 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007108 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007109 }
7110
7111 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007112 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7113 if (outsize <= 0)
7114 goto error;
7115 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007116
Victor Stinner3a50e702011-10-18 21:21:00 +02007117error:
7118 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7119 return -2;
7120 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007121 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007122}
7123
Victor Stinner3a50e702011-10-18 21:21:00 +02007124/*
7125 * Decode a byte string from a code page into unicode object with an error
7126 * handler.
7127 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007128 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007129 * UnicodeDecodeError exception and returns -1 on error.
7130 */
7131static int
7132decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007133 PyObject **v,
7134 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007135 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007136{
7137 const char *startin = in;
7138 const char *endin = in + size;
7139 const DWORD flags = decode_code_page_flags(code_page);
7140 /* Ideally, we should get reason from FormatMessage. This is the Windows
7141 2000 English version of the message. */
7142 const char *reason = "No mapping for the Unicode character exists "
7143 "in the target code page.";
7144 /* each step cannot decode more than 1 character, but a character can be
7145 represented as a surrogate pair */
7146 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007147 int insize;
7148 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007149 PyObject *errorHandler = NULL;
7150 PyObject *exc = NULL;
7151 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007152 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007153 DWORD err;
7154 int ret = -1;
7155
7156 assert(size > 0);
7157
7158 encoding = code_page_name(code_page, &encoding_obj);
7159 if (encoding == NULL)
7160 return -1;
7161
Victor Stinner7d00cc12014-03-17 23:08:06 +01007162 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7164 UnicodeDecodeError. */
7165 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7166 if (exc != NULL) {
7167 PyCodec_StrictErrors(exc);
7168 Py_CLEAR(exc);
7169 }
7170 goto error;
7171 }
7172
7173 if (*v == NULL) {
7174 /* Create unicode object */
7175 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7176 PyErr_NoMemory();
7177 goto error;
7178 }
Victor Stinnerab595942011-12-17 04:59:06 +01007179 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007180 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007181 if (*v == NULL)
7182 goto error;
7183 startout = PyUnicode_AS_UNICODE(*v);
7184 }
7185 else {
7186 /* Extend unicode object */
7187 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7188 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7189 PyErr_NoMemory();
7190 goto error;
7191 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007192 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 goto error;
7194 startout = PyUnicode_AS_UNICODE(*v) + n;
7195 }
7196
7197 /* Decode the byte string character per character */
7198 out = startout;
7199 while (in < endin)
7200 {
7201 /* Decode a character */
7202 insize = 1;
7203 do
7204 {
7205 outsize = MultiByteToWideChar(code_page, flags,
7206 in, insize,
7207 buffer, Py_ARRAY_LENGTH(buffer));
7208 if (outsize > 0)
7209 break;
7210 err = GetLastError();
7211 if (err != ERROR_NO_UNICODE_TRANSLATION
7212 && err != ERROR_INSUFFICIENT_BUFFER)
7213 {
7214 PyErr_SetFromWindowsErr(0);
7215 goto error;
7216 }
7217 insize++;
7218 }
7219 /* 4=maximum length of a UTF-8 sequence */
7220 while (insize <= 4 && (in + insize) <= endin);
7221
7222 if (outsize <= 0) {
7223 Py_ssize_t startinpos, endinpos, outpos;
7224
Victor Stinner7d00cc12014-03-17 23:08:06 +01007225 /* last character in partial decode? */
7226 if (in + insize >= endin && !final)
7227 break;
7228
Victor Stinner3a50e702011-10-18 21:21:00 +02007229 startinpos = in - startin;
7230 endinpos = startinpos + 1;
7231 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007232 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 errors, &errorHandler,
7234 encoding, reason,
7235 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007236 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007237 {
7238 goto error;
7239 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007240 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 }
7242 else {
7243 in += insize;
7244 memcpy(out, buffer, outsize * sizeof(wchar_t));
7245 out += outsize;
7246 }
7247 }
7248
7249 /* write a NUL character at the end */
7250 *out = 0;
7251
7252 /* Extend unicode object */
7253 outsize = out - startout;
7254 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007255 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007257 /* (in - startin) <= size and size is an int */
7258 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007259
7260error:
7261 Py_XDECREF(encoding_obj);
7262 Py_XDECREF(errorHandler);
7263 Py_XDECREF(exc);
7264 return ret;
7265}
7266
Victor Stinner3a50e702011-10-18 21:21:00 +02007267static PyObject *
7268decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007269 const char *s, Py_ssize_t size,
7270 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007271{
Victor Stinner76a31a62011-11-04 00:05:13 +01007272 PyObject *v = NULL;
7273 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007274
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 if (code_page < 0) {
7276 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7277 return NULL;
7278 }
7279
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007280 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007281 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007282
Victor Stinner76a31a62011-11-04 00:05:13 +01007283 do
7284 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007285#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007286 if (size > INT_MAX) {
7287 chunk_size = INT_MAX;
7288 final = 0;
7289 done = 0;
7290 }
7291 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007292#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007293 {
7294 chunk_size = (int)size;
7295 final = (consumed == NULL);
7296 done = 1;
7297 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007298
Victor Stinner76a31a62011-11-04 00:05:13 +01007299 if (chunk_size == 0 && done) {
7300 if (v != NULL)
7301 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007302 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007303 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007304
Victor Stinner76a31a62011-11-04 00:05:13 +01007305 converted = decode_code_page_strict(code_page, &v,
7306 s, chunk_size);
7307 if (converted == -2)
7308 converted = decode_code_page_errors(code_page, &v,
7309 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007310 errors, final);
7311 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007312
7313 if (converted < 0) {
7314 Py_XDECREF(v);
7315 return NULL;
7316 }
7317
7318 if (consumed)
7319 *consumed += converted;
7320
7321 s += converted;
7322 size -= converted;
7323 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007324
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007325 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007326}
7327
Alexander Belopolsky40018472011-02-26 01:02:56 +00007328PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007329PyUnicode_DecodeCodePageStateful(int code_page,
7330 const char *s,
7331 Py_ssize_t size,
7332 const char *errors,
7333 Py_ssize_t *consumed)
7334{
7335 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7336}
7337
7338PyObject *
7339PyUnicode_DecodeMBCSStateful(const char *s,
7340 Py_ssize_t size,
7341 const char *errors,
7342 Py_ssize_t *consumed)
7343{
7344 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7345}
7346
7347PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007348PyUnicode_DecodeMBCS(const char *s,
7349 Py_ssize_t size,
7350 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007351{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007352 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7353}
7354
Victor Stinner3a50e702011-10-18 21:21:00 +02007355static DWORD
7356encode_code_page_flags(UINT code_page, const char *errors)
7357{
7358 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007359 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007360 }
7361 else if (code_page == CP_UTF7) {
7362 /* CP_UTF7 only supports flags=0 */
7363 return 0;
7364 }
7365 else {
7366 if (errors != NULL && strcmp(errors, "replace") == 0)
7367 return 0;
7368 else
7369 return WC_NO_BEST_FIT_CHARS;
7370 }
7371}
7372
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007373/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007374 * Encode a Unicode string to a Windows code page into a byte string in strict
7375 * mode.
7376 *
7377 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007378 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007379 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007380static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007381encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007382 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007383 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007384{
Victor Stinner554f3f02010-06-16 23:33:54 +00007385 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007386 BOOL *pusedDefaultChar = &usedDefaultChar;
7387 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007388 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007389 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 const DWORD flags = encode_code_page_flags(code_page, NULL);
7391 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007392 /* Create a substring so that we can get the UTF-16 representation
7393 of just the slice under consideration. */
7394 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007395
Martin v. Löwis3d325192011-11-04 18:23:06 +01007396 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007397
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007399 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007400 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007401 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007402
Victor Stinner2fc507f2011-11-04 20:06:39 +01007403 substring = PyUnicode_Substring(unicode, offset, offset+len);
7404 if (substring == NULL)
7405 return -1;
7406 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7407 if (p == NULL) {
7408 Py_DECREF(substring);
7409 return -1;
7410 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007411 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007412
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007413 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007414 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007415 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 NULL, 0,
7417 NULL, pusedDefaultChar);
7418 if (outsize <= 0)
7419 goto error;
7420 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007421 if (pusedDefaultChar && *pusedDefaultChar) {
7422 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007423 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007424 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007425
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007427 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007429 if (*outbytes == NULL) {
7430 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007431 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007432 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007433 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007434 }
7435 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007436 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 const Py_ssize_t n = PyBytes_Size(*outbytes);
7438 if (outsize > PY_SSIZE_T_MAX - n) {
7439 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007440 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007441 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007442 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007443 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7444 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007446 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007447 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007448 }
7449
7450 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007451 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007452 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007453 out, outsize,
7454 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007455 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 if (outsize <= 0)
7457 goto error;
7458 if (pusedDefaultChar && *pusedDefaultChar)
7459 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007460 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007461
Victor Stinner3a50e702011-10-18 21:21:00 +02007462error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007463 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007464 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7465 return -2;
7466 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007467 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007468}
7469
Victor Stinner3a50e702011-10-18 21:21:00 +02007470/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007471 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007472 * error handler.
7473 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007474 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 * -1 on other error.
7476 */
7477static int
7478encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007479 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007480 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007481{
Victor Stinner3a50e702011-10-18 21:21:00 +02007482 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007483 Py_ssize_t pos = unicode_offset;
7484 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007485 /* Ideally, we should get reason from FormatMessage. This is the Windows
7486 2000 English version of the message. */
7487 const char *reason = "invalid character";
7488 /* 4=maximum length of a UTF-8 sequence */
7489 char buffer[4];
7490 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7491 Py_ssize_t outsize;
7492 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007493 PyObject *errorHandler = NULL;
7494 PyObject *exc = NULL;
7495 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007496 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007497 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007498 PyObject *rep;
7499 int ret = -1;
7500
7501 assert(insize > 0);
7502
7503 encoding = code_page_name(code_page, &encoding_obj);
7504 if (encoding == NULL)
7505 return -1;
7506
7507 if (errors == NULL || strcmp(errors, "strict") == 0) {
7508 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7509 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007510 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007511 if (exc != NULL) {
7512 PyCodec_StrictErrors(exc);
7513 Py_DECREF(exc);
7514 }
7515 Py_XDECREF(encoding_obj);
7516 return -1;
7517 }
7518
7519 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7520 pusedDefaultChar = &usedDefaultChar;
7521 else
7522 pusedDefaultChar = NULL;
7523
7524 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7525 PyErr_NoMemory();
7526 goto error;
7527 }
7528 outsize = insize * Py_ARRAY_LENGTH(buffer);
7529
7530 if (*outbytes == NULL) {
7531 /* Create string object */
7532 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7533 if (*outbytes == NULL)
7534 goto error;
7535 out = PyBytes_AS_STRING(*outbytes);
7536 }
7537 else {
7538 /* Extend string object */
7539 Py_ssize_t n = PyBytes_Size(*outbytes);
7540 if (n > PY_SSIZE_T_MAX - outsize) {
7541 PyErr_NoMemory();
7542 goto error;
7543 }
7544 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7545 goto error;
7546 out = PyBytes_AS_STRING(*outbytes) + n;
7547 }
7548
7549 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007550 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007551 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007552 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7553 wchar_t chars[2];
7554 int charsize;
7555 if (ch < 0x10000) {
7556 chars[0] = (wchar_t)ch;
7557 charsize = 1;
7558 }
7559 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007560 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7561 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007562 charsize = 2;
7563 }
7564
Victor Stinner3a50e702011-10-18 21:21:00 +02007565 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007566 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007567 buffer, Py_ARRAY_LENGTH(buffer),
7568 NULL, pusedDefaultChar);
7569 if (outsize > 0) {
7570 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7571 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007572 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007573 memcpy(out, buffer, outsize);
7574 out += outsize;
7575 continue;
7576 }
7577 }
7578 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7579 PyErr_SetFromWindowsErr(0);
7580 goto error;
7581 }
7582
Victor Stinner3a50e702011-10-18 21:21:00 +02007583 rep = unicode_encode_call_errorhandler(
7584 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007585 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007586 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007587 if (rep == NULL)
7588 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007589 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007590
7591 if (PyBytes_Check(rep)) {
7592 outsize = PyBytes_GET_SIZE(rep);
7593 if (outsize != 1) {
7594 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7595 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7596 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7597 Py_DECREF(rep);
7598 goto error;
7599 }
7600 out = PyBytes_AS_STRING(*outbytes) + offset;
7601 }
7602 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7603 out += outsize;
7604 }
7605 else {
7606 Py_ssize_t i;
7607 enum PyUnicode_Kind kind;
7608 void *data;
7609
Benjamin Petersonbac79492012-01-14 13:34:47 -05007610 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007611 Py_DECREF(rep);
7612 goto error;
7613 }
7614
7615 outsize = PyUnicode_GET_LENGTH(rep);
7616 if (outsize != 1) {
7617 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7618 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7619 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7620 Py_DECREF(rep);
7621 goto error;
7622 }
7623 out = PyBytes_AS_STRING(*outbytes) + offset;
7624 }
7625 kind = PyUnicode_KIND(rep);
7626 data = PyUnicode_DATA(rep);
7627 for (i=0; i < outsize; i++) {
7628 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7629 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007630 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007631 encoding, unicode,
7632 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007633 "unable to encode error handler result to ASCII");
7634 Py_DECREF(rep);
7635 goto error;
7636 }
7637 *out = (unsigned char)ch;
7638 out++;
7639 }
7640 }
7641 Py_DECREF(rep);
7642 }
7643 /* write a NUL byte */
7644 *out = 0;
7645 outsize = out - PyBytes_AS_STRING(*outbytes);
7646 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7647 if (_PyBytes_Resize(outbytes, outsize) < 0)
7648 goto error;
7649 ret = 0;
7650
7651error:
7652 Py_XDECREF(encoding_obj);
7653 Py_XDECREF(errorHandler);
7654 Py_XDECREF(exc);
7655 return ret;
7656}
7657
Victor Stinner3a50e702011-10-18 21:21:00 +02007658static PyObject *
7659encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007660 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007661 const char *errors)
7662{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007663 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007664 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007665 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007666 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007667
Victor Stinner29dacf22015-01-26 16:41:32 +01007668 if (!PyUnicode_Check(unicode)) {
7669 PyErr_BadArgument();
7670 return NULL;
7671 }
7672
Benjamin Petersonbac79492012-01-14 13:34:47 -05007673 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007674 return NULL;
7675 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007676
Victor Stinner3a50e702011-10-18 21:21:00 +02007677 if (code_page < 0) {
7678 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7679 return NULL;
7680 }
7681
Martin v. Löwis3d325192011-11-04 18:23:06 +01007682 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007683 return PyBytes_FromStringAndSize(NULL, 0);
7684
Victor Stinner7581cef2011-11-03 22:32:33 +01007685 offset = 0;
7686 do
7687 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007688#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007689 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007690 chunks. */
7691 if (len > INT_MAX/2) {
7692 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007693 done = 0;
7694 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007695 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007696#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007697 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007698 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007699 done = 1;
7700 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007701
Victor Stinner76a31a62011-11-04 00:05:13 +01007702 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007703 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007704 errors);
7705 if (ret == -2)
7706 ret = encode_code_page_errors(code_page, &outbytes,
7707 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007708 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007709 if (ret < 0) {
7710 Py_XDECREF(outbytes);
7711 return NULL;
7712 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007713
Victor Stinner7581cef2011-11-03 22:32:33 +01007714 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007715 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007716 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007717
Victor Stinner3a50e702011-10-18 21:21:00 +02007718 return outbytes;
7719}
7720
7721PyObject *
7722PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7723 Py_ssize_t size,
7724 const char *errors)
7725{
Victor Stinner7581cef2011-11-03 22:32:33 +01007726 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007727 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007728 if (unicode == NULL)
7729 return NULL;
7730 res = encode_code_page(CP_ACP, unicode, errors);
7731 Py_DECREF(unicode);
7732 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007733}
7734
7735PyObject *
7736PyUnicode_EncodeCodePage(int code_page,
7737 PyObject *unicode,
7738 const char *errors)
7739{
Victor Stinner7581cef2011-11-03 22:32:33 +01007740 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007741}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007742
Alexander Belopolsky40018472011-02-26 01:02:56 +00007743PyObject *
7744PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007745{
Victor Stinner7581cef2011-11-03 22:32:33 +01007746 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007747}
7748
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007749#undef NEED_RETRY
7750
Steve Dowercc16be82016-09-08 10:35:16 -07007751#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007752
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753/* --- Character Mapping Codec -------------------------------------------- */
7754
Victor Stinnerfb161b12013-04-18 01:44:27 +02007755static int
7756charmap_decode_string(const char *s,
7757 Py_ssize_t size,
7758 PyObject *mapping,
7759 const char *errors,
7760 _PyUnicodeWriter *writer)
7761{
7762 const char *starts = s;
7763 const char *e;
7764 Py_ssize_t startinpos, endinpos;
7765 PyObject *errorHandler = NULL, *exc = NULL;
7766 Py_ssize_t maplen;
7767 enum PyUnicode_Kind mapkind;
7768 void *mapdata;
7769 Py_UCS4 x;
7770 unsigned char ch;
7771
7772 if (PyUnicode_READY(mapping) == -1)
7773 return -1;
7774
7775 maplen = PyUnicode_GET_LENGTH(mapping);
7776 mapdata = PyUnicode_DATA(mapping);
7777 mapkind = PyUnicode_KIND(mapping);
7778
7779 e = s + size;
7780
7781 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7782 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7783 * is disabled in encoding aliases, latin1 is preferred because
7784 * its implementation is faster. */
7785 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7786 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7787 Py_UCS4 maxchar = writer->maxchar;
7788
7789 assert (writer->kind == PyUnicode_1BYTE_KIND);
7790 while (s < e) {
7791 ch = *s;
7792 x = mapdata_ucs1[ch];
7793 if (x > maxchar) {
7794 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7795 goto onError;
7796 maxchar = writer->maxchar;
7797 outdata = (Py_UCS1 *)writer->data;
7798 }
7799 outdata[writer->pos] = x;
7800 writer->pos++;
7801 ++s;
7802 }
7803 return 0;
7804 }
7805
7806 while (s < e) {
7807 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7808 enum PyUnicode_Kind outkind = writer->kind;
7809 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7810 if (outkind == PyUnicode_1BYTE_KIND) {
7811 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7812 Py_UCS4 maxchar = writer->maxchar;
7813 while (s < e) {
7814 ch = *s;
7815 x = mapdata_ucs2[ch];
7816 if (x > maxchar)
7817 goto Error;
7818 outdata[writer->pos] = x;
7819 writer->pos++;
7820 ++s;
7821 }
7822 break;
7823 }
7824 else if (outkind == PyUnicode_2BYTE_KIND) {
7825 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7826 while (s < e) {
7827 ch = *s;
7828 x = mapdata_ucs2[ch];
7829 if (x == 0xFFFE)
7830 goto Error;
7831 outdata[writer->pos] = x;
7832 writer->pos++;
7833 ++s;
7834 }
7835 break;
7836 }
7837 }
7838 ch = *s;
7839
7840 if (ch < maplen)
7841 x = PyUnicode_READ(mapkind, mapdata, ch);
7842 else
7843 x = 0xfffe; /* invalid value */
7844Error:
7845 if (x == 0xfffe)
7846 {
7847 /* undefined mapping */
7848 startinpos = s-starts;
7849 endinpos = startinpos+1;
7850 if (unicode_decode_call_errorhandler_writer(
7851 errors, &errorHandler,
7852 "charmap", "character maps to <undefined>",
7853 &starts, &e, &startinpos, &endinpos, &exc, &s,
7854 writer)) {
7855 goto onError;
7856 }
7857 continue;
7858 }
7859
7860 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7861 goto onError;
7862 ++s;
7863 }
7864 Py_XDECREF(errorHandler);
7865 Py_XDECREF(exc);
7866 return 0;
7867
7868onError:
7869 Py_XDECREF(errorHandler);
7870 Py_XDECREF(exc);
7871 return -1;
7872}
7873
7874static int
7875charmap_decode_mapping(const char *s,
7876 Py_ssize_t size,
7877 PyObject *mapping,
7878 const char *errors,
7879 _PyUnicodeWriter *writer)
7880{
7881 const char *starts = s;
7882 const char *e;
7883 Py_ssize_t startinpos, endinpos;
7884 PyObject *errorHandler = NULL, *exc = NULL;
7885 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007886 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007887
7888 e = s + size;
7889
7890 while (s < e) {
7891 ch = *s;
7892
7893 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7894 key = PyLong_FromLong((long)ch);
7895 if (key == NULL)
7896 goto onError;
7897
7898 item = PyObject_GetItem(mapping, key);
7899 Py_DECREF(key);
7900 if (item == NULL) {
7901 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7902 /* No mapping found means: mapping is undefined. */
7903 PyErr_Clear();
7904 goto Undefined;
7905 } else
7906 goto onError;
7907 }
7908
7909 /* Apply mapping */
7910 if (item == Py_None)
7911 goto Undefined;
7912 if (PyLong_Check(item)) {
7913 long value = PyLong_AS_LONG(item);
7914 if (value == 0xFFFE)
7915 goto Undefined;
7916 if (value < 0 || value > MAX_UNICODE) {
7917 PyErr_Format(PyExc_TypeError,
7918 "character mapping must be in range(0x%lx)",
7919 (unsigned long)MAX_UNICODE + 1);
7920 goto onError;
7921 }
7922
7923 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7924 goto onError;
7925 }
7926 else if (PyUnicode_Check(item)) {
7927 if (PyUnicode_READY(item) == -1)
7928 goto onError;
7929 if (PyUnicode_GET_LENGTH(item) == 1) {
7930 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7931 if (value == 0xFFFE)
7932 goto Undefined;
7933 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7934 goto onError;
7935 }
7936 else {
7937 writer->overallocate = 1;
7938 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7939 goto onError;
7940 }
7941 }
7942 else {
7943 /* wrong return value */
7944 PyErr_SetString(PyExc_TypeError,
7945 "character mapping must return integer, None or str");
7946 goto onError;
7947 }
7948 Py_CLEAR(item);
7949 ++s;
7950 continue;
7951
7952Undefined:
7953 /* undefined mapping */
7954 Py_CLEAR(item);
7955 startinpos = s-starts;
7956 endinpos = startinpos+1;
7957 if (unicode_decode_call_errorhandler_writer(
7958 errors, &errorHandler,
7959 "charmap", "character maps to <undefined>",
7960 &starts, &e, &startinpos, &endinpos, &exc, &s,
7961 writer)) {
7962 goto onError;
7963 }
7964 }
7965 Py_XDECREF(errorHandler);
7966 Py_XDECREF(exc);
7967 return 0;
7968
7969onError:
7970 Py_XDECREF(item);
7971 Py_XDECREF(errorHandler);
7972 Py_XDECREF(exc);
7973 return -1;
7974}
7975
Alexander Belopolsky40018472011-02-26 01:02:56 +00007976PyObject *
7977PyUnicode_DecodeCharmap(const char *s,
7978 Py_ssize_t size,
7979 PyObject *mapping,
7980 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007981{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007982 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007983
Guido van Rossumd57fd912000-03-10 22:53:23 +00007984 /* Default to Latin-1 */
7985 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007986 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007987
Guido van Rossumd57fd912000-03-10 22:53:23 +00007988 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007989 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007990 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007991 writer.min_length = size;
7992 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007993 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007994
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007995 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007996 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7997 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007998 }
7999 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008000 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8001 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008002 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008003 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008004
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008006 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008007 return NULL;
8008}
8009
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008010/* Charmap encoding: the lookup table */
8011
Alexander Belopolsky40018472011-02-26 01:02:56 +00008012struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008013 PyObject_HEAD
8014 unsigned char level1[32];
8015 int count2, count3;
8016 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008017};
8018
8019static PyObject*
8020encoding_map_size(PyObject *obj, PyObject* args)
8021{
8022 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008023 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025}
8026
8027static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008028 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008029 PyDoc_STR("Return the size (in bytes) of this object") },
8030 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008031};
8032
8033static void
8034encoding_map_dealloc(PyObject* o)
8035{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008036 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008037}
8038
8039static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008040 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 "EncodingMap", /*tp_name*/
8042 sizeof(struct encoding_map), /*tp_basicsize*/
8043 0, /*tp_itemsize*/
8044 /* methods */
8045 encoding_map_dealloc, /*tp_dealloc*/
8046 0, /*tp_print*/
8047 0, /*tp_getattr*/
8048 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008049 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 0, /*tp_repr*/
8051 0, /*tp_as_number*/
8052 0, /*tp_as_sequence*/
8053 0, /*tp_as_mapping*/
8054 0, /*tp_hash*/
8055 0, /*tp_call*/
8056 0, /*tp_str*/
8057 0, /*tp_getattro*/
8058 0, /*tp_setattro*/
8059 0, /*tp_as_buffer*/
8060 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8061 0, /*tp_doc*/
8062 0, /*tp_traverse*/
8063 0, /*tp_clear*/
8064 0, /*tp_richcompare*/
8065 0, /*tp_weaklistoffset*/
8066 0, /*tp_iter*/
8067 0, /*tp_iternext*/
8068 encoding_map_methods, /*tp_methods*/
8069 0, /*tp_members*/
8070 0, /*tp_getset*/
8071 0, /*tp_base*/
8072 0, /*tp_dict*/
8073 0, /*tp_descr_get*/
8074 0, /*tp_descr_set*/
8075 0, /*tp_dictoffset*/
8076 0, /*tp_init*/
8077 0, /*tp_alloc*/
8078 0, /*tp_new*/
8079 0, /*tp_free*/
8080 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008081};
8082
8083PyObject*
8084PyUnicode_BuildEncodingMap(PyObject* string)
8085{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008086 PyObject *result;
8087 struct encoding_map *mresult;
8088 int i;
8089 int need_dict = 0;
8090 unsigned char level1[32];
8091 unsigned char level2[512];
8092 unsigned char *mlevel1, *mlevel2, *mlevel3;
8093 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008094 int kind;
8095 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008096 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008097 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008099 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008100 PyErr_BadArgument();
8101 return NULL;
8102 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008103 kind = PyUnicode_KIND(string);
8104 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008105 length = PyUnicode_GET_LENGTH(string);
8106 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008107 memset(level1, 0xFF, sizeof level1);
8108 memset(level2, 0xFF, sizeof level2);
8109
8110 /* If there isn't a one-to-one mapping of NULL to \0,
8111 or if there are non-BMP characters, we need to use
8112 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008113 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008114 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008115 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008116 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008117 ch = PyUnicode_READ(kind, data, i);
8118 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008119 need_dict = 1;
8120 break;
8121 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008122 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 /* unmapped character */
8124 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008125 l1 = ch >> 11;
8126 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008127 if (level1[l1] == 0xFF)
8128 level1[l1] = count2++;
8129 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008130 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008131 }
8132
8133 if (count2 >= 0xFF || count3 >= 0xFF)
8134 need_dict = 1;
8135
8136 if (need_dict) {
8137 PyObject *result = PyDict_New();
8138 PyObject *key, *value;
8139 if (!result)
8140 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008141 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008142 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008143 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008144 if (!key || !value)
8145 goto failed1;
8146 if (PyDict_SetItem(result, key, value) == -1)
8147 goto failed1;
8148 Py_DECREF(key);
8149 Py_DECREF(value);
8150 }
8151 return result;
8152 failed1:
8153 Py_XDECREF(key);
8154 Py_XDECREF(value);
8155 Py_DECREF(result);
8156 return NULL;
8157 }
8158
8159 /* Create a three-level trie */
8160 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8161 16*count2 + 128*count3 - 1);
8162 if (!result)
8163 return PyErr_NoMemory();
8164 PyObject_Init(result, &EncodingMapType);
8165 mresult = (struct encoding_map*)result;
8166 mresult->count2 = count2;
8167 mresult->count3 = count3;
8168 mlevel1 = mresult->level1;
8169 mlevel2 = mresult->level23;
8170 mlevel3 = mresult->level23 + 16*count2;
8171 memcpy(mlevel1, level1, 32);
8172 memset(mlevel2, 0xFF, 16*count2);
8173 memset(mlevel3, 0, 128*count3);
8174 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008175 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008176 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008177 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8178 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008179 /* unmapped character */
8180 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008181 o1 = ch>>11;
8182 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008183 i2 = 16*mlevel1[o1] + o2;
8184 if (mlevel2[i2] == 0xFF)
8185 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008186 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008187 i3 = 128*mlevel2[i2] + o3;
8188 mlevel3[i3] = i;
8189 }
8190 return result;
8191}
8192
8193static int
Victor Stinner22168992011-11-20 17:09:18 +01008194encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008195{
8196 struct encoding_map *map = (struct encoding_map*)mapping;
8197 int l1 = c>>11;
8198 int l2 = (c>>7) & 0xF;
8199 int l3 = c & 0x7F;
8200 int i;
8201
Victor Stinner22168992011-11-20 17:09:18 +01008202 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008203 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008204 if (c == 0)
8205 return 0;
8206 /* level 1*/
8207 i = map->level1[l1];
8208 if (i == 0xFF) {
8209 return -1;
8210 }
8211 /* level 2*/
8212 i = map->level23[16*i+l2];
8213 if (i == 0xFF) {
8214 return -1;
8215 }
8216 /* level 3 */
8217 i = map->level23[16*map->count2 + 128*i + l3];
8218 if (i == 0) {
8219 return -1;
8220 }
8221 return i;
8222}
8223
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008224/* Lookup the character ch in the mapping. If the character
8225 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008226 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008227static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008228charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008229{
Christian Heimes217cfd12007-12-02 14:31:20 +00008230 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 PyObject *x;
8232
8233 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008235 x = PyObject_GetItem(mapping, w);
8236 Py_DECREF(w);
8237 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8239 /* No mapping found means: mapping is undefined. */
8240 PyErr_Clear();
8241 x = Py_None;
8242 Py_INCREF(x);
8243 return x;
8244 } else
8245 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008246 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008247 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008248 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008249 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 long value = PyLong_AS_LONG(x);
8251 if (value < 0 || value > 255) {
8252 PyErr_SetString(PyExc_TypeError,
8253 "character mapping must be in range(256)");
8254 Py_DECREF(x);
8255 return NULL;
8256 }
8257 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008258 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008259 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008261 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008262 /* wrong return value */
8263 PyErr_Format(PyExc_TypeError,
8264 "character mapping must return integer, bytes or None, not %.400s",
8265 x->ob_type->tp_name);
8266 Py_DECREF(x);
8267 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008268 }
8269}
8270
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008271static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008272charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008273{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008274 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8275 /* exponentially overallocate to minimize reallocations */
8276 if (requiredsize < 2*outsize)
8277 requiredsize = 2*outsize;
8278 if (_PyBytes_Resize(outobj, requiredsize))
8279 return -1;
8280 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008281}
8282
Benjamin Peterson14339b62009-01-31 16:36:08 +00008283typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008284 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008285} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008286/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008287 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008288 space is available. Return a new reference to the object that
8289 was put in the output buffer, or Py_None, if the mapping was undefined
8290 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008291 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008292static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008293charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008294 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008296 PyObject *rep;
8297 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008298 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008299
Christian Heimes90aa7642007-12-19 02:45:37 +00008300 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008301 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008302 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008303 if (res == -1)
8304 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008305 if (outsize<requiredsize)
8306 if (charmapencode_resize(outobj, outpos, requiredsize))
8307 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008308 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 outstart[(*outpos)++] = (char)res;
8310 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008311 }
8312
8313 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008315 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008316 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008317 Py_DECREF(rep);
8318 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008319 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 if (PyLong_Check(rep)) {
8321 Py_ssize_t requiredsize = *outpos+1;
8322 if (outsize<requiredsize)
8323 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8324 Py_DECREF(rep);
8325 return enc_EXCEPTION;
8326 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008327 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008328 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008329 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 else {
8331 const char *repchars = PyBytes_AS_STRING(rep);
8332 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8333 Py_ssize_t requiredsize = *outpos+repsize;
8334 if (outsize<requiredsize)
8335 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8336 Py_DECREF(rep);
8337 return enc_EXCEPTION;
8338 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008339 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008340 memcpy(outstart + *outpos, repchars, repsize);
8341 *outpos += repsize;
8342 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008343 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008344 Py_DECREF(rep);
8345 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346}
8347
8348/* handle an error in PyUnicode_EncodeCharmap
8349 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008350static int
8351charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008352 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008353 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008354 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008355 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356{
8357 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008358 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008359 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008360 enum PyUnicode_Kind kind;
8361 void *data;
8362 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008363 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008364 Py_ssize_t collstartpos = *inpos;
8365 Py_ssize_t collendpos = *inpos+1;
8366 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367 char *encoding = "charmap";
8368 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008369 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008370 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008371 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008372
Benjamin Petersonbac79492012-01-14 13:34:47 -05008373 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008374 return -1;
8375 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008376 /* find all unencodable characters */
8377 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008378 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008379 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008380 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008381 val = encoding_map_lookup(ch, mapping);
8382 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008383 break;
8384 ++collendpos;
8385 continue;
8386 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008387
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008388 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8389 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 if (rep==NULL)
8391 return -1;
8392 else if (rep!=Py_None) {
8393 Py_DECREF(rep);
8394 break;
8395 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008396 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398 }
8399 /* cache callback name lookup
8400 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008401 if (*error_handler == _Py_ERROR_UNKNOWN)
8402 *error_handler = get_error_handler(errors);
8403
8404 switch (*error_handler) {
8405 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008406 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008407 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008408
8409 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008410 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 x = charmapencode_output('?', mapping, res, respos);
8412 if (x==enc_EXCEPTION) {
8413 return -1;
8414 }
8415 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008416 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008417 return -1;
8418 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008419 }
8420 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008421 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008422 *inpos = collendpos;
8423 break;
Victor Stinner50149202015-09-22 00:26:54 +02008424
8425 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008426 /* generate replacement (temporarily (mis)uses p) */
8427 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008428 char buffer[2+29+1+1];
8429 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008430 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008431 for (cp = buffer; *cp; ++cp) {
8432 x = charmapencode_output(*cp, mapping, res, respos);
8433 if (x==enc_EXCEPTION)
8434 return -1;
8435 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008436 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 return -1;
8438 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008439 }
8440 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008441 *inpos = collendpos;
8442 break;
Victor Stinner50149202015-09-22 00:26:54 +02008443
Benjamin Peterson14339b62009-01-31 16:36:08 +00008444 default:
Victor Stinner50149202015-09-22 00:26:54 +02008445 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008446 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008448 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008449 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008450 if (PyBytes_Check(repunicode)) {
8451 /* Directly copy bytes result to output. */
8452 Py_ssize_t outsize = PyBytes_Size(*res);
8453 Py_ssize_t requiredsize;
8454 repsize = PyBytes_Size(repunicode);
8455 requiredsize = *respos + repsize;
8456 if (requiredsize > outsize)
8457 /* Make room for all additional bytes. */
8458 if (charmapencode_resize(res, respos, requiredsize)) {
8459 Py_DECREF(repunicode);
8460 return -1;
8461 }
8462 memcpy(PyBytes_AsString(*res) + *respos,
8463 PyBytes_AsString(repunicode), repsize);
8464 *respos += repsize;
8465 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008466 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008467 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008468 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008469 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008470 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008471 Py_DECREF(repunicode);
8472 return -1;
8473 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008474 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008475 data = PyUnicode_DATA(repunicode);
8476 kind = PyUnicode_KIND(repunicode);
8477 for (index = 0; index < repsize; index++) {
8478 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8479 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008481 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 return -1;
8483 }
8484 else if (x==enc_FAILED) {
8485 Py_DECREF(repunicode);
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 *inpos = newpos;
8491 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008492 }
8493 return 0;
8494}
8495
Alexander Belopolsky40018472011-02-26 01:02:56 +00008496PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008497_PyUnicode_EncodeCharmap(PyObject *unicode,
8498 PyObject *mapping,
8499 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008500{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501 /* output object */
8502 PyObject *res = NULL;
8503 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008504 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008505 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008507 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008508 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008509 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008510 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008511 void *data;
8512 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008513
Benjamin Petersonbac79492012-01-14 13:34:47 -05008514 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008515 return NULL;
8516 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008517 data = PyUnicode_DATA(unicode);
8518 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008519
Guido van Rossumd57fd912000-03-10 22:53:23 +00008520 /* Default to Latin-1 */
8521 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008522 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008523
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008524 /* allocate enough for a simple encoding without
8525 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008526 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 if (res == NULL)
8528 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008529 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008531
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008532 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008533 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008535 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008536 if (x==enc_EXCEPTION) /* error */
8537 goto onError;
8538 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008539 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008541 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008542 &res, &respos)) {
8543 goto onError;
8544 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008545 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008546 else
8547 /* done with this character => adjust input position */
8548 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008549 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008550
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008552 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008553 if (_PyBytes_Resize(&res, respos) < 0)
8554 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008555
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008556 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008557 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558 return res;
8559
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008561 Py_XDECREF(res);
8562 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008563 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008564 return NULL;
8565}
8566
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008567/* Deprecated */
8568PyObject *
8569PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8570 Py_ssize_t size,
8571 PyObject *mapping,
8572 const char *errors)
8573{
8574 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008575 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008576 if (unicode == NULL)
8577 return NULL;
8578 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8579 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008580 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008581}
8582
Alexander Belopolsky40018472011-02-26 01:02:56 +00008583PyObject *
8584PyUnicode_AsCharmapString(PyObject *unicode,
8585 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008586{
8587 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008588 PyErr_BadArgument();
8589 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008590 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008591 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592}
8593
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008594/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008595static void
8596make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008597 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008598 Py_ssize_t startpos, Py_ssize_t endpos,
8599 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008601 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008602 *exceptionObject = _PyUnicodeTranslateError_Create(
8603 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008604 }
8605 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008606 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8607 goto onError;
8608 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8609 goto onError;
8610 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8611 goto onError;
8612 return;
8613 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008614 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008615 }
8616}
8617
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618/* error handling callback helper:
8619 build arguments, call the callback and check the arguments,
8620 put the result into newpos and return the replacement string, which
8621 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008622static PyObject *
8623unicode_translate_call_errorhandler(const char *errors,
8624 PyObject **errorHandler,
8625 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008627 Py_ssize_t startpos, Py_ssize_t endpos,
8628 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008629{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008630 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008631
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008632 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008633 PyObject *restuple;
8634 PyObject *resunicode;
8635
8636 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640 }
8641
8642 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008645 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008646
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008647 restuple = PyObject_CallFunctionObjArgs(
8648 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008650 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008651 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008652 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 Py_DECREF(restuple);
8654 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008655 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008656 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008657 &resunicode, &i_newpos)) {
8658 Py_DECREF(restuple);
8659 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008660 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008661 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008662 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008663 else
8664 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008666 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 Py_DECREF(restuple);
8668 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008669 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008670 Py_INCREF(resunicode);
8671 Py_DECREF(restuple);
8672 return resunicode;
8673}
8674
8675/* Lookup the character ch in the mapping and put the result in result,
8676 which must be decrefed by the caller.
8677 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008678static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008680{
Christian Heimes217cfd12007-12-02 14:31:20 +00008681 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008682 PyObject *x;
8683
8684 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008685 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008686 x = PyObject_GetItem(mapping, w);
8687 Py_DECREF(w);
8688 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008689 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8690 /* No mapping found means: use 1:1 mapping. */
8691 PyErr_Clear();
8692 *result = NULL;
8693 return 0;
8694 } else
8695 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696 }
8697 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 *result = x;
8699 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008700 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008701 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008703 if (value < 0 || value > MAX_UNICODE) {
8704 PyErr_Format(PyExc_ValueError,
8705 "character mapping must be in range(0x%x)",
8706 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 Py_DECREF(x);
8708 return -1;
8709 }
8710 *result = x;
8711 return 0;
8712 }
8713 else if (PyUnicode_Check(x)) {
8714 *result = x;
8715 return 0;
8716 }
8717 else {
8718 /* wrong return value */
8719 PyErr_SetString(PyExc_TypeError,
8720 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008721 Py_DECREF(x);
8722 return -1;
8723 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008724}
Victor Stinner1194ea02014-04-04 19:37:40 +02008725
8726/* lookup the character, write the result into the writer.
8727 Return 1 if the result was written into the writer, return 0 if the mapping
8728 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008729static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008730charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8731 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008732{
Victor Stinner1194ea02014-04-04 19:37:40 +02008733 PyObject *item;
8734
8735 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008737
8738 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008739 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008740 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008741 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008743 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008744 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008745
8746 if (item == Py_None) {
8747 Py_DECREF(item);
8748 return 0;
8749 }
8750
8751 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008752 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8753 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8754 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008755 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8756 Py_DECREF(item);
8757 return -1;
8758 }
8759 Py_DECREF(item);
8760 return 1;
8761 }
8762
8763 if (!PyUnicode_Check(item)) {
8764 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008765 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008766 }
8767
8768 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8769 Py_DECREF(item);
8770 return -1;
8771 }
8772
8773 Py_DECREF(item);
8774 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008775}
8776
Victor Stinner89a76ab2014-04-05 11:44:04 +02008777static int
8778unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8779 Py_UCS1 *translate)
8780{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008781 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008782 int ret = 0;
8783
Victor Stinner89a76ab2014-04-05 11:44:04 +02008784 if (charmaptranslate_lookup(ch, mapping, &item)) {
8785 return -1;
8786 }
8787
8788 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008789 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008790 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008791 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008792 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008793 /* not found => default to 1:1 mapping */
8794 translate[ch] = ch;
8795 return 1;
8796 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008797 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008798 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008799 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8800 used it */
8801 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008802 /* invalid character or character outside ASCII:
8803 skip the fast translate */
8804 goto exit;
8805 }
8806 translate[ch] = (Py_UCS1)replace;
8807 }
8808 else if (PyUnicode_Check(item)) {
8809 Py_UCS4 replace;
8810
8811 if (PyUnicode_READY(item) == -1) {
8812 Py_DECREF(item);
8813 return -1;
8814 }
8815 if (PyUnicode_GET_LENGTH(item) != 1)
8816 goto exit;
8817
8818 replace = PyUnicode_READ_CHAR(item, 0);
8819 if (replace > 127)
8820 goto exit;
8821 translate[ch] = (Py_UCS1)replace;
8822 }
8823 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008824 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008825 goto exit;
8826 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008827 ret = 1;
8828
Benjamin Peterson1365de72014-04-07 20:15:41 -04008829 exit:
8830 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008831 return ret;
8832}
8833
8834/* Fast path for ascii => ascii translation. Return 1 if the whole string
8835 was translated into writer, return 0 if the input string was partially
8836 translated into writer, raise an exception and return -1 on error. */
8837static int
8838unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008839 _PyUnicodeWriter *writer, int ignore,
8840 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008841{
Victor Stinner872b2912014-04-05 14:27:07 +02008842 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008843 Py_ssize_t len;
8844 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008845 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008846
Victor Stinner89a76ab2014-04-05 11:44:04 +02008847 len = PyUnicode_GET_LENGTH(input);
8848
Victor Stinner872b2912014-04-05 14:27:07 +02008849 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008850
8851 in = PyUnicode_1BYTE_DATA(input);
8852 end = in + len;
8853
8854 assert(PyUnicode_IS_ASCII(writer->buffer));
8855 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8856 out = PyUnicode_1BYTE_DATA(writer->buffer);
8857
Victor Stinner872b2912014-04-05 14:27:07 +02008858 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008859 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008860 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008861 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008862 int translate = unicode_fast_translate_lookup(mapping, ch,
8863 ascii_table);
8864 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008865 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008866 if (translate == 0)
8867 goto exit;
8868 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008869 }
Victor Stinner872b2912014-04-05 14:27:07 +02008870 if (ch2 == 0xfe) {
8871 if (ignore)
8872 continue;
8873 goto exit;
8874 }
8875 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008876 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008877 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008878 }
Victor Stinner872b2912014-04-05 14:27:07 +02008879 res = 1;
8880
8881exit:
8882 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008883 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008884 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008885}
8886
Victor Stinner3222da22015-10-01 22:07:32 +02008887static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008888_PyUnicode_TranslateCharmap(PyObject *input,
8889 PyObject *mapping,
8890 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008891{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008892 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008893 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008894 Py_ssize_t size, i;
8895 int kind;
8896 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008897 _PyUnicodeWriter writer;
8898 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008899 char *reason = "character maps to <undefined>";
8900 PyObject *errorHandler = NULL;
8901 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008902 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008903 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008904
Guido van Rossumd57fd912000-03-10 22:53:23 +00008905 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008906 PyErr_BadArgument();
8907 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008908 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008910 if (PyUnicode_READY(input) == -1)
8911 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008912 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008913 kind = PyUnicode_KIND(input);
8914 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008915
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008916 if (size == 0)
8917 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008918
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008919 /* allocate enough for a simple 1:1 translation without
8920 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008921 _PyUnicodeWriter_Init(&writer);
8922 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008924
Victor Stinner872b2912014-04-05 14:27:07 +02008925 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8926
Victor Stinner33798672016-03-01 21:59:58 +01008927 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008928 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008929 if (PyUnicode_IS_ASCII(input)) {
8930 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8931 if (res < 0) {
8932 _PyUnicodeWriter_Dealloc(&writer);
8933 return NULL;
8934 }
8935 if (res == 1)
8936 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008937 }
Victor Stinner33798672016-03-01 21:59:58 +01008938 else {
8939 i = 0;
8940 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008941
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008942 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008943 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008944 int translate;
8945 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8946 Py_ssize_t newpos;
8947 /* startpos for collecting untranslatable chars */
8948 Py_ssize_t collstart;
8949 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008950 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008951
Victor Stinner1194ea02014-04-04 19:37:40 +02008952 ch = PyUnicode_READ(kind, data, i);
8953 translate = charmaptranslate_output(ch, mapping, &writer);
8954 if (translate < 0)
8955 goto onError;
8956
8957 if (translate != 0) {
8958 /* it worked => adjust input pointer */
8959 ++i;
8960 continue;
8961 }
8962
8963 /* untranslatable character */
8964 collstart = i;
8965 collend = i+1;
8966
8967 /* find all untranslatable characters */
8968 while (collend < size) {
8969 PyObject *x;
8970 ch = PyUnicode_READ(kind, data, collend);
8971 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008972 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008973 Py_XDECREF(x);
8974 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008975 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008976 ++collend;
8977 }
8978
8979 if (ignore) {
8980 i = collend;
8981 }
8982 else {
8983 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8984 reason, input, &exc,
8985 collstart, collend, &newpos);
8986 if (repunicode == NULL)
8987 goto onError;
8988 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008989 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008990 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008991 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008992 Py_DECREF(repunicode);
8993 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008994 }
8995 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008996 Py_XDECREF(exc);
8997 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008998 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008999
Benjamin Peterson29060642009-01-31 22:14:21 +00009000 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009001 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009002 Py_XDECREF(exc);
9003 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009004 return NULL;
9005}
9006
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009007/* Deprecated. Use PyUnicode_Translate instead. */
9008PyObject *
9009PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9010 Py_ssize_t size,
9011 PyObject *mapping,
9012 const char *errors)
9013{
Christian Heimes5f520f42012-09-11 14:03:25 +02009014 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009015 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009016 if (!unicode)
9017 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009018 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9019 Py_DECREF(unicode);
9020 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009021}
9022
Alexander Belopolsky40018472011-02-26 01:02:56 +00009023PyObject *
9024PyUnicode_Translate(PyObject *str,
9025 PyObject *mapping,
9026 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009027{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009028 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009029 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009030 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009031}
Tim Petersced69f82003-09-16 20:30:58 +00009032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009033static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009034fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009035{
9036 /* No need to call PyUnicode_READY(self) because this function is only
9037 called as a callback from fixup() which does it already. */
9038 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9039 const int kind = PyUnicode_KIND(self);
9040 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009041 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009042 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009043 Py_ssize_t i;
9044
9045 for (i = 0; i < len; ++i) {
9046 ch = PyUnicode_READ(kind, data, i);
9047 fixed = 0;
9048 if (ch > 127) {
9049 if (Py_UNICODE_ISSPACE(ch))
9050 fixed = ' ';
9051 else {
9052 const int decimal = Py_UNICODE_TODECIMAL(ch);
9053 if (decimal >= 0)
9054 fixed = '0' + decimal;
9055 }
9056 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009057 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009058 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059 PyUnicode_WRITE(kind, data, i, fixed);
9060 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009061 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009062 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009063 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009064 }
9065
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009066 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067}
9068
9069PyObject *
9070_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9071{
9072 if (!PyUnicode_Check(unicode)) {
9073 PyErr_BadInternalCall();
9074 return NULL;
9075 }
9076 if (PyUnicode_READY(unicode) == -1)
9077 return NULL;
9078 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9079 /* If the string is already ASCII, just return the same string */
9080 Py_INCREF(unicode);
9081 return unicode;
9082 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009083 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009084}
9085
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009086PyObject *
9087PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9088 Py_ssize_t length)
9089{
Victor Stinnerf0124502011-11-21 23:12:56 +01009090 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009091 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009092 Py_UCS4 maxchar;
9093 enum PyUnicode_Kind kind;
9094 void *data;
9095
Victor Stinner99d7ad02012-02-22 13:37:39 +01009096 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009097 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009098 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009099 if (ch > 127) {
9100 int decimal = Py_UNICODE_TODECIMAL(ch);
9101 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009102 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009103 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009104 }
9105 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009106
9107 /* Copy to a new string */
9108 decimal = PyUnicode_New(length, maxchar);
9109 if (decimal == NULL)
9110 return decimal;
9111 kind = PyUnicode_KIND(decimal);
9112 data = PyUnicode_DATA(decimal);
9113 /* Iterate over code points */
9114 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009115 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009116 if (ch > 127) {
9117 int decimal = Py_UNICODE_TODECIMAL(ch);
9118 if (decimal >= 0)
9119 ch = '0' + decimal;
9120 }
9121 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009122 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009123 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009124}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009125/* --- Decimal Encoder ---------------------------------------------------- */
9126
Alexander Belopolsky40018472011-02-26 01:02:56 +00009127int
9128PyUnicode_EncodeDecimal(Py_UNICODE *s,
9129 Py_ssize_t length,
9130 char *output,
9131 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009132{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009133 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009134 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009135 enum PyUnicode_Kind kind;
9136 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009137
9138 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009139 PyErr_BadArgument();
9140 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009141 }
9142
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009143 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009144 if (unicode == NULL)
9145 return -1;
9146
Victor Stinner42bf7752011-11-21 22:52:58 +01009147 kind = PyUnicode_KIND(unicode);
9148 data = PyUnicode_DATA(unicode);
9149
Victor Stinnerb84d7232011-11-22 01:50:07 +01009150 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009151 PyObject *exc;
9152 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009153 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009154 Py_ssize_t startpos;
9155
9156 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009157
Benjamin Peterson29060642009-01-31 22:14:21 +00009158 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009159 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009160 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009161 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009162 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009163 decimal = Py_UNICODE_TODECIMAL(ch);
9164 if (decimal >= 0) {
9165 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009166 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009167 continue;
9168 }
9169 if (0 < ch && ch < 256) {
9170 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009171 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009172 continue;
9173 }
Victor Stinner6345be92011-11-25 20:09:01 +01009174
Victor Stinner42bf7752011-11-21 22:52:58 +01009175 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009176 exc = NULL;
9177 raise_encode_exception(&exc, "decimal", unicode,
9178 startpos, startpos+1,
9179 "invalid decimal Unicode string");
9180 Py_XDECREF(exc);
9181 Py_DECREF(unicode);
9182 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009183 }
9184 /* 0-terminate the output string */
9185 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009186 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009187 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009188}
9189
Guido van Rossumd57fd912000-03-10 22:53:23 +00009190/* --- Helpers ------------------------------------------------------------ */
9191
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009192/* helper macro to fixup start/end slice values */
9193#define ADJUST_INDICES(start, end, len) \
9194 if (end > len) \
9195 end = len; \
9196 else if (end < 0) { \
9197 end += len; \
9198 if (end < 0) \
9199 end = 0; \
9200 } \
9201 if (start < 0) { \
9202 start += len; \
9203 if (start < 0) \
9204 start = 0; \
9205 }
9206
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009207static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009208any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009210 Py_ssize_t end,
9211 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009213 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009214 void *buf1, *buf2;
9215 Py_ssize_t len1, len2, result;
9216
9217 kind1 = PyUnicode_KIND(s1);
9218 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009219 if (kind1 < kind2)
9220 return -1;
9221
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009222 len1 = PyUnicode_GET_LENGTH(s1);
9223 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009224 ADJUST_INDICES(start, end, len1);
9225 if (end - start < len2)
9226 return -1;
9227
9228 buf1 = PyUnicode_DATA(s1);
9229 buf2 = PyUnicode_DATA(s2);
9230 if (len2 == 1) {
9231 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9232 result = findchar((const char *)buf1 + kind1*start,
9233 kind1, end - start, ch, direction);
9234 if (result == -1)
9235 return -1;
9236 else
9237 return start + result;
9238 }
9239
9240 if (kind2 != kind1) {
9241 buf2 = _PyUnicode_AsKind(s2, kind1);
9242 if (!buf2)
9243 return -2;
9244 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009245
Victor Stinner794d5672011-10-10 03:21:36 +02009246 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009247 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009248 case PyUnicode_1BYTE_KIND:
9249 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9250 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9251 else
9252 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9253 break;
9254 case PyUnicode_2BYTE_KIND:
9255 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9256 break;
9257 case PyUnicode_4BYTE_KIND:
9258 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9259 break;
9260 default:
9261 assert(0); result = -2;
9262 }
9263 }
9264 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009265 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009266 case PyUnicode_1BYTE_KIND:
9267 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9268 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9269 else
9270 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9271 break;
9272 case PyUnicode_2BYTE_KIND:
9273 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9274 break;
9275 case PyUnicode_4BYTE_KIND:
9276 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9277 break;
9278 default:
9279 assert(0); result = -2;
9280 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009281 }
9282
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009283 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009284 PyMem_Free(buf2);
9285
9286 return result;
9287}
9288
9289Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009290_PyUnicode_InsertThousandsGrouping(
9291 PyObject *unicode, Py_ssize_t index,
9292 Py_ssize_t n_buffer,
9293 void *digits, Py_ssize_t n_digits,
9294 Py_ssize_t min_width,
9295 const char *grouping, PyObject *thousands_sep,
9296 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297{
Victor Stinner41a863c2012-02-24 00:37:51 +01009298 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009299 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009300 Py_ssize_t thousands_sep_len;
9301 Py_ssize_t len;
9302
9303 if (unicode != NULL) {
9304 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009305 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009306 }
9307 else {
9308 kind = PyUnicode_1BYTE_KIND;
9309 data = NULL;
9310 }
9311 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9312 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9313 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9314 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009315 if (thousands_sep_kind < kind) {
9316 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9317 if (!thousands_sep_data)
9318 return -1;
9319 }
9320 else {
9321 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9322 if (!data)
9323 return -1;
9324 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009325 }
9326
Benjamin Petersonead6b532011-12-20 17:23:42 -06009327 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009328 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009329 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009330 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009331 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009332 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009333 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009334 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009335 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009336 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009337 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009338 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009339 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009340 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009341 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009342 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009343 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009344 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009345 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009347 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009348 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009349 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009350 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009351 break;
9352 default:
9353 assert(0);
9354 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009355 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009356 if (unicode != NULL && thousands_sep_kind != kind) {
9357 if (thousands_sep_kind < kind)
9358 PyMem_Free(thousands_sep_data);
9359 else
9360 PyMem_Free(data);
9361 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009362 if (unicode == NULL) {
9363 *maxchar = 127;
9364 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009365 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009366 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009367 }
9368 }
9369 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370}
9371
9372
Alexander Belopolsky40018472011-02-26 01:02:56 +00009373Py_ssize_t
9374PyUnicode_Count(PyObject *str,
9375 PyObject *substr,
9376 Py_ssize_t start,
9377 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009378{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009379 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009380 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009381 void *buf1 = NULL, *buf2 = NULL;
9382 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009383
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009384 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009385 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009386
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009387 kind1 = PyUnicode_KIND(str);
9388 kind2 = PyUnicode_KIND(substr);
9389 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009390 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009391
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009392 len1 = PyUnicode_GET_LENGTH(str);
9393 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009394 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009395 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009396 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009397
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009398 buf1 = PyUnicode_DATA(str);
9399 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009400 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009401 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009402 if (!buf2)
9403 goto onError;
9404 }
9405
9406 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009408 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009409 result = asciilib_count(
9410 ((Py_UCS1*)buf1) + start, end - start,
9411 buf2, len2, PY_SSIZE_T_MAX
9412 );
9413 else
9414 result = ucs1lib_count(
9415 ((Py_UCS1*)buf1) + start, end - start,
9416 buf2, len2, PY_SSIZE_T_MAX
9417 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009418 break;
9419 case PyUnicode_2BYTE_KIND:
9420 result = ucs2lib_count(
9421 ((Py_UCS2*)buf1) + start, end - start,
9422 buf2, len2, PY_SSIZE_T_MAX
9423 );
9424 break;
9425 case PyUnicode_4BYTE_KIND:
9426 result = ucs4lib_count(
9427 ((Py_UCS4*)buf1) + start, end - start,
9428 buf2, len2, PY_SSIZE_T_MAX
9429 );
9430 break;
9431 default:
9432 assert(0); result = 0;
9433 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009434
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009435 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009436 PyMem_Free(buf2);
9437
Guido van Rossumd57fd912000-03-10 22:53:23 +00009438 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009440 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009441 PyMem_Free(buf2);
9442 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009443}
9444
Alexander Belopolsky40018472011-02-26 01:02:56 +00009445Py_ssize_t
9446PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009447 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009448 Py_ssize_t start,
9449 Py_ssize_t end,
9450 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009452 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009453 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009454
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009455 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009456}
9457
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458Py_ssize_t
9459PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9460 Py_ssize_t start, Py_ssize_t end,
9461 int direction)
9462{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009463 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009464 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 if (PyUnicode_READY(str) == -1)
9466 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009467 len = PyUnicode_GET_LENGTH(str);
9468 ADJUST_INDICES(start, end, len);
9469 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009470 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009472 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9473 kind, end-start, ch, direction);
9474 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009476 else
9477 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009478}
9479
Alexander Belopolsky40018472011-02-26 01:02:56 +00009480static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009481tailmatch(PyObject *self,
9482 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009483 Py_ssize_t start,
9484 Py_ssize_t end,
9485 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009486{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487 int kind_self;
9488 int kind_sub;
9489 void *data_self;
9490 void *data_sub;
9491 Py_ssize_t offset;
9492 Py_ssize_t i;
9493 Py_ssize_t end_sub;
9494
9495 if (PyUnicode_READY(self) == -1 ||
9496 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009497 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9500 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009501 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009502 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009504 if (PyUnicode_GET_LENGTH(substring) == 0)
9505 return 1;
9506
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009507 kind_self = PyUnicode_KIND(self);
9508 data_self = PyUnicode_DATA(self);
9509 kind_sub = PyUnicode_KIND(substring);
9510 data_sub = PyUnicode_DATA(substring);
9511 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9512
9513 if (direction > 0)
9514 offset = end;
9515 else
9516 offset = start;
9517
9518 if (PyUnicode_READ(kind_self, data_self, offset) ==
9519 PyUnicode_READ(kind_sub, data_sub, 0) &&
9520 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9521 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9522 /* If both are of the same kind, memcmp is sufficient */
9523 if (kind_self == kind_sub) {
9524 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009525 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009526 data_sub,
9527 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009528 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009530 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 else {
9532 /* We do not need to compare 0 and len(substring)-1 because
9533 the if statement above ensured already that they are equal
9534 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535 for (i = 1; i < end_sub; ++i) {
9536 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9537 PyUnicode_READ(kind_sub, data_sub, i))
9538 return 0;
9539 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009540 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009541 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009542 }
9543
9544 return 0;
9545}
9546
Alexander Belopolsky40018472011-02-26 01:02:56 +00009547Py_ssize_t
9548PyUnicode_Tailmatch(PyObject *str,
9549 PyObject *substr,
9550 Py_ssize_t start,
9551 Py_ssize_t end,
9552 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009553{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009554 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009555 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009556
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009557 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009558}
9559
Guido van Rossumd57fd912000-03-10 22:53:23 +00009560/* Apply fixfct filter to the Unicode object self and return a
9561 reference to the modified object */
9562
Alexander Belopolsky40018472011-02-26 01:02:56 +00009563static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009564fixup(PyObject *self,
9565 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009566{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009567 PyObject *u;
9568 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009569 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009570
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009571 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009572 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009573 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009574 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009575
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009576 /* fix functions return the new maximum character in a string,
9577 if the kind of the resulting unicode object does not change,
9578 everything is fine. Otherwise we need to change the string kind
9579 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009580 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009581
9582 if (maxchar_new == 0) {
9583 /* no changes */;
9584 if (PyUnicode_CheckExact(self)) {
9585 Py_DECREF(u);
9586 Py_INCREF(self);
9587 return self;
9588 }
9589 else
9590 return u;
9591 }
9592
Victor Stinnere6abb482012-05-02 01:15:40 +02009593 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009594
Victor Stinnereaab6042011-12-11 22:22:39 +01009595 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009596 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009597
9598 /* In case the maximum character changed, we need to
9599 convert the string to the new category. */
9600 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9601 if (v == NULL) {
9602 Py_DECREF(u);
9603 return NULL;
9604 }
9605 if (maxchar_new > maxchar_old) {
9606 /* If the maxchar increased so that the kind changed, not all
9607 characters are representable anymore and we need to fix the
9608 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009609 _PyUnicode_FastCopyCharacters(v, 0,
9610 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009611 maxchar_old = fixfct(v);
9612 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 }
9614 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009615 _PyUnicode_FastCopyCharacters(v, 0,
9616 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009617 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009618 Py_DECREF(u);
9619 assert(_PyUnicode_CheckConsistency(v, 1));
9620 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009621}
9622
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009623static PyObject *
9624ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009625{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009626 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9627 char *resdata, *data = PyUnicode_DATA(self);
9628 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009629
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009630 res = PyUnicode_New(len, 127);
9631 if (res == NULL)
9632 return NULL;
9633 resdata = PyUnicode_DATA(res);
9634 if (lower)
9635 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009636 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009637 _Py_bytes_upper(resdata, data, len);
9638 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009639}
9640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009641static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009642handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009643{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009644 Py_ssize_t j;
9645 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009646 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009647 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009648
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009649 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9650
9651 where ! is a negation and \p{xxx} is a character with property xxx.
9652 */
9653 for (j = i - 1; j >= 0; j--) {
9654 c = PyUnicode_READ(kind, data, j);
9655 if (!_PyUnicode_IsCaseIgnorable(c))
9656 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009657 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009658 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9659 if (final_sigma) {
9660 for (j = i + 1; j < length; j++) {
9661 c = PyUnicode_READ(kind, data, j);
9662 if (!_PyUnicode_IsCaseIgnorable(c))
9663 break;
9664 }
9665 final_sigma = j == length || !_PyUnicode_IsCased(c);
9666 }
9667 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668}
9669
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670static int
9671lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9672 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009673{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009674 /* Obscure special case. */
9675 if (c == 0x3A3) {
9676 mapped[0] = handle_capital_sigma(kind, data, length, i);
9677 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009678 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009679 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009680}
9681
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009682static Py_ssize_t
9683do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009684{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009685 Py_ssize_t i, k = 0;
9686 int n_res, j;
9687 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009688
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009689 c = PyUnicode_READ(kind, data, 0);
9690 n_res = _PyUnicode_ToUpperFull(c, mapped);
9691 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009692 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009693 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009694 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009695 for (i = 1; i < length; i++) {
9696 c = PyUnicode_READ(kind, data, i);
9697 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9698 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009699 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009700 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009701 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009702 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009703 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009704}
9705
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009706static Py_ssize_t
9707do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9708 Py_ssize_t i, k = 0;
9709
9710 for (i = 0; i < length; i++) {
9711 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9712 int n_res, j;
9713 if (Py_UNICODE_ISUPPER(c)) {
9714 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9715 }
9716 else if (Py_UNICODE_ISLOWER(c)) {
9717 n_res = _PyUnicode_ToUpperFull(c, mapped);
9718 }
9719 else {
9720 n_res = 1;
9721 mapped[0] = c;
9722 }
9723 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009724 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009725 res[k++] = mapped[j];
9726 }
9727 }
9728 return k;
9729}
9730
9731static Py_ssize_t
9732do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9733 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009734{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009735 Py_ssize_t i, k = 0;
9736
9737 for (i = 0; i < length; i++) {
9738 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9739 int n_res, j;
9740 if (lower)
9741 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9742 else
9743 n_res = _PyUnicode_ToUpperFull(c, mapped);
9744 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009745 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009746 res[k++] = mapped[j];
9747 }
9748 }
9749 return k;
9750}
9751
9752static Py_ssize_t
9753do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9754{
9755 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9756}
9757
9758static Py_ssize_t
9759do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9760{
9761 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9762}
9763
Benjamin Petersone51757f2012-01-12 21:10:29 -05009764static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009765do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9766{
9767 Py_ssize_t i, k = 0;
9768
9769 for (i = 0; i < length; i++) {
9770 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9771 Py_UCS4 mapped[3];
9772 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9773 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009774 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009775 res[k++] = mapped[j];
9776 }
9777 }
9778 return k;
9779}
9780
9781static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009782do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9783{
9784 Py_ssize_t i, k = 0;
9785 int previous_is_cased;
9786
9787 previous_is_cased = 0;
9788 for (i = 0; i < length; i++) {
9789 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9790 Py_UCS4 mapped[3];
9791 int n_res, j;
9792
9793 if (previous_is_cased)
9794 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9795 else
9796 n_res = _PyUnicode_ToTitleFull(c, mapped);
9797
9798 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009799 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009800 res[k++] = mapped[j];
9801 }
9802
9803 previous_is_cased = _PyUnicode_IsCased(c);
9804 }
9805 return k;
9806}
9807
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009808static PyObject *
9809case_operation(PyObject *self,
9810 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9811{
9812 PyObject *res = NULL;
9813 Py_ssize_t length, newlength = 0;
9814 int kind, outkind;
9815 void *data, *outdata;
9816 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9817
Benjamin Petersoneea48462012-01-16 14:28:50 -05009818 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009819
9820 kind = PyUnicode_KIND(self);
9821 data = PyUnicode_DATA(self);
9822 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009823 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009824 PyErr_SetString(PyExc_OverflowError, "string is too long");
9825 return NULL;
9826 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009827 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009828 if (tmp == NULL)
9829 return PyErr_NoMemory();
9830 newlength = perform(kind, data, length, tmp, &maxchar);
9831 res = PyUnicode_New(newlength, maxchar);
9832 if (res == NULL)
9833 goto leave;
9834 tmpend = tmp + newlength;
9835 outdata = PyUnicode_DATA(res);
9836 outkind = PyUnicode_KIND(res);
9837 switch (outkind) {
9838 case PyUnicode_1BYTE_KIND:
9839 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9840 break;
9841 case PyUnicode_2BYTE_KIND:
9842 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9843 break;
9844 case PyUnicode_4BYTE_KIND:
9845 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9846 break;
9847 default:
9848 assert(0);
9849 break;
9850 }
9851 leave:
9852 PyMem_FREE(tmp);
9853 return res;
9854}
9855
Tim Peters8ce9f162004-08-27 01:49:32 +00009856PyObject *
9857PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009858{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009859 PyObject *res;
9860 PyObject *fseq;
9861 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009862 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009863
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009864 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009865 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009866 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009867 }
9868
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009869 /* NOTE: the following code can't call back into Python code,
9870 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009871 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009872
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009873 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009874 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009875 res = _PyUnicode_JoinArray(separator, items, seqlen);
9876 Py_DECREF(fseq);
9877 return res;
9878}
9879
9880PyObject *
9881_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9882{
9883 PyObject *res = NULL; /* the result */
9884 PyObject *sep = NULL;
9885 Py_ssize_t seplen;
9886 PyObject *item;
9887 Py_ssize_t sz, i, res_offset;
9888 Py_UCS4 maxchar;
9889 Py_UCS4 item_maxchar;
9890 int use_memcpy;
9891 unsigned char *res_data = NULL, *sep_data = NULL;
9892 PyObject *last_obj;
9893 unsigned int kind = 0;
9894
Tim Peters05eba1f2004-08-27 21:32:02 +00009895 /* If empty sequence, return u"". */
9896 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009897 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009898 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009899
Tim Peters05eba1f2004-08-27 21:32:02 +00009900 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009901 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009902 if (seqlen == 1) {
9903 if (PyUnicode_CheckExact(items[0])) {
9904 res = items[0];
9905 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009906 return res;
9907 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009908 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009909 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009910 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009911 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009912 /* Set up sep and seplen */
9913 if (separator == NULL) {
9914 /* fall back to a blank space separator */
9915 sep = PyUnicode_FromOrdinal(' ');
9916 if (!sep)
9917 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009918 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009919 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009920 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009921 else {
9922 if (!PyUnicode_Check(separator)) {
9923 PyErr_Format(PyExc_TypeError,
9924 "separator: expected str instance,"
9925 " %.80s found",
9926 Py_TYPE(separator)->tp_name);
9927 goto onError;
9928 }
9929 if (PyUnicode_READY(separator))
9930 goto onError;
9931 sep = separator;
9932 seplen = PyUnicode_GET_LENGTH(separator);
9933 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9934 /* inc refcount to keep this code path symmetric with the
9935 above case of a blank separator */
9936 Py_INCREF(sep);
9937 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009938 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009939 }
9940
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009941 /* There are at least two things to join, or else we have a subclass
9942 * of str in the sequence.
9943 * Do a pre-pass to figure out the total amount of space we'll
9944 * need (sz), and see whether all argument are strings.
9945 */
9946 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009947#ifdef Py_DEBUG
9948 use_memcpy = 0;
9949#else
9950 use_memcpy = 1;
9951#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009952 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009953 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009954 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009955 if (!PyUnicode_Check(item)) {
9956 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009957 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009958 " %.80s found",
9959 i, Py_TYPE(item)->tp_name);
9960 goto onError;
9961 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009962 if (PyUnicode_READY(item) == -1)
9963 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009964 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009965 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009966 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009967 if (i != 0) {
9968 add_sz += seplen;
9969 }
9970 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009971 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009972 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009973 goto onError;
9974 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009975 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009976 if (use_memcpy && last_obj != NULL) {
9977 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9978 use_memcpy = 0;
9979 }
9980 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009981 }
Tim Petersced69f82003-09-16 20:30:58 +00009982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009984 if (res == NULL)
9985 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009986
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009987 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009988#ifdef Py_DEBUG
9989 use_memcpy = 0;
9990#else
9991 if (use_memcpy) {
9992 res_data = PyUnicode_1BYTE_DATA(res);
9993 kind = PyUnicode_KIND(res);
9994 if (seplen != 0)
9995 sep_data = PyUnicode_1BYTE_DATA(sep);
9996 }
9997#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009998 if (use_memcpy) {
9999 for (i = 0; i < seqlen; ++i) {
10000 Py_ssize_t itemlen;
10001 item = items[i];
10002
10003 /* Copy item, and maybe the separator. */
10004 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010005 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010006 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010007 kind * seplen);
10008 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010009 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010010
10011 itemlen = PyUnicode_GET_LENGTH(item);
10012 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010013 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010014 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010015 kind * itemlen);
10016 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010017 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010018 }
10019 assert(res_data == PyUnicode_1BYTE_DATA(res)
10020 + kind * PyUnicode_GET_LENGTH(res));
10021 }
10022 else {
10023 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10024 Py_ssize_t itemlen;
10025 item = items[i];
10026
10027 /* Copy item, and maybe the separator. */
10028 if (i && seplen != 0) {
10029 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10030 res_offset += seplen;
10031 }
10032
10033 itemlen = PyUnicode_GET_LENGTH(item);
10034 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010035 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010036 res_offset += itemlen;
10037 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010038 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010039 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010040 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010043 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010045
Benjamin Peterson29060642009-01-31 22:14:21 +000010046 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010048 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010049 return NULL;
10050}
10051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052#define FILL(kind, data, value, start, length) \
10053 do { \
10054 Py_ssize_t i_ = 0; \
10055 assert(kind != PyUnicode_WCHAR_KIND); \
10056 switch ((kind)) { \
10057 case PyUnicode_1BYTE_KIND: { \
10058 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010059 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 break; \
10061 } \
10062 case PyUnicode_2BYTE_KIND: { \
10063 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10064 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10065 break; \
10066 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010067 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10069 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10070 break; \
10071 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010072 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 } \
10074 } while (0)
10075
Victor Stinnerd3f08822012-05-29 12:57:52 +020010076void
10077_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10078 Py_UCS4 fill_char)
10079{
10080 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10081 const void *data = PyUnicode_DATA(unicode);
10082 assert(PyUnicode_IS_READY(unicode));
10083 assert(unicode_modifiable(unicode));
10084 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10085 assert(start >= 0);
10086 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10087 FILL(kind, data, fill_char, start, length);
10088}
10089
Victor Stinner3fe55312012-01-04 00:33:50 +010010090Py_ssize_t
10091PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10092 Py_UCS4 fill_char)
10093{
10094 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010095
10096 if (!PyUnicode_Check(unicode)) {
10097 PyErr_BadInternalCall();
10098 return -1;
10099 }
10100 if (PyUnicode_READY(unicode) == -1)
10101 return -1;
10102 if (unicode_check_modifiable(unicode))
10103 return -1;
10104
Victor Stinnerd3f08822012-05-29 12:57:52 +020010105 if (start < 0) {
10106 PyErr_SetString(PyExc_IndexError, "string index out of range");
10107 return -1;
10108 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010109 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10110 PyErr_SetString(PyExc_ValueError,
10111 "fill character is bigger than "
10112 "the string maximum character");
10113 return -1;
10114 }
10115
10116 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10117 length = Py_MIN(maxlen, length);
10118 if (length <= 0)
10119 return 0;
10120
Victor Stinnerd3f08822012-05-29 12:57:52 +020010121 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010122 return length;
10123}
10124
Victor Stinner9310abb2011-10-05 00:59:23 +020010125static PyObject *
10126pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010127 Py_ssize_t left,
10128 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010130{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 PyObject *u;
10132 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010133 int kind;
10134 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135
10136 if (left < 0)
10137 left = 0;
10138 if (right < 0)
10139 right = 0;
10140
Victor Stinnerc4b49542011-12-11 22:44:26 +010010141 if (left == 0 && right == 0)
10142 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10145 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010146 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10147 return NULL;
10148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010150 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010152 if (!u)
10153 return NULL;
10154
10155 kind = PyUnicode_KIND(u);
10156 data = PyUnicode_DATA(u);
10157 if (left)
10158 FILL(kind, data, fill, 0, left);
10159 if (right)
10160 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010161 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010162 assert(_PyUnicode_CheckConsistency(u, 1));
10163 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010164}
10165
Alexander Belopolsky40018472011-02-26 01:02:56 +000010166PyObject *
10167PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010168{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010169 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010170
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010171 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010172 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010173
Benjamin Petersonead6b532011-12-20 17:23:42 -060010174 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010176 if (PyUnicode_IS_ASCII(string))
10177 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010178 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010179 PyUnicode_GET_LENGTH(string), keepends);
10180 else
10181 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010182 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010183 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 break;
10185 case PyUnicode_2BYTE_KIND:
10186 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010187 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 PyUnicode_GET_LENGTH(string), keepends);
10189 break;
10190 case PyUnicode_4BYTE_KIND:
10191 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010192 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 PyUnicode_GET_LENGTH(string), keepends);
10194 break;
10195 default:
10196 assert(0);
10197 list = 0;
10198 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010199 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010200}
10201
Alexander Belopolsky40018472011-02-26 01:02:56 +000010202static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010203split(PyObject *self,
10204 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010205 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010206{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010207 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 void *buf1, *buf2;
10209 Py_ssize_t len1, len2;
10210 PyObject* out;
10211
Guido van Rossumd57fd912000-03-10 22:53:23 +000010212 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010213 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 if (PyUnicode_READY(self) == -1)
10216 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010219 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010221 if (PyUnicode_IS_ASCII(self))
10222 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010223 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010224 PyUnicode_GET_LENGTH(self), maxcount
10225 );
10226 else
10227 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010228 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010229 PyUnicode_GET_LENGTH(self), maxcount
10230 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 case PyUnicode_2BYTE_KIND:
10232 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010233 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 PyUnicode_GET_LENGTH(self), maxcount
10235 );
10236 case PyUnicode_4BYTE_KIND:
10237 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010238 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 PyUnicode_GET_LENGTH(self), maxcount
10240 );
10241 default:
10242 assert(0);
10243 return NULL;
10244 }
10245
10246 if (PyUnicode_READY(substring) == -1)
10247 return NULL;
10248
10249 kind1 = PyUnicode_KIND(self);
10250 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 len1 = PyUnicode_GET_LENGTH(self);
10252 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010253 if (kind1 < kind2 || len1 < len2) {
10254 out = PyList_New(1);
10255 if (out == NULL)
10256 return NULL;
10257 Py_INCREF(self);
10258 PyList_SET_ITEM(out, 0, self);
10259 return out;
10260 }
10261 buf1 = PyUnicode_DATA(self);
10262 buf2 = PyUnicode_DATA(substring);
10263 if (kind2 != kind1) {
10264 buf2 = _PyUnicode_AsKind(substring, kind1);
10265 if (!buf2)
10266 return NULL;
10267 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010269 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010271 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10272 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010273 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010274 else
10275 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010276 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 break;
10278 case PyUnicode_2BYTE_KIND:
10279 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010280 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 break;
10282 case PyUnicode_4BYTE_KIND:
10283 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010284 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 break;
10286 default:
10287 out = NULL;
10288 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010289 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 PyMem_Free(buf2);
10291 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010292}
10293
Alexander Belopolsky40018472011-02-26 01:02:56 +000010294static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010295rsplit(PyObject *self,
10296 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010297 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010298{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010299 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 void *buf1, *buf2;
10301 Py_ssize_t len1, len2;
10302 PyObject* out;
10303
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010304 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010305 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 if (PyUnicode_READY(self) == -1)
10308 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010311 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010313 if (PyUnicode_IS_ASCII(self))
10314 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010315 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010316 PyUnicode_GET_LENGTH(self), maxcount
10317 );
10318 else
10319 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010320 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010321 PyUnicode_GET_LENGTH(self), maxcount
10322 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 case PyUnicode_2BYTE_KIND:
10324 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010325 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326 PyUnicode_GET_LENGTH(self), maxcount
10327 );
10328 case PyUnicode_4BYTE_KIND:
10329 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010330 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 PyUnicode_GET_LENGTH(self), maxcount
10332 );
10333 default:
10334 assert(0);
10335 return NULL;
10336 }
10337
10338 if (PyUnicode_READY(substring) == -1)
10339 return NULL;
10340
10341 kind1 = PyUnicode_KIND(self);
10342 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 len1 = PyUnicode_GET_LENGTH(self);
10344 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010345 if (kind1 < kind2 || len1 < len2) {
10346 out = PyList_New(1);
10347 if (out == NULL)
10348 return NULL;
10349 Py_INCREF(self);
10350 PyList_SET_ITEM(out, 0, self);
10351 return out;
10352 }
10353 buf1 = PyUnicode_DATA(self);
10354 buf2 = PyUnicode_DATA(substring);
10355 if (kind2 != kind1) {
10356 buf2 = _PyUnicode_AsKind(substring, kind1);
10357 if (!buf2)
10358 return NULL;
10359 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010361 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010362 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010363 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10364 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010365 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010366 else
10367 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010368 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 break;
10370 case PyUnicode_2BYTE_KIND:
10371 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010372 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 break;
10374 case PyUnicode_4BYTE_KIND:
10375 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010376 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 break;
10378 default:
10379 out = NULL;
10380 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010381 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 PyMem_Free(buf2);
10383 return out;
10384}
10385
10386static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010387anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10388 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010390 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010392 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10393 return asciilib_find(buf1, len1, buf2, len2, offset);
10394 else
10395 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 case PyUnicode_2BYTE_KIND:
10397 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10398 case PyUnicode_4BYTE_KIND:
10399 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10400 }
10401 assert(0);
10402 return -1;
10403}
10404
10405static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010406anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10407 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010409 switch (kind) {
10410 case PyUnicode_1BYTE_KIND:
10411 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10412 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10413 else
10414 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10415 case PyUnicode_2BYTE_KIND:
10416 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10417 case PyUnicode_4BYTE_KIND:
10418 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10419 }
10420 assert(0);
10421 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010422}
10423
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010424static void
10425replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10426 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10427{
10428 int kind = PyUnicode_KIND(u);
10429 void *data = PyUnicode_DATA(u);
10430 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10431 if (kind == PyUnicode_1BYTE_KIND) {
10432 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10433 (Py_UCS1 *)data + len,
10434 u1, u2, maxcount);
10435 }
10436 else if (kind == PyUnicode_2BYTE_KIND) {
10437 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10438 (Py_UCS2 *)data + len,
10439 u1, u2, maxcount);
10440 }
10441 else {
10442 assert(kind == PyUnicode_4BYTE_KIND);
10443 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10444 (Py_UCS4 *)data + len,
10445 u1, u2, maxcount);
10446 }
10447}
10448
Alexander Belopolsky40018472011-02-26 01:02:56 +000010449static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450replace(PyObject *self, PyObject *str1,
10451 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010452{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010453 PyObject *u;
10454 char *sbuf = PyUnicode_DATA(self);
10455 char *buf1 = PyUnicode_DATA(str1);
10456 char *buf2 = PyUnicode_DATA(str2);
10457 int srelease = 0, release1 = 0, release2 = 0;
10458 int skind = PyUnicode_KIND(self);
10459 int kind1 = PyUnicode_KIND(str1);
10460 int kind2 = PyUnicode_KIND(str2);
10461 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10462 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10463 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010464 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010465 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010466
10467 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010468 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010469 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010470 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010471
Victor Stinner59de0ee2011-10-07 10:01:28 +020010472 if (str1 == str2)
10473 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474
Victor Stinner49a0a212011-10-12 23:46:10 +020010475 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010476 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10477 if (maxchar < maxchar_str1)
10478 /* substring too wide to be present */
10479 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010480 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10481 /* Replacing str1 with str2 may cause a maxchar reduction in the
10482 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010483 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010484 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010487 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010489 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010491 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010492 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010493 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010494
Victor Stinner69ed0f42013-04-09 21:48:24 +020010495 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010496 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010497 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010498 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010499 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010501 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010503
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010504 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10505 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010506 }
10507 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010508 int rkind = skind;
10509 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010510 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010512 if (kind1 < rkind) {
10513 /* widen substring */
10514 buf1 = _PyUnicode_AsKind(str1, rkind);
10515 if (!buf1) goto error;
10516 release1 = 1;
10517 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010518 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010519 if (i < 0)
10520 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 if (rkind > kind2) {
10522 /* widen replacement */
10523 buf2 = _PyUnicode_AsKind(str2, rkind);
10524 if (!buf2) goto error;
10525 release2 = 1;
10526 }
10527 else if (rkind < kind2) {
10528 /* widen self and buf1 */
10529 rkind = kind2;
10530 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010531 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 sbuf = _PyUnicode_AsKind(self, rkind);
10533 if (!sbuf) goto error;
10534 srelease = 1;
10535 buf1 = _PyUnicode_AsKind(str1, rkind);
10536 if (!buf1) goto error;
10537 release1 = 1;
10538 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010539 u = PyUnicode_New(slen, maxchar);
10540 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010542 assert(PyUnicode_KIND(u) == rkind);
10543 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010544
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010545 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010546 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010547 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010548 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010549 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010551
10552 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010553 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010554 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010555 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010556 if (i == -1)
10557 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010558 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010560 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010562 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010563 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010564 }
10565 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010567 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010568 int rkind = skind;
10569 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010572 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 buf1 = _PyUnicode_AsKind(str1, rkind);
10574 if (!buf1) goto error;
10575 release1 = 1;
10576 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010577 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010578 if (n == 0)
10579 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010581 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 buf2 = _PyUnicode_AsKind(str2, rkind);
10583 if (!buf2) goto error;
10584 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010585 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010587 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 rkind = kind2;
10589 sbuf = _PyUnicode_AsKind(self, rkind);
10590 if (!sbuf) goto error;
10591 srelease = 1;
10592 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010593 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010594 buf1 = _PyUnicode_AsKind(str1, rkind);
10595 if (!buf1) goto error;
10596 release1 = 1;
10597 }
10598 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10599 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010600 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 PyErr_SetString(PyExc_OverflowError,
10602 "replace string is too long");
10603 goto error;
10604 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010605 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010606 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010607 _Py_INCREF_UNICODE_EMPTY();
10608 if (!unicode_empty)
10609 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010610 u = unicode_empty;
10611 goto done;
10612 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010613 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 PyErr_SetString(PyExc_OverflowError,
10615 "replace string is too long");
10616 goto error;
10617 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010618 u = PyUnicode_New(new_size, maxchar);
10619 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010620 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010621 assert(PyUnicode_KIND(u) == rkind);
10622 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 ires = i = 0;
10624 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010625 while (n-- > 0) {
10626 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010627 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010628 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010629 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010630 if (j == -1)
10631 break;
10632 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010633 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010634 memcpy(res + rkind * ires,
10635 sbuf + rkind * i,
10636 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010637 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010638 }
10639 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010641 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010643 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010645 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010647 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010648 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010649 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010650 memcpy(res + rkind * ires,
10651 sbuf + rkind * i,
10652 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010653 }
10654 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010655 /* interleave */
10656 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010657 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010659 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010660 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010661 if (--n <= 0)
10662 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010663 memcpy(res + rkind * ires,
10664 sbuf + rkind * i,
10665 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 ires++;
10667 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010668 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010669 memcpy(res + rkind * ires,
10670 sbuf + rkind * i,
10671 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010672 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010673 }
10674
10675 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010676 unicode_adjust_maxchar(&u);
10677 if (u == NULL)
10678 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010679 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010680
10681 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010682 if (srelease)
10683 PyMem_FREE(sbuf);
10684 if (release1)
10685 PyMem_FREE(buf1);
10686 if (release2)
10687 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010688 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010690
Benjamin Peterson29060642009-01-31 22:14:21 +000010691 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010692 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 if (srelease)
10694 PyMem_FREE(sbuf);
10695 if (release1)
10696 PyMem_FREE(buf1);
10697 if (release2)
10698 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010699 return unicode_result_unchanged(self);
10700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010701 error:
10702 if (srelease && sbuf)
10703 PyMem_FREE(sbuf);
10704 if (release1 && buf1)
10705 PyMem_FREE(buf1);
10706 if (release2 && buf2)
10707 PyMem_FREE(buf2);
10708 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010709}
10710
10711/* --- Unicode Object Methods --------------------------------------------- */
10712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010713PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010714 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010715\n\
10716Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010717characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718
10719static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010720unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010721{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010722 if (PyUnicode_READY(self) == -1)
10723 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010724 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010725}
10726
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010727PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010728 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010729\n\
10730Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010731have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010732
10733static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010734unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010735{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010736 if (PyUnicode_READY(self) == -1)
10737 return NULL;
10738 if (PyUnicode_GET_LENGTH(self) == 0)
10739 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010740 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010741}
10742
Benjamin Petersond5890c82012-01-14 13:23:30 -050010743PyDoc_STRVAR(casefold__doc__,
10744 "S.casefold() -> str\n\
10745\n\
10746Return a version of S suitable for caseless comparisons.");
10747
10748static PyObject *
10749unicode_casefold(PyObject *self)
10750{
10751 if (PyUnicode_READY(self) == -1)
10752 return NULL;
10753 if (PyUnicode_IS_ASCII(self))
10754 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010755 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010756}
10757
10758
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010759/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010760
10761static int
10762convert_uc(PyObject *obj, void *addr)
10763{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010764 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010765
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010766 if (!PyUnicode_Check(obj)) {
10767 PyErr_Format(PyExc_TypeError,
10768 "The fill character must be a unicode character, "
10769 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010770 return 0;
10771 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010772 if (PyUnicode_READY(obj) < 0)
10773 return 0;
10774 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010775 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010776 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010777 return 0;
10778 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010779 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010780 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010781}
10782
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010783PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010784 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010786Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010787done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010788
10789static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010790unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010791{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010792 Py_ssize_t marg, left;
10793 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 Py_UCS4 fillchar = ' ';
10795
Victor Stinnere9a29352011-10-01 02:14:59 +020010796 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010797 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798
Benjamin Petersonbac79492012-01-14 13:34:47 -050010799 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010800 return NULL;
10801
Victor Stinnerc4b49542011-12-11 22:44:26 +010010802 if (PyUnicode_GET_LENGTH(self) >= width)
10803 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010804
Victor Stinnerc4b49542011-12-11 22:44:26 +010010805 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010806 left = marg / 2 + (marg & width & 1);
10807
Victor Stinner9310abb2011-10-05 00:59:23 +020010808 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010809}
10810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010811/* This function assumes that str1 and str2 are readied by the caller. */
10812
Marc-André Lemburge5034372000-08-08 08:04:29 +000010813static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010814unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010815{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010816#define COMPARE(TYPE1, TYPE2) \
10817 do { \
10818 TYPE1* p1 = (TYPE1 *)data1; \
10819 TYPE2* p2 = (TYPE2 *)data2; \
10820 TYPE1* end = p1 + len; \
10821 Py_UCS4 c1, c2; \
10822 for (; p1 != end; p1++, p2++) { \
10823 c1 = *p1; \
10824 c2 = *p2; \
10825 if (c1 != c2) \
10826 return (c1 < c2) ? -1 : 1; \
10827 } \
10828 } \
10829 while (0)
10830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010831 int kind1, kind2;
10832 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010833 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010834
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010835 kind1 = PyUnicode_KIND(str1);
10836 kind2 = PyUnicode_KIND(str2);
10837 data1 = PyUnicode_DATA(str1);
10838 data2 = PyUnicode_DATA(str2);
10839 len1 = PyUnicode_GET_LENGTH(str1);
10840 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010841 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010842
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010843 switch(kind1) {
10844 case PyUnicode_1BYTE_KIND:
10845 {
10846 switch(kind2) {
10847 case PyUnicode_1BYTE_KIND:
10848 {
10849 int cmp = memcmp(data1, data2, len);
10850 /* normalize result of memcmp() into the range [-1; 1] */
10851 if (cmp < 0)
10852 return -1;
10853 if (cmp > 0)
10854 return 1;
10855 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010856 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010857 case PyUnicode_2BYTE_KIND:
10858 COMPARE(Py_UCS1, Py_UCS2);
10859 break;
10860 case PyUnicode_4BYTE_KIND:
10861 COMPARE(Py_UCS1, Py_UCS4);
10862 break;
10863 default:
10864 assert(0);
10865 }
10866 break;
10867 }
10868 case PyUnicode_2BYTE_KIND:
10869 {
10870 switch(kind2) {
10871 case PyUnicode_1BYTE_KIND:
10872 COMPARE(Py_UCS2, Py_UCS1);
10873 break;
10874 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010875 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010876 COMPARE(Py_UCS2, Py_UCS2);
10877 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010878 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010879 case PyUnicode_4BYTE_KIND:
10880 COMPARE(Py_UCS2, Py_UCS4);
10881 break;
10882 default:
10883 assert(0);
10884 }
10885 break;
10886 }
10887 case PyUnicode_4BYTE_KIND:
10888 {
10889 switch(kind2) {
10890 case PyUnicode_1BYTE_KIND:
10891 COMPARE(Py_UCS4, Py_UCS1);
10892 break;
10893 case PyUnicode_2BYTE_KIND:
10894 COMPARE(Py_UCS4, Py_UCS2);
10895 break;
10896 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010897 {
10898#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10899 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10900 /* normalize result of wmemcmp() into the range [-1; 1] */
10901 if (cmp < 0)
10902 return -1;
10903 if (cmp > 0)
10904 return 1;
10905#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010906 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010907#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010908 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010909 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010910 default:
10911 assert(0);
10912 }
10913 break;
10914 }
10915 default:
10916 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010917 }
10918
Victor Stinner770e19e2012-10-04 22:59:45 +020010919 if (len1 == len2)
10920 return 0;
10921 if (len1 < len2)
10922 return -1;
10923 else
10924 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010925
10926#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010927}
10928
Benjamin Peterson621b4302016-09-09 13:54:34 -070010929static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010930unicode_compare_eq(PyObject *str1, PyObject *str2)
10931{
10932 int kind;
10933 void *data1, *data2;
10934 Py_ssize_t len;
10935 int cmp;
10936
Victor Stinnere5567ad2012-10-23 02:48:49 +020010937 len = PyUnicode_GET_LENGTH(str1);
10938 if (PyUnicode_GET_LENGTH(str2) != len)
10939 return 0;
10940 kind = PyUnicode_KIND(str1);
10941 if (PyUnicode_KIND(str2) != kind)
10942 return 0;
10943 data1 = PyUnicode_DATA(str1);
10944 data2 = PyUnicode_DATA(str2);
10945
10946 cmp = memcmp(data1, data2, len * kind);
10947 return (cmp == 0);
10948}
10949
10950
Alexander Belopolsky40018472011-02-26 01:02:56 +000010951int
10952PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010954 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10955 if (PyUnicode_READY(left) == -1 ||
10956 PyUnicode_READY(right) == -1)
10957 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010958
10959 /* a string is equal to itself */
10960 if (left == right)
10961 return 0;
10962
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010963 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010965 PyErr_Format(PyExc_TypeError,
10966 "Can't compare %.100s and %.100s",
10967 left->ob_type->tp_name,
10968 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010969 return -1;
10970}
10971
Martin v. Löwis5b222132007-06-10 09:51:05 +000010972int
10973PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10974{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010975 Py_ssize_t i;
10976 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010977 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010978 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010979
Victor Stinner910337b2011-10-03 03:20:16 +020010980 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010981 if (!PyUnicode_IS_READY(uni)) {
10982 const wchar_t *ws = _PyUnicode_WSTR(uni);
10983 /* Compare Unicode string and source character set string */
10984 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10985 if (chr != ustr[i])
10986 return (chr < ustr[i]) ? -1 : 1;
10987 }
10988 /* This check keeps Python strings that end in '\0' from comparing equal
10989 to C strings identical up to that point. */
10990 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10991 return 1; /* uni is longer */
10992 if (ustr[i])
10993 return -1; /* str is longer */
10994 return 0;
10995 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010997 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010998 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010999 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011000 size_t len, len2 = strlen(str);
11001 int cmp;
11002
11003 len = Py_MIN(len1, len2);
11004 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011005 if (cmp != 0) {
11006 if (cmp < 0)
11007 return -1;
11008 else
11009 return 1;
11010 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011011 if (len1 > len2)
11012 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011013 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011014 return -1; /* str is longer */
11015 return 0;
11016 }
11017 else {
11018 void *data = PyUnicode_DATA(uni);
11019 /* Compare Unicode string and source character set string */
11020 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011021 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011022 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11023 /* This check keeps Python strings that end in '\0' from comparing equal
11024 to C strings identical up to that point. */
11025 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11026 return 1; /* uni is longer */
11027 if (str[i])
11028 return -1; /* str is longer */
11029 return 0;
11030 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011031}
11032
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011033static int
11034non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11035{
11036 size_t i, len;
11037 const wchar_t *p;
11038 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11039 if (strlen(str) != len)
11040 return 0;
11041 p = _PyUnicode_WSTR(unicode);
11042 assert(p);
11043 for (i = 0; i < len; i++) {
11044 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011045 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011046 return 0;
11047 }
11048 return 1;
11049}
11050
11051int
11052_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11053{
11054 size_t len;
11055 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011056 assert(str);
11057#ifndef NDEBUG
11058 for (const char *p = str; *p; p++) {
11059 assert((unsigned char)*p < 128);
11060 }
11061#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011062 if (PyUnicode_READY(unicode) == -1) {
11063 /* Memory error or bad data */
11064 PyErr_Clear();
11065 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11066 }
11067 if (!PyUnicode_IS_ASCII(unicode))
11068 return 0;
11069 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11070 return strlen(str) == len &&
11071 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11072}
11073
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011074int
11075_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11076{
11077 PyObject *right_uni;
11078 Py_hash_t hash;
11079
11080 assert(_PyUnicode_CHECK(left));
11081 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011082#ifndef NDEBUG
11083 for (const char *p = right->string; *p; p++) {
11084 assert((unsigned char)*p < 128);
11085 }
11086#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011087
11088 if (PyUnicode_READY(left) == -1) {
11089 /* memory error or bad data */
11090 PyErr_Clear();
11091 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11092 }
11093
11094 if (!PyUnicode_IS_ASCII(left))
11095 return 0;
11096
11097 right_uni = _PyUnicode_FromId(right); /* borrowed */
11098 if (right_uni == NULL) {
11099 /* memory error or bad data */
11100 PyErr_Clear();
11101 return _PyUnicode_EqualToASCIIString(left, right->string);
11102 }
11103
11104 if (left == right_uni)
11105 return 1;
11106
11107 if (PyUnicode_CHECK_INTERNED(left))
11108 return 0;
11109
11110 assert(_PyUnicode_HASH(right_uni) != 1);
11111 hash = _PyUnicode_HASH(left);
11112 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11113 return 0;
11114
11115 return unicode_compare_eq(left, right_uni);
11116}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011117
Benjamin Peterson29060642009-01-31 22:14:21 +000011118#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011119 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011120
Alexander Belopolsky40018472011-02-26 01:02:56 +000011121PyObject *
11122PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011123{
11124 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011125 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011126
Victor Stinnere5567ad2012-10-23 02:48:49 +020011127 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11128 Py_RETURN_NOTIMPLEMENTED;
11129
11130 if (PyUnicode_READY(left) == -1 ||
11131 PyUnicode_READY(right) == -1)
11132 return NULL;
11133
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011134 if (left == right) {
11135 switch (op) {
11136 case Py_EQ:
11137 case Py_LE:
11138 case Py_GE:
11139 /* a string is equal to itself */
11140 v = Py_True;
11141 break;
11142 case Py_NE:
11143 case Py_LT:
11144 case Py_GT:
11145 v = Py_False;
11146 break;
11147 default:
11148 PyErr_BadArgument();
11149 return NULL;
11150 }
11151 }
11152 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011153 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011154 result ^= (op == Py_NE);
11155 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011156 }
11157 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011158 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011159
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011160 /* Convert the return value to a Boolean */
11161 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011162 case Py_LE:
11163 v = TEST_COND(result <= 0);
11164 break;
11165 case Py_GE:
11166 v = TEST_COND(result >= 0);
11167 break;
11168 case Py_LT:
11169 v = TEST_COND(result == -1);
11170 break;
11171 case Py_GT:
11172 v = TEST_COND(result == 1);
11173 break;
11174 default:
11175 PyErr_BadArgument();
11176 return NULL;
11177 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011178 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011179 Py_INCREF(v);
11180 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011181}
11182
Alexander Belopolsky40018472011-02-26 01:02:56 +000011183int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011184_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11185{
11186 return unicode_eq(aa, bb);
11187}
11188
11189int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011190PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011191{
Victor Stinner77282cb2013-04-14 19:22:47 +020011192 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011193 void *buf1, *buf2;
11194 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011195 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011196
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011197 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011198 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011199 "'in <string>' requires string as left operand, not %.100s",
11200 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011201 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011202 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011203 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011204 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011205 if (ensure_unicode(str) < 0)
11206 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011208 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011209 kind2 = PyUnicode_KIND(substr);
11210 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011211 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011212 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011213 len2 = PyUnicode_GET_LENGTH(substr);
11214 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011215 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011216 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011217 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011218 if (len2 == 1) {
11219 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11220 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011221 return result;
11222 }
11223 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011224 buf2 = _PyUnicode_AsKind(substr, kind1);
11225 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011226 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011227 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228
Victor Stinner77282cb2013-04-14 19:22:47 +020011229 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011230 case PyUnicode_1BYTE_KIND:
11231 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11232 break;
11233 case PyUnicode_2BYTE_KIND:
11234 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11235 break;
11236 case PyUnicode_4BYTE_KIND:
11237 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11238 break;
11239 default:
11240 result = -1;
11241 assert(0);
11242 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011243
Victor Stinner77282cb2013-04-14 19:22:47 +020011244 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011245 PyMem_Free(buf2);
11246
Guido van Rossum403d68b2000-03-13 15:55:09 +000011247 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011248}
11249
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250/* Concat to string or Unicode object giving a new Unicode object. */
11251
Alexander Belopolsky40018472011-02-26 01:02:56 +000011252PyObject *
11253PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011254{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011255 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011256 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011257 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011258
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011259 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11260 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261
11262 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011263 if (left == unicode_empty)
11264 return PyUnicode_FromObject(right);
11265 if (right == unicode_empty)
11266 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011268 left_len = PyUnicode_GET_LENGTH(left);
11269 right_len = PyUnicode_GET_LENGTH(right);
11270 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011271 PyErr_SetString(PyExc_OverflowError,
11272 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011273 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011274 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011275 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011276
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011277 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11278 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011279 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011280
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011282 result = PyUnicode_New(new_len, maxchar);
11283 if (result == NULL)
11284 return NULL;
11285 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11286 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11287 assert(_PyUnicode_CheckConsistency(result, 1));
11288 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289}
11290
Walter Dörwald1ab83302007-05-18 17:15:44 +000011291void
Victor Stinner23e56682011-10-03 03:54:37 +020011292PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011293{
Victor Stinner23e56682011-10-03 03:54:37 +020011294 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011295 Py_UCS4 maxchar, maxchar2;
11296 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011297
11298 if (p_left == NULL) {
11299 if (!PyErr_Occurred())
11300 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011301 return;
11302 }
Victor Stinner23e56682011-10-03 03:54:37 +020011303 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011304 if (right == NULL || left == NULL
11305 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011306 if (!PyErr_Occurred())
11307 PyErr_BadInternalCall();
11308 goto error;
11309 }
11310
Benjamin Petersonbac79492012-01-14 13:34:47 -050011311 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011312 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011313 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011314 goto error;
11315
Victor Stinner488fa492011-12-12 00:01:39 +010011316 /* Shortcuts */
11317 if (left == unicode_empty) {
11318 Py_DECREF(left);
11319 Py_INCREF(right);
11320 *p_left = right;
11321 return;
11322 }
11323 if (right == unicode_empty)
11324 return;
11325
11326 left_len = PyUnicode_GET_LENGTH(left);
11327 right_len = PyUnicode_GET_LENGTH(right);
11328 if (left_len > PY_SSIZE_T_MAX - right_len) {
11329 PyErr_SetString(PyExc_OverflowError,
11330 "strings are too large to concat");
11331 goto error;
11332 }
11333 new_len = left_len + right_len;
11334
11335 if (unicode_modifiable(left)
11336 && PyUnicode_CheckExact(right)
11337 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011338 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11339 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011340 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011341 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011342 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11343 {
11344 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011345 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011346 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011347
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011348 /* copy 'right' into the newly allocated area of 'left' */
11349 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011350 }
Victor Stinner488fa492011-12-12 00:01:39 +010011351 else {
11352 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11353 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011354 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011355
Victor Stinner488fa492011-12-12 00:01:39 +010011356 /* Concat the two Unicode strings */
11357 res = PyUnicode_New(new_len, maxchar);
11358 if (res == NULL)
11359 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011360 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11361 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011362 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011363 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011364 }
11365 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011366 return;
11367
11368error:
Victor Stinner488fa492011-12-12 00:01:39 +010011369 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011370}
11371
11372void
11373PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11374{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011375 PyUnicode_Append(pleft, right);
11376 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011377}
11378
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011379/*
11380Wraps stringlib_parse_args_finds() and additionally ensures that the
11381first argument is a unicode object.
11382*/
11383
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011384static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011385parse_args_finds_unicode(const char * function_name, PyObject *args,
11386 PyObject **substring,
11387 Py_ssize_t *start, Py_ssize_t *end)
11388{
11389 if(stringlib_parse_args_finds(function_name, args, substring,
11390 start, end)) {
11391 if (ensure_unicode(*substring) < 0)
11392 return 0;
11393 return 1;
11394 }
11395 return 0;
11396}
11397
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011398PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011399 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011401Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011402string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011403interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404
11405static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011406unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011408 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011409 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011410 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011412 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011413 void *buf1, *buf2;
11414 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011416 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011417 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011419 kind1 = PyUnicode_KIND(self);
11420 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011421 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011422 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011423
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011424 len1 = PyUnicode_GET_LENGTH(self);
11425 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011426 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011427 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011428 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011429
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011430 buf1 = PyUnicode_DATA(self);
11431 buf2 = PyUnicode_DATA(substring);
11432 if (kind2 != kind1) {
11433 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011434 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011435 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011436 }
11437 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011438 case PyUnicode_1BYTE_KIND:
11439 iresult = ucs1lib_count(
11440 ((Py_UCS1*)buf1) + start, end - start,
11441 buf2, len2, PY_SSIZE_T_MAX
11442 );
11443 break;
11444 case PyUnicode_2BYTE_KIND:
11445 iresult = ucs2lib_count(
11446 ((Py_UCS2*)buf1) + start, end - start,
11447 buf2, len2, PY_SSIZE_T_MAX
11448 );
11449 break;
11450 case PyUnicode_4BYTE_KIND:
11451 iresult = ucs4lib_count(
11452 ((Py_UCS4*)buf1) + start, end - start,
11453 buf2, len2, PY_SSIZE_T_MAX
11454 );
11455 break;
11456 default:
11457 assert(0); iresult = 0;
11458 }
11459
11460 result = PyLong_FromSsize_t(iresult);
11461
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011462 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465 return result;
11466}
11467
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011468PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011469 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011471Encode S using the codec registered for encoding. Default encoding\n\
11472is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011473handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011474a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11475'xmlcharrefreplace' as well as any other name registered with\n\
11476codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477
11478static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011479unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011481 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 char *encoding = NULL;
11483 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011484
Benjamin Peterson308d6372009-09-18 21:42:35 +000011485 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11486 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011488 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011489}
11490
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011491PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011492 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493\n\
11494Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011495If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496
11497static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011498unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011500 Py_ssize_t i, j, line_pos, src_len, incr;
11501 Py_UCS4 ch;
11502 PyObject *u;
11503 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011504 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011506 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011507 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508
Ezio Melotti745d54d2013-11-16 19:10:57 +020011509 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11510 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011511 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512
Antoine Pitrou22425222011-10-04 19:10:51 +020011513 if (PyUnicode_READY(self) == -1)
11514 return NULL;
11515
Thomas Wouters7e474022000-07-16 12:04:32 +000011516 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011517 src_len = PyUnicode_GET_LENGTH(self);
11518 i = j = line_pos = 0;
11519 kind = PyUnicode_KIND(self);
11520 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011521 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011522 for (; i < src_len; i++) {
11523 ch = PyUnicode_READ(kind, src_data, i);
11524 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011525 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011526 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011527 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011529 goto overflow;
11530 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011531 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011532 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011533 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011535 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011536 goto overflow;
11537 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011539 if (ch == '\n' || ch == '\r')
11540 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011542 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011543 if (!found)
11544 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011545
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011547 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548 if (!u)
11549 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011550 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551
Antoine Pitroue71d5742011-10-04 15:55:09 +020011552 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553
Antoine Pitroue71d5742011-10-04 15:55:09 +020011554 for (; i < src_len; i++) {
11555 ch = PyUnicode_READ(kind, src_data, i);
11556 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011557 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011558 incr = tabsize - (line_pos % tabsize);
11559 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011560 FILL(kind, dest_data, ' ', j, incr);
11561 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011562 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011563 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011564 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011565 line_pos++;
11566 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011567 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011568 if (ch == '\n' || ch == '\r')
11569 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011571 }
11572 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011573 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011574
Antoine Pitroue71d5742011-10-04 15:55:09 +020011575 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011576 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11577 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578}
11579
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011580PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011581 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011582\n\
11583Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011584such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585arguments start and end are interpreted as in slice notation.\n\
11586\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011587Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588
11589static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011592 /* initialize variables to prevent gcc warning */
11593 PyObject *substring = NULL;
11594 Py_ssize_t start = 0;
11595 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011596 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011598 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011601 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011602 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011604 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011606 if (result == -2)
11607 return NULL;
11608
Christian Heimes217cfd12007-12-02 14:31:20 +000011609 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610}
11611
11612static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011613unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011615 void *data;
11616 enum PyUnicode_Kind kind;
11617 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011618
11619 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11620 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011622 }
11623 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11624 PyErr_SetString(PyExc_IndexError, "string index out of range");
11625 return NULL;
11626 }
11627 kind = PyUnicode_KIND(self);
11628 data = PyUnicode_DATA(self);
11629 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011630 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631}
11632
Guido van Rossumc2504932007-09-18 19:42:40 +000011633/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011634 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011635static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011636unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011637{
Guido van Rossumc2504932007-09-18 19:42:40 +000011638 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011639 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011640
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011641#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011642 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011643#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (_PyUnicode_HASH(self) != -1)
11645 return _PyUnicode_HASH(self);
11646 if (PyUnicode_READY(self) == -1)
11647 return -1;
11648 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011649 /*
11650 We make the hash of the empty string be 0, rather than using
11651 (prefix ^ suffix), since this slightly obfuscates the hash secret
11652 */
11653 if (len == 0) {
11654 _PyUnicode_HASH(self) = 0;
11655 return 0;
11656 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011657 x = _Py_HashBytes(PyUnicode_DATA(self),
11658 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011659 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011660 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661}
11662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011663PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011664 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011666Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667
11668static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011671 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011672 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011673 PyObject *substring = NULL;
11674 Py_ssize_t start = 0;
11675 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011677 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011679
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011680 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011682
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011683 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011684
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011685 if (result == -2)
11686 return NULL;
11687
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688 if (result < 0) {
11689 PyErr_SetString(PyExc_ValueError, "substring not found");
11690 return NULL;
11691 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011692
Christian Heimes217cfd12007-12-02 14:31:20 +000011693 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694}
11695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011696PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011697 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011699Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011700at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701
11702static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011703unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 Py_ssize_t i, length;
11706 int kind;
11707 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708 int cased;
11709
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 if (PyUnicode_READY(self) == -1)
11711 return NULL;
11712 length = PyUnicode_GET_LENGTH(self);
11713 kind = PyUnicode_KIND(self);
11714 data = PyUnicode_DATA(self);
11715
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717 if (length == 1)
11718 return PyBool_FromLong(
11719 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011721 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011723 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011724
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 for (i = 0; i < length; i++) {
11727 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011728
Benjamin Peterson29060642009-01-31 22:14:21 +000011729 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11730 return PyBool_FromLong(0);
11731 else if (!cased && Py_UNICODE_ISLOWER(ch))
11732 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011734 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735}
11736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011737PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011738 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011740Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011741at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742
11743static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011744unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011746 Py_ssize_t i, length;
11747 int kind;
11748 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749 int cased;
11750
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 if (PyUnicode_READY(self) == -1)
11752 return NULL;
11753 length = PyUnicode_GET_LENGTH(self);
11754 kind = PyUnicode_KIND(self);
11755 data = PyUnicode_DATA(self);
11756
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011758 if (length == 1)
11759 return PyBool_FromLong(
11760 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011762 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011764 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011765
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767 for (i = 0; i < length; i++) {
11768 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011769
Benjamin Peterson29060642009-01-31 22:14:21 +000011770 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11771 return PyBool_FromLong(0);
11772 else if (!cased && Py_UNICODE_ISUPPER(ch))
11773 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011775 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776}
11777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011778PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011779 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011781Return True if S is a titlecased string and there is at least one\n\
11782character in S, i.e. upper- and titlecase characters may only\n\
11783follow uncased characters and lowercase characters only cased ones.\n\
11784Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785
11786static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011787unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011789 Py_ssize_t i, length;
11790 int kind;
11791 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792 int cased, previous_is_cased;
11793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011794 if (PyUnicode_READY(self) == -1)
11795 return NULL;
11796 length = PyUnicode_GET_LENGTH(self);
11797 kind = PyUnicode_KIND(self);
11798 data = PyUnicode_DATA(self);
11799
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 if (length == 1) {
11802 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11803 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11804 (Py_UNICODE_ISUPPER(ch) != 0));
11805 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011807 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011809 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011810
Guido van Rossumd57fd912000-03-10 22:53:23 +000011811 cased = 0;
11812 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011813 for (i = 0; i < length; i++) {
11814 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011815
Benjamin Peterson29060642009-01-31 22:14:21 +000011816 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11817 if (previous_is_cased)
11818 return PyBool_FromLong(0);
11819 previous_is_cased = 1;
11820 cased = 1;
11821 }
11822 else if (Py_UNICODE_ISLOWER(ch)) {
11823 if (!previous_is_cased)
11824 return PyBool_FromLong(0);
11825 previous_is_cased = 1;
11826 cased = 1;
11827 }
11828 else
11829 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011831 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011832}
11833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011834PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011835 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011837Return True if all characters in S are whitespace\n\
11838and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011839
11840static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011841unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011843 Py_ssize_t i, length;
11844 int kind;
11845 void *data;
11846
11847 if (PyUnicode_READY(self) == -1)
11848 return NULL;
11849 length = PyUnicode_GET_LENGTH(self);
11850 kind = PyUnicode_KIND(self);
11851 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011852
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011854 if (length == 1)
11855 return PyBool_FromLong(
11856 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011858 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011860 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 for (i = 0; i < length; i++) {
11863 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011864 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011865 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011867 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868}
11869
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011870PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011871 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011872\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011873Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011874and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011875
11876static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011877unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011878{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879 Py_ssize_t i, length;
11880 int kind;
11881 void *data;
11882
11883 if (PyUnicode_READY(self) == -1)
11884 return NULL;
11885 length = PyUnicode_GET_LENGTH(self);
11886 kind = PyUnicode_KIND(self);
11887 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011888
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011889 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 if (length == 1)
11891 return PyBool_FromLong(
11892 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011893
11894 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011895 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011896 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011897
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011898 for (i = 0; i < length; i++) {
11899 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011900 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011901 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011902 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011903}
11904
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011905PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011906 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011907\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011908Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011909and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011910
11911static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011912unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011913{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011914 int kind;
11915 void *data;
11916 Py_ssize_t len, i;
11917
11918 if (PyUnicode_READY(self) == -1)
11919 return NULL;
11920
11921 kind = PyUnicode_KIND(self);
11922 data = PyUnicode_DATA(self);
11923 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011924
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011925 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926 if (len == 1) {
11927 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11928 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11929 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011930
11931 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011932 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011933 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011935 for (i = 0; i < len; i++) {
11936 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011937 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011938 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011939 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011940 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011941}
11942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011943PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011944 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011946Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011947False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948
11949static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011950unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011952 Py_ssize_t i, length;
11953 int kind;
11954 void *data;
11955
11956 if (PyUnicode_READY(self) == -1)
11957 return NULL;
11958 length = PyUnicode_GET_LENGTH(self);
11959 kind = PyUnicode_KIND(self);
11960 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011961
Guido van Rossumd57fd912000-03-10 22:53:23 +000011962 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011963 if (length == 1)
11964 return PyBool_FromLong(
11965 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011967 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011969 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011970
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011971 for (i = 0; i < length; i++) {
11972 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011973 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011974 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011975 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011976}
11977
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011978PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011979 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011980\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011981Return True if all characters in S are digits\n\
11982and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983
11984static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011985unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011986{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011987 Py_ssize_t i, length;
11988 int kind;
11989 void *data;
11990
11991 if (PyUnicode_READY(self) == -1)
11992 return NULL;
11993 length = PyUnicode_GET_LENGTH(self);
11994 kind = PyUnicode_KIND(self);
11995 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011996
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011998 if (length == 1) {
11999 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12000 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12001 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012002
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012003 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012004 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012005 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012006
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007 for (i = 0; i < length; i++) {
12008 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012009 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012010 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012011 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012012}
12013
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012014PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012015 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012016\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000012017Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012018False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012019
12020static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012021unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012022{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023 Py_ssize_t i, length;
12024 int kind;
12025 void *data;
12026
12027 if (PyUnicode_READY(self) == -1)
12028 return NULL;
12029 length = PyUnicode_GET_LENGTH(self);
12030 kind = PyUnicode_KIND(self);
12031 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012032
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 if (length == 1)
12035 return PyBool_FromLong(
12036 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012037
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012038 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012040 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012042 for (i = 0; i < length; i++) {
12043 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012044 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012045 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012046 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012047}
12048
Martin v. Löwis47383402007-08-15 07:32:56 +000012049int
12050PyUnicode_IsIdentifier(PyObject *self)
12051{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012052 int kind;
12053 void *data;
12054 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012055 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012056
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012057 if (PyUnicode_READY(self) == -1) {
12058 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012059 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012060 }
12061
12062 /* Special case for empty strings */
12063 if (PyUnicode_GET_LENGTH(self) == 0)
12064 return 0;
12065 kind = PyUnicode_KIND(self);
12066 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012067
12068 /* PEP 3131 says that the first character must be in
12069 XID_Start and subsequent characters in XID_Continue,
12070 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012071 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012072 letters, digits, underscore). However, given the current
12073 definition of XID_Start and XID_Continue, it is sufficient
12074 to check just for these, except that _ must be allowed
12075 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012076 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012077 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012078 return 0;
12079
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012080 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012081 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012082 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012083 return 1;
12084}
12085
12086PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012087 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012088\n\
12089Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012090to the language definition.\n\
12091\n\
12092Use keyword.iskeyword() to test for reserved identifiers\n\
12093such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012094
12095static PyObject*
12096unicode_isidentifier(PyObject *self)
12097{
12098 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12099}
12100
Georg Brandl559e5d72008-06-11 18:37:52 +000012101PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012102 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012103\n\
12104Return True if all characters in S are considered\n\
12105printable in repr() or S is empty, False otherwise.");
12106
12107static PyObject*
12108unicode_isprintable(PyObject *self)
12109{
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);
Georg Brandl559e5d72008-06-11 18:37:52 +000012119
12120 /* 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_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125 for (i = 0; i < length; i++) {
12126 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012127 Py_RETURN_FALSE;
12128 }
12129 }
12130 Py_RETURN_TRUE;
12131}
12132
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012133PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012134 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012135\n\
12136Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012137iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138
12139static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012140unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012142 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012143}
12144
Martin v. Löwis18e16552006-02-15 17:27:45 +000012145static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012146unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012148 if (PyUnicode_READY(self) == -1)
12149 return -1;
12150 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012151}
12152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012153PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012154 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012155\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012156Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012157done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012158
12159static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012160unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012161{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012162 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012163 Py_UCS4 fillchar = ' ';
12164
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012165 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166 return NULL;
12167
Benjamin Petersonbac79492012-01-14 13:34:47 -050012168 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012169 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170
Victor Stinnerc4b49542011-12-11 22:44:26 +010012171 if (PyUnicode_GET_LENGTH(self) >= width)
12172 return unicode_result_unchanged(self);
12173
12174 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175}
12176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012177PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012178 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012180Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181
12182static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012183unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012185 if (PyUnicode_READY(self) == -1)
12186 return NULL;
12187 if (PyUnicode_IS_ASCII(self))
12188 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012189 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190}
12191
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012192#define LEFTSTRIP 0
12193#define RIGHTSTRIP 1
12194#define BOTHSTRIP 2
12195
12196/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012197static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012198
12199#define STRIPNAME(i) (stripformat[i]+3)
12200
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012201/* externally visible for str.strip(unicode) */
12202PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012203_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012204{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012205 void *data;
12206 int kind;
12207 Py_ssize_t i, j, len;
12208 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012209 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012210
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012211 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12212 return NULL;
12213
12214 kind = PyUnicode_KIND(self);
12215 data = PyUnicode_DATA(self);
12216 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012217 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012218 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12219 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012220 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012221
Benjamin Peterson14339b62009-01-31 16:36:08 +000012222 i = 0;
12223 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012224 while (i < len) {
12225 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12226 if (!BLOOM(sepmask, ch))
12227 break;
12228 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12229 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012230 i++;
12231 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012232 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012233
Benjamin Peterson14339b62009-01-31 16:36:08 +000012234 j = len;
12235 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012236 j--;
12237 while (j >= i) {
12238 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12239 if (!BLOOM(sepmask, ch))
12240 break;
12241 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12242 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012243 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012244 }
12245
Benjamin Peterson29060642009-01-31 22:14:21 +000012246 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012247 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012248
Victor Stinner7931d9a2011-11-04 00:22:48 +010012249 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012250}
12251
12252PyObject*
12253PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12254{
12255 unsigned char *data;
12256 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012257 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012258
Victor Stinnerde636f32011-10-01 03:55:54 +020012259 if (PyUnicode_READY(self) == -1)
12260 return NULL;
12261
Victor Stinner684d5fd2012-05-03 02:32:34 +020012262 length = PyUnicode_GET_LENGTH(self);
12263 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012264
Victor Stinner684d5fd2012-05-03 02:32:34 +020012265 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012266 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012267
Victor Stinnerde636f32011-10-01 03:55:54 +020012268 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012269 PyErr_SetString(PyExc_IndexError, "string index out of range");
12270 return NULL;
12271 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012272 if (start >= length || end < start)
12273 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012274
Victor Stinner684d5fd2012-05-03 02:32:34 +020012275 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012276 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012277 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012278 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012279 }
12280 else {
12281 kind = PyUnicode_KIND(self);
12282 data = PyUnicode_1BYTE_DATA(self);
12283 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012284 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012285 length);
12286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012287}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288
12289static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012290do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012291{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012292 Py_ssize_t len, i, j;
12293
12294 if (PyUnicode_READY(self) == -1)
12295 return NULL;
12296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012298
Victor Stinnercc7af722013-04-09 22:39:24 +020012299 if (PyUnicode_IS_ASCII(self)) {
12300 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12301
12302 i = 0;
12303 if (striptype != RIGHTSTRIP) {
12304 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012305 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012306 if (!_Py_ascii_whitespace[ch])
12307 break;
12308 i++;
12309 }
12310 }
12311
12312 j = len;
12313 if (striptype != LEFTSTRIP) {
12314 j--;
12315 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012316 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012317 if (!_Py_ascii_whitespace[ch])
12318 break;
12319 j--;
12320 }
12321 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012322 }
12323 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012324 else {
12325 int kind = PyUnicode_KIND(self);
12326 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012327
Victor Stinnercc7af722013-04-09 22:39:24 +020012328 i = 0;
12329 if (striptype != RIGHTSTRIP) {
12330 while (i < len) {
12331 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12332 if (!Py_UNICODE_ISSPACE(ch))
12333 break;
12334 i++;
12335 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012336 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012337
12338 j = len;
12339 if (striptype != LEFTSTRIP) {
12340 j--;
12341 while (j >= i) {
12342 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12343 if (!Py_UNICODE_ISSPACE(ch))
12344 break;
12345 j--;
12346 }
12347 j++;
12348 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012349 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012350
Victor Stinner7931d9a2011-11-04 00:22:48 +010012351 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012352}
12353
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012354
12355static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012356do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012357{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012358 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012359
Serhiy Storchakac6792272013-10-19 21:03:34 +030012360 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012361 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012362
Benjamin Peterson14339b62009-01-31 16:36:08 +000012363 if (sep != NULL && sep != Py_None) {
12364 if (PyUnicode_Check(sep))
12365 return _PyUnicode_XStrip(self, striptype, sep);
12366 else {
12367 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012368 "%s arg must be None or str",
12369 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012370 return NULL;
12371 }
12372 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012373
Benjamin Peterson14339b62009-01-31 16:36:08 +000012374 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012375}
12376
12377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012378PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012379 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012380\n\
12381Return a copy of the string S with leading and trailing\n\
12382whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012383If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012384
12385static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012386unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012387{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012388 if (PyTuple_GET_SIZE(args) == 0)
12389 return do_strip(self, BOTHSTRIP); /* Common case */
12390 else
12391 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012392}
12393
12394
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012395PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012396 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012397\n\
12398Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012399If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012400
12401static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012402unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012403{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012404 if (PyTuple_GET_SIZE(args) == 0)
12405 return do_strip(self, LEFTSTRIP); /* Common case */
12406 else
12407 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012408}
12409
12410
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012411PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012412 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012413\n\
12414Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012415If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012416
12417static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012418unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012419{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012420 if (PyTuple_GET_SIZE(args) == 0)
12421 return do_strip(self, RIGHTSTRIP); /* Common case */
12422 else
12423 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012424}
12425
12426
Guido van Rossumd57fd912000-03-10 22:53:23 +000012427static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012428unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012429{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012430 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012431 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012432
Serhiy Storchaka05997252013-01-26 12:14:02 +020012433 if (len < 1)
12434 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012435
Victor Stinnerc4b49542011-12-11 22:44:26 +010012436 /* no repeat, return original string */
12437 if (len == 1)
12438 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012439
Benjamin Petersonbac79492012-01-14 13:34:47 -050012440 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012441 return NULL;
12442
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012443 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012444 PyErr_SetString(PyExc_OverflowError,
12445 "repeated string is too long");
12446 return NULL;
12447 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012449
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012450 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012451 if (!u)
12452 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012453 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012455 if (PyUnicode_GET_LENGTH(str) == 1) {
12456 const int kind = PyUnicode_KIND(str);
12457 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012458 if (kind == PyUnicode_1BYTE_KIND) {
12459 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012460 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012461 }
12462 else if (kind == PyUnicode_2BYTE_KIND) {
12463 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012464 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012465 ucs2[n] = fill_char;
12466 } else {
12467 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12468 assert(kind == PyUnicode_4BYTE_KIND);
12469 for (n = 0; n < len; ++n)
12470 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012471 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012472 }
12473 else {
12474 /* number of characters copied this far */
12475 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012476 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012477 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012478 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012479 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012480 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012481 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012482 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012483 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012484 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012485 }
12486
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012487 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012488 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489}
12490
Alexander Belopolsky40018472011-02-26 01:02:56 +000012491PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012492PyUnicode_Replace(PyObject *str,
12493 PyObject *substr,
12494 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012495 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012496{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012497 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12498 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012499 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012500 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501}
12502
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012503PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012504 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012505\n\
12506Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012507old replaced by new. If the optional argument count is\n\
12508given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012509
12510static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012511unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012512{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012513 PyObject *str1;
12514 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012515 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012517 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012519 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012520 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012521 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522}
12523
Alexander Belopolsky40018472011-02-26 01:02:56 +000012524static PyObject *
12525unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012527 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012528 Py_ssize_t isize;
12529 Py_ssize_t osize, squote, dquote, i, o;
12530 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012531 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012532 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012533
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012534 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012535 return NULL;
12536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 isize = PyUnicode_GET_LENGTH(unicode);
12538 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012539
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012540 /* Compute length of output, quote characters, and
12541 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012542 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543 max = 127;
12544 squote = dquote = 0;
12545 ikind = PyUnicode_KIND(unicode);
12546 for (i = 0; i < isize; i++) {
12547 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012548 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012550 case '\'': squote++; break;
12551 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012553 incr = 2;
12554 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 default:
12556 /* Fast-path ASCII */
12557 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012558 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012559 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012560 ;
12561 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012562 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012564 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012566 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012568 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012569 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012570 if (osize > PY_SSIZE_T_MAX - incr) {
12571 PyErr_SetString(PyExc_OverflowError,
12572 "string is too long to generate repr");
12573 return NULL;
12574 }
12575 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012576 }
12577
12578 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012579 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012580 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012581 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 if (dquote)
12583 /* Both squote and dquote present. Use squote,
12584 and escape them */
12585 osize += squote;
12586 else
12587 quote = '"';
12588 }
Victor Stinner55c08782013-04-14 18:45:39 +020012589 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012590
12591 repr = PyUnicode_New(osize, max);
12592 if (repr == NULL)
12593 return NULL;
12594 okind = PyUnicode_KIND(repr);
12595 odata = PyUnicode_DATA(repr);
12596
12597 PyUnicode_WRITE(okind, odata, 0, quote);
12598 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012599 if (unchanged) {
12600 _PyUnicode_FastCopyCharacters(repr, 1,
12601 unicode, 0,
12602 isize);
12603 }
12604 else {
12605 for (i = 0, o = 1; i < isize; i++) {
12606 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012607
Victor Stinner55c08782013-04-14 18:45:39 +020012608 /* Escape quotes and backslashes */
12609 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012610 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012611 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012612 continue;
12613 }
12614
12615 /* Map special whitespace to '\t', \n', '\r' */
12616 if (ch == '\t') {
12617 PyUnicode_WRITE(okind, odata, o++, '\\');
12618 PyUnicode_WRITE(okind, odata, o++, 't');
12619 }
12620 else if (ch == '\n') {
12621 PyUnicode_WRITE(okind, odata, o++, '\\');
12622 PyUnicode_WRITE(okind, odata, o++, 'n');
12623 }
12624 else if (ch == '\r') {
12625 PyUnicode_WRITE(okind, odata, o++, '\\');
12626 PyUnicode_WRITE(okind, odata, o++, 'r');
12627 }
12628
12629 /* Map non-printable US ASCII to '\xhh' */
12630 else if (ch < ' ' || ch == 0x7F) {
12631 PyUnicode_WRITE(okind, odata, o++, '\\');
12632 PyUnicode_WRITE(okind, odata, o++, 'x');
12633 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12634 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12635 }
12636
12637 /* Copy ASCII characters as-is */
12638 else if (ch < 0x7F) {
12639 PyUnicode_WRITE(okind, odata, o++, ch);
12640 }
12641
12642 /* Non-ASCII characters */
12643 else {
12644 /* Map Unicode whitespace and control characters
12645 (categories Z* and C* except ASCII space)
12646 */
12647 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12648 PyUnicode_WRITE(okind, odata, o++, '\\');
12649 /* Map 8-bit characters to '\xhh' */
12650 if (ch <= 0xff) {
12651 PyUnicode_WRITE(okind, odata, o++, 'x');
12652 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12653 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12654 }
12655 /* Map 16-bit characters to '\uxxxx' */
12656 else if (ch <= 0xffff) {
12657 PyUnicode_WRITE(okind, odata, o++, 'u');
12658 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12659 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12660 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12661 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12662 }
12663 /* Map 21-bit characters to '\U00xxxxxx' */
12664 else {
12665 PyUnicode_WRITE(okind, odata, o++, 'U');
12666 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12667 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12668 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12669 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12670 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12671 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12672 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12673 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12674 }
12675 }
12676 /* Copy characters as-is */
12677 else {
12678 PyUnicode_WRITE(okind, odata, o++, ch);
12679 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012680 }
12681 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012682 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012683 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012684 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012685 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012686}
12687
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012688PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012689 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690\n\
12691Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012692such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012693arguments start and end are interpreted as in slice notation.\n\
12694\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012695Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696
12697static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012698unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012700 /* initialize variables to prevent gcc warning */
12701 PyObject *substring = NULL;
12702 Py_ssize_t start = 0;
12703 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012704 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012706 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012707 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012709 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012712 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012713
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012714 if (result == -2)
12715 return NULL;
12716
Christian Heimes217cfd12007-12-02 14:31:20 +000012717 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718}
12719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012720PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012721 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012723Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724
12725static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012727{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012728 /* initialize variables to prevent gcc warning */
12729 PyObject *substring = NULL;
12730 Py_ssize_t start = 0;
12731 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012732 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012733
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012734 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012735 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012737 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012739
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012740 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012742 if (result == -2)
12743 return NULL;
12744
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745 if (result < 0) {
12746 PyErr_SetString(PyExc_ValueError, "substring not found");
12747 return NULL;
12748 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012749
Christian Heimes217cfd12007-12-02 14:31:20 +000012750 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751}
12752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012753PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012754 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012756Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012757done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758
12759static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012760unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012762 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012763 Py_UCS4 fillchar = ' ';
12764
Victor Stinnere9a29352011-10-01 02:14:59 +020012765 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012766 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012767
Benjamin Petersonbac79492012-01-14 13:34:47 -050012768 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012769 return NULL;
12770
Victor Stinnerc4b49542011-12-11 22:44:26 +010012771 if (PyUnicode_GET_LENGTH(self) >= width)
12772 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012773
Victor Stinnerc4b49542011-12-11 22:44:26 +010012774 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775}
12776
Alexander Belopolsky40018472011-02-26 01:02:56 +000012777PyObject *
12778PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012779{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012780 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012781 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012783 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784}
12785
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012786PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012787 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012788\n\
12789Return a list of the words in S, using sep as the\n\
12790delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012791splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012792whitespace string is a separator and empty strings are\n\
12793removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794
12795static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012796unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012798 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012800 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012802 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12803 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012804 return NULL;
12805
12806 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012807 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012808
12809 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012810 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012811
12812 PyErr_Format(PyExc_TypeError,
12813 "must be str or None, not %.100s",
12814 Py_TYPE(substring)->tp_name);
12815 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816}
12817
Thomas Wouters477c8d52006-05-27 19:21:47 +000012818PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012819PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012820{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012821 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012822 int kind1, kind2;
12823 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012824 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012825
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012826 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012827 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012828
Victor Stinner14f8f022011-10-05 20:58:25 +020012829 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012830 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012831 len1 = PyUnicode_GET_LENGTH(str_obj);
12832 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012833 if (kind1 < kind2 || len1 < len2) {
12834 _Py_INCREF_UNICODE_EMPTY();
12835 if (!unicode_empty)
12836 out = NULL;
12837 else {
12838 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12839 Py_DECREF(unicode_empty);
12840 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012841 return out;
12842 }
12843 buf1 = PyUnicode_DATA(str_obj);
12844 buf2 = PyUnicode_DATA(sep_obj);
12845 if (kind2 != kind1) {
12846 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12847 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012848 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012849 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012850
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012851 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012852 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012853 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12854 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12855 else
12856 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012857 break;
12858 case PyUnicode_2BYTE_KIND:
12859 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12860 break;
12861 case PyUnicode_4BYTE_KIND:
12862 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12863 break;
12864 default:
12865 assert(0);
12866 out = 0;
12867 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012868
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012869 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012870 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012871
12872 return out;
12873}
12874
12875
12876PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012877PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012878{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012879 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012880 int kind1, kind2;
12881 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012882 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012883
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012884 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012885 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012886
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012887 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012888 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012889 len1 = PyUnicode_GET_LENGTH(str_obj);
12890 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012891 if (kind1 < kind2 || len1 < len2) {
12892 _Py_INCREF_UNICODE_EMPTY();
12893 if (!unicode_empty)
12894 out = NULL;
12895 else {
12896 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12897 Py_DECREF(unicode_empty);
12898 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012899 return out;
12900 }
12901 buf1 = PyUnicode_DATA(str_obj);
12902 buf2 = PyUnicode_DATA(sep_obj);
12903 if (kind2 != kind1) {
12904 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12905 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012906 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012907 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012908
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012909 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012910 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012911 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12912 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12913 else
12914 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012915 break;
12916 case PyUnicode_2BYTE_KIND:
12917 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12918 break;
12919 case PyUnicode_4BYTE_KIND:
12920 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12921 break;
12922 default:
12923 assert(0);
12924 out = 0;
12925 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012926
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012927 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012928 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012929
12930 return out;
12931}
12932
12933PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012934 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012935\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012936Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012937the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012938found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012939
12940static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012941unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012942{
Victor Stinner9310abb2011-10-05 00:59:23 +020012943 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012944}
12945
12946PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012947 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012948\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012949Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012950the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012951separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012952
12953static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012954unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012955{
Victor Stinner9310abb2011-10-05 00:59:23 +020012956 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012957}
12958
Alexander Belopolsky40018472011-02-26 01:02:56 +000012959PyObject *
12960PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012961{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012962 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012963 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012964
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012965 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012966}
12967
12968PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012969 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012970\n\
12971Return a list of the words in S, using sep as the\n\
12972delimiter string, starting at the end of the string and\n\
12973working to the front. If maxsplit is given, at most maxsplit\n\
12974splits are done. If sep is not specified, any whitespace string\n\
12975is a separator.");
12976
12977static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012978unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012979{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012980 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012981 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012982 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012983
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012984 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12985 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012986 return NULL;
12987
12988 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012989 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012990
12991 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012992 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012993
12994 PyErr_Format(PyExc_TypeError,
12995 "must be str or None, not %.100s",
12996 Py_TYPE(substring)->tp_name);
12997 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012998}
12999
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013000PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013001 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013002\n\
13003Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000013004Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013005is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013006
13007static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013008unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013009{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013010 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000013011 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013012
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013013 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
13014 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013015 return NULL;
13016
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013017 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013018}
13019
13020static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013021PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013022{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013023 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013024}
13025
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013026PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013027 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013028\n\
13029Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013030and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013031
13032static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013033unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013034{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013035 if (PyUnicode_READY(self) == -1)
13036 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013037 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013038}
13039
Larry Hastings61272b72014-01-07 12:41:53 -080013040/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013041
Larry Hastings31826802013-10-19 00:09:25 -070013042@staticmethod
13043str.maketrans as unicode_maketrans
13044
13045 x: object
13046
13047 y: unicode=NULL
13048
13049 z: unicode=NULL
13050
13051 /
13052
13053Return a translation table usable for str.translate().
13054
13055If there is only one argument, it must be a dictionary mapping Unicode
13056ordinals (integers) or characters to Unicode ordinals, strings or None.
13057Character keys will be then converted to ordinals.
13058If there are two arguments, they must be strings of equal length, and
13059in the resulting dictionary, each character in x will be mapped to the
13060character at the same position in y. If there is a third argument, it
13061must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013062[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013063
Larry Hastings31826802013-10-19 00:09:25 -070013064static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013065unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013066/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013067{
Georg Brandlceee0772007-11-27 23:48:05 +000013068 PyObject *new = NULL, *key, *value;
13069 Py_ssize_t i = 0;
13070 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013071
Georg Brandlceee0772007-11-27 23:48:05 +000013072 new = PyDict_New();
13073 if (!new)
13074 return NULL;
13075 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013076 int x_kind, y_kind, z_kind;
13077 void *x_data, *y_data, *z_data;
13078
Georg Brandlceee0772007-11-27 23:48:05 +000013079 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013080 if (!PyUnicode_Check(x)) {
13081 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13082 "be a string if there is a second argument");
13083 goto err;
13084 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013085 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013086 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13087 "arguments must have equal length");
13088 goto err;
13089 }
13090 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013091 x_kind = PyUnicode_KIND(x);
13092 y_kind = PyUnicode_KIND(y);
13093 x_data = PyUnicode_DATA(x);
13094 y_data = PyUnicode_DATA(y);
13095 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13096 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013097 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013098 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013099 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013100 if (!value) {
13101 Py_DECREF(key);
13102 goto err;
13103 }
Georg Brandlceee0772007-11-27 23:48:05 +000013104 res = PyDict_SetItem(new, key, value);
13105 Py_DECREF(key);
13106 Py_DECREF(value);
13107 if (res < 0)
13108 goto err;
13109 }
13110 /* create entries for deleting chars in z */
13111 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013112 z_kind = PyUnicode_KIND(z);
13113 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013114 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013115 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013116 if (!key)
13117 goto err;
13118 res = PyDict_SetItem(new, key, Py_None);
13119 Py_DECREF(key);
13120 if (res < 0)
13121 goto err;
13122 }
13123 }
13124 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013125 int kind;
13126 void *data;
13127
Georg Brandlceee0772007-11-27 23:48:05 +000013128 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013129 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013130 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13131 "to maketrans it must be a dict");
13132 goto err;
13133 }
13134 /* copy entries into the new dict, converting string keys to int keys */
13135 while (PyDict_Next(x, &i, &key, &value)) {
13136 if (PyUnicode_Check(key)) {
13137 /* convert string keys to integer keys */
13138 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013139 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013140 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13141 "table must be of length 1");
13142 goto err;
13143 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 kind = PyUnicode_KIND(key);
13145 data = PyUnicode_DATA(key);
13146 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013147 if (!newkey)
13148 goto err;
13149 res = PyDict_SetItem(new, newkey, value);
13150 Py_DECREF(newkey);
13151 if (res < 0)
13152 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013153 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013154 /* just keep integer keys */
13155 if (PyDict_SetItem(new, key, value) < 0)
13156 goto err;
13157 } else {
13158 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13159 "be strings or integers");
13160 goto err;
13161 }
13162 }
13163 }
13164 return new;
13165 err:
13166 Py_DECREF(new);
13167 return NULL;
13168}
13169
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013170PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013171 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013172\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013173Return a copy of the string S in which each character has been mapped\n\
13174through the given translation table. The table must implement\n\
13175lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13176mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13177this operation raises LookupError, the character is left untouched.\n\
13178Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013179
13180static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013181unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013182{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013183 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184}
13185
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013186PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013187 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013189Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190
13191static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013192unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013194 if (PyUnicode_READY(self) == -1)
13195 return NULL;
13196 if (PyUnicode_IS_ASCII(self))
13197 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013198 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199}
13200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013201PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013202 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013204Pad a numeric string S with zeros on the left, to fill a field\n\
13205of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013206
13207static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013208unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013210 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013211 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013212 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013213 int kind;
13214 void *data;
13215 Py_UCS4 chr;
13216
Martin v. Löwis18e16552006-02-15 17:27:45 +000013217 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218 return NULL;
13219
Benjamin Petersonbac79492012-01-14 13:34:47 -050013220 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013221 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013222
Victor Stinnerc4b49542011-12-11 22:44:26 +010013223 if (PyUnicode_GET_LENGTH(self) >= width)
13224 return unicode_result_unchanged(self);
13225
13226 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227
13228 u = pad(self, fill, 0, '0');
13229
Walter Dörwald068325e2002-04-15 13:36:47 +000013230 if (u == NULL)
13231 return NULL;
13232
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013233 kind = PyUnicode_KIND(u);
13234 data = PyUnicode_DATA(u);
13235 chr = PyUnicode_READ(kind, data, fill);
13236
13237 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013238 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013239 PyUnicode_WRITE(kind, data, 0, chr);
13240 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013241 }
13242
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013243 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013244 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013245}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013246
13247#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013248static PyObject *
13249unicode__decimal2ascii(PyObject *self)
13250{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013251 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013252}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013253#endif
13254
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013255PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013256 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013257\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013258Return True if S starts with the specified prefix, False otherwise.\n\
13259With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013260With optional end, stop comparing S at that position.\n\
13261prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013262
13263static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013264unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013265 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013266{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013267 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013268 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013269 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013270 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013271 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013272
Jesus Ceaac451502011-04-20 17:09:23 +020013273 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013274 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013275 if (PyTuple_Check(subobj)) {
13276 Py_ssize_t i;
13277 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013278 substring = PyTuple_GET_ITEM(subobj, i);
13279 if (!PyUnicode_Check(substring)) {
13280 PyErr_Format(PyExc_TypeError,
13281 "tuple for startswith must only contain str, "
13282 "not %.100s",
13283 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013284 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013285 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013286 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013287 if (result == -1)
13288 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013289 if (result) {
13290 Py_RETURN_TRUE;
13291 }
13292 }
13293 /* nothing matched */
13294 Py_RETURN_FALSE;
13295 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013296 if (!PyUnicode_Check(subobj)) {
13297 PyErr_Format(PyExc_TypeError,
13298 "startswith first arg must be str or "
13299 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013300 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013301 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013302 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013303 if (result == -1)
13304 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013305 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013306}
13307
13308
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013309PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013310 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013311\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013312Return True if S ends with the specified suffix, False otherwise.\n\
13313With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013314With optional end, stop comparing S at that position.\n\
13315suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013316
13317static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013318unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013319 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013320{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013321 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013322 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013323 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013324 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013325 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013326
Jesus Ceaac451502011-04-20 17:09:23 +020013327 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013328 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013329 if (PyTuple_Check(subobj)) {
13330 Py_ssize_t i;
13331 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013332 substring = PyTuple_GET_ITEM(subobj, i);
13333 if (!PyUnicode_Check(substring)) {
13334 PyErr_Format(PyExc_TypeError,
13335 "tuple for endswith must only contain str, "
13336 "not %.100s",
13337 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013338 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013339 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013340 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013341 if (result == -1)
13342 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013343 if (result) {
13344 Py_RETURN_TRUE;
13345 }
13346 }
13347 Py_RETURN_FALSE;
13348 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013349 if (!PyUnicode_Check(subobj)) {
13350 PyErr_Format(PyExc_TypeError,
13351 "endswith first arg must be str or "
13352 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013353 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013354 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013355 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013356 if (result == -1)
13357 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013358 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013359}
13360
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013361static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013362_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013363{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013364 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13365 writer->data = PyUnicode_DATA(writer->buffer);
13366
13367 if (!writer->readonly) {
13368 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013369 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013370 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013371 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013372 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13373 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13374 writer->kind = PyUnicode_WCHAR_KIND;
13375 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13376
Victor Stinner8f674cc2013-04-17 23:02:17 +020013377 /* Copy-on-write mode: set buffer size to 0 so
13378 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13379 * next write. */
13380 writer->size = 0;
13381 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013382}
13383
Victor Stinnerd3f08822012-05-29 12:57:52 +020013384void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013385_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013386{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013387 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013388
13389 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013390 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013391
13392 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13393 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13394 writer->kind = PyUnicode_WCHAR_KIND;
13395 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013396}
13397
Victor Stinnerd3f08822012-05-29 12:57:52 +020013398int
13399_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13400 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013401{
13402 Py_ssize_t newlen;
13403 PyObject *newbuffer;
13404
Victor Stinner2740e462016-09-06 16:58:36 -070013405 assert(maxchar <= MAX_UNICODE);
13406
Victor Stinnerca9381e2015-09-22 00:58:32 +020013407 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013408 assert((maxchar > writer->maxchar && length >= 0)
13409 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013410
Victor Stinner202fdca2012-05-07 12:47:02 +020013411 if (length > PY_SSIZE_T_MAX - writer->pos) {
13412 PyErr_NoMemory();
13413 return -1;
13414 }
13415 newlen = writer->pos + length;
13416
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013417 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013418
Victor Stinnerd3f08822012-05-29 12:57:52 +020013419 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013420 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013421 if (writer->overallocate
13422 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13423 /* overallocate to limit the number of realloc() */
13424 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013425 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013426 if (newlen < writer->min_length)
13427 newlen = writer->min_length;
13428
Victor Stinnerd3f08822012-05-29 12:57:52 +020013429 writer->buffer = PyUnicode_New(newlen, maxchar);
13430 if (writer->buffer == NULL)
13431 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013432 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013433 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013434 if (writer->overallocate
13435 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13436 /* overallocate to limit the number of realloc() */
13437 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013438 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013439 if (newlen < writer->min_length)
13440 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013441
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013442 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013443 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013444 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013445 newbuffer = PyUnicode_New(newlen, maxchar);
13446 if (newbuffer == NULL)
13447 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013448 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13449 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013450 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013451 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013452 }
13453 else {
13454 newbuffer = resize_compact(writer->buffer, newlen);
13455 if (newbuffer == NULL)
13456 return -1;
13457 }
13458 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013459 }
13460 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013461 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013462 newbuffer = PyUnicode_New(writer->size, maxchar);
13463 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013464 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013465 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13466 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013467 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013468 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013469 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013470 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013471
13472#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013473}
13474
Victor Stinnerca9381e2015-09-22 00:58:32 +020013475int
13476_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13477 enum PyUnicode_Kind kind)
13478{
13479 Py_UCS4 maxchar;
13480
13481 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13482 assert(writer->kind < kind);
13483
13484 switch (kind)
13485 {
13486 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13487 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13488 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13489 default:
13490 assert(0 && "invalid kind");
13491 return -1;
13492 }
13493
13494 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13495}
13496
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013497static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013498_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013499{
Victor Stinner2740e462016-09-06 16:58:36 -070013500 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013501 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13502 return -1;
13503 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13504 writer->pos++;
13505 return 0;
13506}
13507
13508int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013509_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13510{
13511 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13512}
13513
13514int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013515_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13516{
13517 Py_UCS4 maxchar;
13518 Py_ssize_t len;
13519
13520 if (PyUnicode_READY(str) == -1)
13521 return -1;
13522 len = PyUnicode_GET_LENGTH(str);
13523 if (len == 0)
13524 return 0;
13525 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13526 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013527 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013528 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013529 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013530 Py_INCREF(str);
13531 writer->buffer = str;
13532 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013533 writer->pos += len;
13534 return 0;
13535 }
13536 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13537 return -1;
13538 }
13539 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13540 str, 0, len);
13541 writer->pos += len;
13542 return 0;
13543}
13544
Victor Stinnere215d962012-10-06 23:03:36 +020013545int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013546_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13547 Py_ssize_t start, Py_ssize_t end)
13548{
13549 Py_UCS4 maxchar;
13550 Py_ssize_t len;
13551
13552 if (PyUnicode_READY(str) == -1)
13553 return -1;
13554
13555 assert(0 <= start);
13556 assert(end <= PyUnicode_GET_LENGTH(str));
13557 assert(start <= end);
13558
13559 if (end == 0)
13560 return 0;
13561
13562 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13563 return _PyUnicodeWriter_WriteStr(writer, str);
13564
13565 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13566 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13567 else
13568 maxchar = writer->maxchar;
13569 len = end - start;
13570
13571 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13572 return -1;
13573
13574 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13575 str, start, len);
13576 writer->pos += len;
13577 return 0;
13578}
13579
13580int
Victor Stinner4a587072013-11-19 12:54:53 +010013581_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13582 const char *ascii, Py_ssize_t len)
13583{
13584 if (len == -1)
13585 len = strlen(ascii);
13586
13587 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13588
13589 if (writer->buffer == NULL && !writer->overallocate) {
13590 PyObject *str;
13591
13592 str = _PyUnicode_FromASCII(ascii, len);
13593 if (str == NULL)
13594 return -1;
13595
13596 writer->readonly = 1;
13597 writer->buffer = str;
13598 _PyUnicodeWriter_Update(writer);
13599 writer->pos += len;
13600 return 0;
13601 }
13602
13603 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13604 return -1;
13605
13606 switch (writer->kind)
13607 {
13608 case PyUnicode_1BYTE_KIND:
13609 {
13610 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13611 Py_UCS1 *data = writer->data;
13612
Christian Heimesf051e432016-09-13 20:22:02 +020013613 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013614 break;
13615 }
13616 case PyUnicode_2BYTE_KIND:
13617 {
13618 _PyUnicode_CONVERT_BYTES(
13619 Py_UCS1, Py_UCS2,
13620 ascii, ascii + len,
13621 (Py_UCS2 *)writer->data + writer->pos);
13622 break;
13623 }
13624 case PyUnicode_4BYTE_KIND:
13625 {
13626 _PyUnicode_CONVERT_BYTES(
13627 Py_UCS1, Py_UCS4,
13628 ascii, ascii + len,
13629 (Py_UCS4 *)writer->data + writer->pos);
13630 break;
13631 }
13632 default:
13633 assert(0);
13634 }
13635
13636 writer->pos += len;
13637 return 0;
13638}
13639
13640int
13641_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13642 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013643{
13644 Py_UCS4 maxchar;
13645
13646 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13647 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13648 return -1;
13649 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13650 writer->pos += len;
13651 return 0;
13652}
13653
Victor Stinnerd3f08822012-05-29 12:57:52 +020013654PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013655_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013656{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013657 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013658
Victor Stinnerd3f08822012-05-29 12:57:52 +020013659 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013660 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013661 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013662 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013663
13664 str = writer->buffer;
13665 writer->buffer = NULL;
13666
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013667 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013668 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13669 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013670 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013671
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013672 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13673 PyObject *str2;
13674 str2 = resize_compact(str, writer->pos);
13675 if (str2 == NULL) {
13676 Py_DECREF(str);
13677 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013678 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013679 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013680 }
13681
Victor Stinner15a0bd32013-07-08 22:29:55 +020013682 assert(_PyUnicode_CheckConsistency(str, 1));
13683 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013684}
13685
Victor Stinnerd3f08822012-05-29 12:57:52 +020013686void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013687_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013688{
13689 Py_CLEAR(writer->buffer);
13690}
13691
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013692#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013693
13694PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013695 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013696\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013697Return a formatted version of S, using substitutions from args and kwargs.\n\
13698The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013699
Eric Smith27bbca62010-11-04 17:06:58 +000013700PyDoc_STRVAR(format_map__doc__,
13701 "S.format_map(mapping) -> str\n\
13702\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013703Return a formatted version of S, using substitutions from mapping.\n\
13704The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013705
Eric Smith4a7d76d2008-05-30 18:10:19 +000013706static PyObject *
13707unicode__format__(PyObject* self, PyObject* args)
13708{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013709 PyObject *format_spec;
13710 _PyUnicodeWriter writer;
13711 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013712
13713 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13714 return NULL;
13715
Victor Stinnerd3f08822012-05-29 12:57:52 +020013716 if (PyUnicode_READY(self) == -1)
13717 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013718 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013719 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13720 self, format_spec, 0,
13721 PyUnicode_GET_LENGTH(format_spec));
13722 if (ret == -1) {
13723 _PyUnicodeWriter_Dealloc(&writer);
13724 return NULL;
13725 }
13726 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013727}
13728
Eric Smith8c663262007-08-25 02:26:07 +000013729PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013730 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013731\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013732Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013733
13734static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013735unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013736{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013737 Py_ssize_t size;
13738
13739 /* If it's a compact object, account for base structure +
13740 character data. */
13741 if (PyUnicode_IS_COMPACT_ASCII(v))
13742 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13743 else if (PyUnicode_IS_COMPACT(v))
13744 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013745 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013746 else {
13747 /* If it is a two-block object, account for base object, and
13748 for character block if present. */
13749 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013750 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013751 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013752 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013753 }
13754 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013755 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013756 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013757 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013758 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013759 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013760
13761 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013762}
13763
13764PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013765 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013766
13767static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013768unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013769{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013770 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013771 if (!copy)
13772 return NULL;
13773 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013774}
13775
Guido van Rossumd57fd912000-03-10 22:53:23 +000013776static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013777 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013778 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013779 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13780 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013781 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13782 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013783 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013784 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13785 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13786 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013787 {"expandtabs", (PyCFunction) unicode_expandtabs,
13788 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013789 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013790 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013791 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13792 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13793 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013794 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013795 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13796 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13797 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013798 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013799 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013800 {"splitlines", (PyCFunction) unicode_splitlines,
13801 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013802 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013803 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13804 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13805 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13806 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13807 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13808 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13809 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13810 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13811 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13812 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13813 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13814 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13815 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13816 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013817 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013818 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013819 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013820 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013821 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013822 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013823 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013824 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013825#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013826 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013827 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013828#endif
13829
Benjamin Peterson14339b62009-01-31 16:36:08 +000013830 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013831 {NULL, NULL}
13832};
13833
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013834static PyObject *
13835unicode_mod(PyObject *v, PyObject *w)
13836{
Brian Curtindfc80e32011-08-10 20:28:54 -050013837 if (!PyUnicode_Check(v))
13838 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013839 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013840}
13841
13842static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013843 0, /*nb_add*/
13844 0, /*nb_subtract*/
13845 0, /*nb_multiply*/
13846 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013847};
13848
Guido van Rossumd57fd912000-03-10 22:53:23 +000013849static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013850 (lenfunc) unicode_length, /* sq_length */
13851 PyUnicode_Concat, /* sq_concat */
13852 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13853 (ssizeargfunc) unicode_getitem, /* sq_item */
13854 0, /* sq_slice */
13855 0, /* sq_ass_item */
13856 0, /* sq_ass_slice */
13857 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013858};
13859
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013860static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013861unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013862{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013863 if (PyUnicode_READY(self) == -1)
13864 return NULL;
13865
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013866 if (PyIndex_Check(item)) {
13867 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013868 if (i == -1 && PyErr_Occurred())
13869 return NULL;
13870 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013871 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013872 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013873 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013874 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013875 PyObject *result;
13876 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013877 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013878 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013880 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013881 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013882 return NULL;
13883 }
13884
13885 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013886 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013887 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013888 slicelength == PyUnicode_GET_LENGTH(self)) {
13889 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013890 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013891 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013892 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013893 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013894 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013895 src_kind = PyUnicode_KIND(self);
13896 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013897 if (!PyUnicode_IS_ASCII(self)) {
13898 kind_limit = kind_maxchar_limit(src_kind);
13899 max_char = 0;
13900 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13901 ch = PyUnicode_READ(src_kind, src_data, cur);
13902 if (ch > max_char) {
13903 max_char = ch;
13904 if (max_char >= kind_limit)
13905 break;
13906 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013907 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013908 }
Victor Stinner55c99112011-10-13 01:17:06 +020013909 else
13910 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013911 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013912 if (result == NULL)
13913 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013914 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013915 dest_data = PyUnicode_DATA(result);
13916
13917 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013918 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13919 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013920 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013921 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013922 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013923 } else {
13924 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13925 return NULL;
13926 }
13927}
13928
13929static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013930 (lenfunc)unicode_length, /* mp_length */
13931 (binaryfunc)unicode_subscript, /* mp_subscript */
13932 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013933};
13934
Guido van Rossumd57fd912000-03-10 22:53:23 +000013935
Guido van Rossumd57fd912000-03-10 22:53:23 +000013936/* Helpers for PyUnicode_Format() */
13937
Victor Stinnera47082312012-10-04 02:19:54 +020013938struct unicode_formatter_t {
13939 PyObject *args;
13940 int args_owned;
13941 Py_ssize_t arglen, argidx;
13942 PyObject *dict;
13943
13944 enum PyUnicode_Kind fmtkind;
13945 Py_ssize_t fmtcnt, fmtpos;
13946 void *fmtdata;
13947 PyObject *fmtstr;
13948
13949 _PyUnicodeWriter writer;
13950};
13951
13952struct unicode_format_arg_t {
13953 Py_UCS4 ch;
13954 int flags;
13955 Py_ssize_t width;
13956 int prec;
13957 int sign;
13958};
13959
Guido van Rossumd57fd912000-03-10 22:53:23 +000013960static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013961unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013962{
Victor Stinnera47082312012-10-04 02:19:54 +020013963 Py_ssize_t argidx = ctx->argidx;
13964
13965 if (argidx < ctx->arglen) {
13966 ctx->argidx++;
13967 if (ctx->arglen < 0)
13968 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013969 else
Victor Stinnera47082312012-10-04 02:19:54 +020013970 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013971 }
13972 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013973 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013974 return NULL;
13975}
13976
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013977/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013978
Victor Stinnera47082312012-10-04 02:19:54 +020013979/* Format a float into the writer if the writer is not NULL, or into *p_output
13980 otherwise.
13981
13982 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013983static int
Victor Stinnera47082312012-10-04 02:19:54 +020013984formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13985 PyObject **p_output,
13986 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013987{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013988 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013989 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013990 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013991 int prec;
13992 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013993
Guido van Rossumd57fd912000-03-10 22:53:23 +000013994 x = PyFloat_AsDouble(v);
13995 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013996 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013997
Victor Stinnera47082312012-10-04 02:19:54 +020013998 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013999 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014000 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014001
Victor Stinnera47082312012-10-04 02:19:54 +020014002 if (arg->flags & F_ALT)
14003 dtoa_flags = Py_DTSF_ALT;
14004 else
14005 dtoa_flags = 0;
14006 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014007 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014008 return -1;
14009 len = strlen(p);
14010 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014011 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014012 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014013 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014014 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014015 }
14016 else
14017 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014018 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014019 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014020}
14021
Victor Stinnerd0880d52012-04-27 23:40:13 +020014022/* formatlong() emulates the format codes d, u, o, x and X, and
14023 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14024 * Python's regular ints.
14025 * Return value: a new PyUnicodeObject*, or NULL if error.
14026 * The output string is of the form
14027 * "-"? ("0x" | "0X")? digit+
14028 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14029 * set in flags. The case of hex digits will be correct,
14030 * There will be at least prec digits, zero-filled on the left if
14031 * necessary to get that many.
14032 * val object to be converted
14033 * flags bitmask of format flags; only F_ALT is looked at
14034 * prec minimum number of digits; 0-fill on left if needed
14035 * type a character in [duoxX]; u acts the same as d
14036 *
14037 * CAUTION: o, x and X conversions on regular ints can never
14038 * produce a '-' sign, but can for Python's unbounded ints.
14039 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014040PyObject *
14041_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014042{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014043 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014045 Py_ssize_t i;
14046 int sign; /* 1 if '-', else 0 */
14047 int len; /* number of characters */
14048 Py_ssize_t llen;
14049 int numdigits; /* len == numnondigits + numdigits */
14050 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014051
Victor Stinnerd0880d52012-04-27 23:40:13 +020014052 /* Avoid exceeding SSIZE_T_MAX */
14053 if (prec > INT_MAX-3) {
14054 PyErr_SetString(PyExc_OverflowError,
14055 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014056 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014057 }
14058
14059 assert(PyLong_Check(val));
14060
14061 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014062 default:
14063 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014064 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014065 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014066 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014067 /* int and int subclasses should print numerically when a numeric */
14068 /* format code is used (see issue18780) */
14069 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014070 break;
14071 case 'o':
14072 numnondigits = 2;
14073 result = PyNumber_ToBase(val, 8);
14074 break;
14075 case 'x':
14076 case 'X':
14077 numnondigits = 2;
14078 result = PyNumber_ToBase(val, 16);
14079 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014080 }
14081 if (!result)
14082 return NULL;
14083
14084 assert(unicode_modifiable(result));
14085 assert(PyUnicode_IS_READY(result));
14086 assert(PyUnicode_IS_ASCII(result));
14087
14088 /* To modify the string in-place, there can only be one reference. */
14089 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014090 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014091 PyErr_BadInternalCall();
14092 return NULL;
14093 }
14094 buf = PyUnicode_DATA(result);
14095 llen = PyUnicode_GET_LENGTH(result);
14096 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014097 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014098 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014099 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014100 return NULL;
14101 }
14102 len = (int)llen;
14103 sign = buf[0] == '-';
14104 numnondigits += sign;
14105 numdigits = len - numnondigits;
14106 assert(numdigits > 0);
14107
14108 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014109 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014110 (type == 'o' || type == 'x' || type == 'X'))) {
14111 assert(buf[sign] == '0');
14112 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14113 buf[sign+1] == 'o');
14114 numnondigits -= 2;
14115 buf += 2;
14116 len -= 2;
14117 if (sign)
14118 buf[0] = '-';
14119 assert(len == numnondigits + numdigits);
14120 assert(numdigits > 0);
14121 }
14122
14123 /* Fill with leading zeroes to meet minimum width. */
14124 if (prec > numdigits) {
14125 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14126 numnondigits + prec);
14127 char *b1;
14128 if (!r1) {
14129 Py_DECREF(result);
14130 return NULL;
14131 }
14132 b1 = PyBytes_AS_STRING(r1);
14133 for (i = 0; i < numnondigits; ++i)
14134 *b1++ = *buf++;
14135 for (i = 0; i < prec - numdigits; i++)
14136 *b1++ = '0';
14137 for (i = 0; i < numdigits; i++)
14138 *b1++ = *buf++;
14139 *b1 = '\0';
14140 Py_DECREF(result);
14141 result = r1;
14142 buf = PyBytes_AS_STRING(result);
14143 len = numnondigits + prec;
14144 }
14145
14146 /* Fix up case for hex conversions. */
14147 if (type == 'X') {
14148 /* Need to convert all lower case letters to upper case.
14149 and need to convert 0x to 0X (and -0x to -0X). */
14150 for (i = 0; i < len; i++)
14151 if (buf[i] >= 'a' && buf[i] <= 'x')
14152 buf[i] -= 'a'-'A';
14153 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014154 if (!PyUnicode_Check(result)
14155 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014156 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014157 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014158 Py_DECREF(result);
14159 result = unicode;
14160 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014161 else if (len != PyUnicode_GET_LENGTH(result)) {
14162 if (PyUnicode_Resize(&result, len) < 0)
14163 Py_CLEAR(result);
14164 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014165 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014166}
14167
Ethan Furmandf3ed242014-01-05 06:50:30 -080014168/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014169 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014170 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014171 * -1 and raise an exception on error */
14172static int
Victor Stinnera47082312012-10-04 02:19:54 +020014173mainformatlong(PyObject *v,
14174 struct unicode_format_arg_t *arg,
14175 PyObject **p_output,
14176 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014177{
14178 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014179 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014180
14181 if (!PyNumber_Check(v))
14182 goto wrongtype;
14183
Ethan Furman9ab74802014-03-21 06:38:46 -070014184 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014185 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014186 if (type == 'o' || type == 'x' || type == 'X') {
14187 iobj = PyNumber_Index(v);
14188 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014189 if (PyErr_ExceptionMatches(PyExc_TypeError))
14190 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014191 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014192 }
14193 }
14194 else {
14195 iobj = PyNumber_Long(v);
14196 if (iobj == NULL ) {
14197 if (PyErr_ExceptionMatches(PyExc_TypeError))
14198 goto wrongtype;
14199 return -1;
14200 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014201 }
14202 assert(PyLong_Check(iobj));
14203 }
14204 else {
14205 iobj = v;
14206 Py_INCREF(iobj);
14207 }
14208
14209 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014210 && arg->width == -1 && arg->prec == -1
14211 && !(arg->flags & (F_SIGN | F_BLANK))
14212 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014213 {
14214 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014215 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014216 int base;
14217
Victor Stinnera47082312012-10-04 02:19:54 +020014218 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014219 {
14220 default:
14221 assert(0 && "'type' not in [diuoxX]");
14222 case 'd':
14223 case 'i':
14224 case 'u':
14225 base = 10;
14226 break;
14227 case 'o':
14228 base = 8;
14229 break;
14230 case 'x':
14231 case 'X':
14232 base = 16;
14233 break;
14234 }
14235
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014236 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14237 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014238 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014239 }
14240 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014241 return 1;
14242 }
14243
Ethan Furmanb95b5612015-01-23 20:05:18 -080014244 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014245 Py_DECREF(iobj);
14246 if (res == NULL)
14247 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014248 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014249 return 0;
14250
14251wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014252 switch(type)
14253 {
14254 case 'o':
14255 case 'x':
14256 case 'X':
14257 PyErr_Format(PyExc_TypeError,
14258 "%%%c format: an integer is required, "
14259 "not %.200s",
14260 type, Py_TYPE(v)->tp_name);
14261 break;
14262 default:
14263 PyErr_Format(PyExc_TypeError,
14264 "%%%c format: a number is required, "
14265 "not %.200s",
14266 type, Py_TYPE(v)->tp_name);
14267 break;
14268 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014269 return -1;
14270}
14271
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014272static Py_UCS4
14273formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014274{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014275 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014276 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014277 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014278 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014279 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014280 goto onError;
14281 }
14282 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014283 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014284 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014285 /* make sure number is a type of integer */
14286 if (!PyLong_Check(v)) {
14287 iobj = PyNumber_Index(v);
14288 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014289 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014290 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014291 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014292 Py_DECREF(iobj);
14293 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014294 else {
14295 x = PyLong_AsLong(v);
14296 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014297 if (x == -1 && PyErr_Occurred())
14298 goto onError;
14299
Victor Stinner8faf8212011-12-08 22:14:11 +010014300 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014301 PyErr_SetString(PyExc_OverflowError,
14302 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014303 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014304 }
14305
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014306 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014307 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014308
Benjamin Peterson29060642009-01-31 22:14:21 +000014309 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014310 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014311 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014312 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014313}
14314
Victor Stinnera47082312012-10-04 02:19:54 +020014315/* Parse options of an argument: flags, width, precision.
14316 Handle also "%(name)" syntax.
14317
14318 Return 0 if the argument has been formatted into arg->str.
14319 Return 1 if the argument has been written into ctx->writer,
14320 Raise an exception and return -1 on error. */
14321static int
14322unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14323 struct unicode_format_arg_t *arg)
14324{
14325#define FORMAT_READ(ctx) \
14326 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14327
14328 PyObject *v;
14329
Victor Stinnera47082312012-10-04 02:19:54 +020014330 if (arg->ch == '(') {
14331 /* Get argument value from a dictionary. Example: "%(name)s". */
14332 Py_ssize_t keystart;
14333 Py_ssize_t keylen;
14334 PyObject *key;
14335 int pcount = 1;
14336
14337 if (ctx->dict == NULL) {
14338 PyErr_SetString(PyExc_TypeError,
14339 "format requires a mapping");
14340 return -1;
14341 }
14342 ++ctx->fmtpos;
14343 --ctx->fmtcnt;
14344 keystart = ctx->fmtpos;
14345 /* Skip over balanced parentheses */
14346 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14347 arg->ch = FORMAT_READ(ctx);
14348 if (arg->ch == ')')
14349 --pcount;
14350 else if (arg->ch == '(')
14351 ++pcount;
14352 ctx->fmtpos++;
14353 }
14354 keylen = ctx->fmtpos - keystart - 1;
14355 if (ctx->fmtcnt < 0 || pcount > 0) {
14356 PyErr_SetString(PyExc_ValueError,
14357 "incomplete format key");
14358 return -1;
14359 }
14360 key = PyUnicode_Substring(ctx->fmtstr,
14361 keystart, keystart + keylen);
14362 if (key == NULL)
14363 return -1;
14364 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014365 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014366 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014367 }
14368 ctx->args = PyObject_GetItem(ctx->dict, key);
14369 Py_DECREF(key);
14370 if (ctx->args == NULL)
14371 return -1;
14372 ctx->args_owned = 1;
14373 ctx->arglen = -1;
14374 ctx->argidx = -2;
14375 }
14376
14377 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014378 while (--ctx->fmtcnt >= 0) {
14379 arg->ch = FORMAT_READ(ctx);
14380 ctx->fmtpos++;
14381 switch (arg->ch) {
14382 case '-': arg->flags |= F_LJUST; continue;
14383 case '+': arg->flags |= F_SIGN; continue;
14384 case ' ': arg->flags |= F_BLANK; continue;
14385 case '#': arg->flags |= F_ALT; continue;
14386 case '0': arg->flags |= F_ZERO; continue;
14387 }
14388 break;
14389 }
14390
14391 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014392 if (arg->ch == '*') {
14393 v = unicode_format_getnextarg(ctx);
14394 if (v == NULL)
14395 return -1;
14396 if (!PyLong_Check(v)) {
14397 PyErr_SetString(PyExc_TypeError,
14398 "* wants int");
14399 return -1;
14400 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014401 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014402 if (arg->width == -1 && PyErr_Occurred())
14403 return -1;
14404 if (arg->width < 0) {
14405 arg->flags |= F_LJUST;
14406 arg->width = -arg->width;
14407 }
14408 if (--ctx->fmtcnt >= 0) {
14409 arg->ch = FORMAT_READ(ctx);
14410 ctx->fmtpos++;
14411 }
14412 }
14413 else if (arg->ch >= '0' && arg->ch <= '9') {
14414 arg->width = arg->ch - '0';
14415 while (--ctx->fmtcnt >= 0) {
14416 arg->ch = FORMAT_READ(ctx);
14417 ctx->fmtpos++;
14418 if (arg->ch < '0' || arg->ch > '9')
14419 break;
14420 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14421 mixing signed and unsigned comparison. Since arg->ch is between
14422 '0' and '9', casting to int is safe. */
14423 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14424 PyErr_SetString(PyExc_ValueError,
14425 "width too big");
14426 return -1;
14427 }
14428 arg->width = arg->width*10 + (arg->ch - '0');
14429 }
14430 }
14431
14432 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014433 if (arg->ch == '.') {
14434 arg->prec = 0;
14435 if (--ctx->fmtcnt >= 0) {
14436 arg->ch = FORMAT_READ(ctx);
14437 ctx->fmtpos++;
14438 }
14439 if (arg->ch == '*') {
14440 v = unicode_format_getnextarg(ctx);
14441 if (v == NULL)
14442 return -1;
14443 if (!PyLong_Check(v)) {
14444 PyErr_SetString(PyExc_TypeError,
14445 "* wants int");
14446 return -1;
14447 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014448 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014449 if (arg->prec == -1 && PyErr_Occurred())
14450 return -1;
14451 if (arg->prec < 0)
14452 arg->prec = 0;
14453 if (--ctx->fmtcnt >= 0) {
14454 arg->ch = FORMAT_READ(ctx);
14455 ctx->fmtpos++;
14456 }
14457 }
14458 else if (arg->ch >= '0' && arg->ch <= '9') {
14459 arg->prec = arg->ch - '0';
14460 while (--ctx->fmtcnt >= 0) {
14461 arg->ch = FORMAT_READ(ctx);
14462 ctx->fmtpos++;
14463 if (arg->ch < '0' || arg->ch > '9')
14464 break;
14465 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14466 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014467 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014468 return -1;
14469 }
14470 arg->prec = arg->prec*10 + (arg->ch - '0');
14471 }
14472 }
14473 }
14474
14475 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14476 if (ctx->fmtcnt >= 0) {
14477 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14478 if (--ctx->fmtcnt >= 0) {
14479 arg->ch = FORMAT_READ(ctx);
14480 ctx->fmtpos++;
14481 }
14482 }
14483 }
14484 if (ctx->fmtcnt < 0) {
14485 PyErr_SetString(PyExc_ValueError,
14486 "incomplete format");
14487 return -1;
14488 }
14489 return 0;
14490
14491#undef FORMAT_READ
14492}
14493
14494/* Format one argument. Supported conversion specifiers:
14495
14496 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014497 - "i", "d", "u": int or float
14498 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014499 - "e", "E", "f", "F", "g", "G": float
14500 - "c": int or str (1 character)
14501
Victor Stinner8dbd4212012-12-04 09:30:24 +010014502 When possible, the output is written directly into the Unicode writer
14503 (ctx->writer). A string is created when padding is required.
14504
Victor Stinnera47082312012-10-04 02:19:54 +020014505 Return 0 if the argument has been formatted into *p_str,
14506 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014507 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014508static int
14509unicode_format_arg_format(struct unicode_formatter_t *ctx,
14510 struct unicode_format_arg_t *arg,
14511 PyObject **p_str)
14512{
14513 PyObject *v;
14514 _PyUnicodeWriter *writer = &ctx->writer;
14515
14516 if (ctx->fmtcnt == 0)
14517 ctx->writer.overallocate = 0;
14518
14519 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014520 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014521 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014522 return 1;
14523 }
14524
14525 v = unicode_format_getnextarg(ctx);
14526 if (v == NULL)
14527 return -1;
14528
Victor Stinnera47082312012-10-04 02:19:54 +020014529
14530 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014531 case 's':
14532 case 'r':
14533 case 'a':
14534 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14535 /* Fast path */
14536 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14537 return -1;
14538 return 1;
14539 }
14540
14541 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14542 *p_str = v;
14543 Py_INCREF(*p_str);
14544 }
14545 else {
14546 if (arg->ch == 's')
14547 *p_str = PyObject_Str(v);
14548 else if (arg->ch == 'r')
14549 *p_str = PyObject_Repr(v);
14550 else
14551 *p_str = PyObject_ASCII(v);
14552 }
14553 break;
14554
14555 case 'i':
14556 case 'd':
14557 case 'u':
14558 case 'o':
14559 case 'x':
14560 case 'X':
14561 {
14562 int ret = mainformatlong(v, arg, p_str, writer);
14563 if (ret != 0)
14564 return ret;
14565 arg->sign = 1;
14566 break;
14567 }
14568
14569 case 'e':
14570 case 'E':
14571 case 'f':
14572 case 'F':
14573 case 'g':
14574 case 'G':
14575 if (arg->width == -1 && arg->prec == -1
14576 && !(arg->flags & (F_SIGN | F_BLANK)))
14577 {
14578 /* Fast path */
14579 if (formatfloat(v, arg, NULL, writer) == -1)
14580 return -1;
14581 return 1;
14582 }
14583
14584 arg->sign = 1;
14585 if (formatfloat(v, arg, p_str, NULL) == -1)
14586 return -1;
14587 break;
14588
14589 case 'c':
14590 {
14591 Py_UCS4 ch = formatchar(v);
14592 if (ch == (Py_UCS4) -1)
14593 return -1;
14594 if (arg->width == -1 && arg->prec == -1) {
14595 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014596 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014597 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014598 return 1;
14599 }
14600 *p_str = PyUnicode_FromOrdinal(ch);
14601 break;
14602 }
14603
14604 default:
14605 PyErr_Format(PyExc_ValueError,
14606 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014607 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014608 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14609 (int)arg->ch,
14610 ctx->fmtpos - 1);
14611 return -1;
14612 }
14613 if (*p_str == NULL)
14614 return -1;
14615 assert (PyUnicode_Check(*p_str));
14616 return 0;
14617}
14618
14619static int
14620unicode_format_arg_output(struct unicode_formatter_t *ctx,
14621 struct unicode_format_arg_t *arg,
14622 PyObject *str)
14623{
14624 Py_ssize_t len;
14625 enum PyUnicode_Kind kind;
14626 void *pbuf;
14627 Py_ssize_t pindex;
14628 Py_UCS4 signchar;
14629 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014630 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014631 Py_ssize_t sublen;
14632 _PyUnicodeWriter *writer = &ctx->writer;
14633 Py_UCS4 fill;
14634
14635 fill = ' ';
14636 if (arg->sign && arg->flags & F_ZERO)
14637 fill = '0';
14638
14639 if (PyUnicode_READY(str) == -1)
14640 return -1;
14641
14642 len = PyUnicode_GET_LENGTH(str);
14643 if ((arg->width == -1 || arg->width <= len)
14644 && (arg->prec == -1 || arg->prec >= len)
14645 && !(arg->flags & (F_SIGN | F_BLANK)))
14646 {
14647 /* Fast path */
14648 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14649 return -1;
14650 return 0;
14651 }
14652
14653 /* Truncate the string for "s", "r" and "a" formats
14654 if the precision is set */
14655 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14656 if (arg->prec >= 0 && len > arg->prec)
14657 len = arg->prec;
14658 }
14659
14660 /* Adjust sign and width */
14661 kind = PyUnicode_KIND(str);
14662 pbuf = PyUnicode_DATA(str);
14663 pindex = 0;
14664 signchar = '\0';
14665 if (arg->sign) {
14666 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14667 if (ch == '-' || ch == '+') {
14668 signchar = ch;
14669 len--;
14670 pindex++;
14671 }
14672 else if (arg->flags & F_SIGN)
14673 signchar = '+';
14674 else if (arg->flags & F_BLANK)
14675 signchar = ' ';
14676 else
14677 arg->sign = 0;
14678 }
14679 if (arg->width < len)
14680 arg->width = len;
14681
14682 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014683 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014684 if (!(arg->flags & F_LJUST)) {
14685 if (arg->sign) {
14686 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014687 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014688 }
14689 else {
14690 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014691 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014692 }
14693 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014694 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14695 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014696 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014697 }
14698
Victor Stinnera47082312012-10-04 02:19:54 +020014699 buflen = arg->width;
14700 if (arg->sign && len == arg->width)
14701 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014702 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014703 return -1;
14704
14705 /* Write the sign if needed */
14706 if (arg->sign) {
14707 if (fill != ' ') {
14708 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14709 writer->pos += 1;
14710 }
14711 if (arg->width > len)
14712 arg->width--;
14713 }
14714
14715 /* Write the numeric prefix for "x", "X" and "o" formats
14716 if the alternate form is used.
14717 For example, write "0x" for the "%#x" format. */
14718 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14719 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14720 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14721 if (fill != ' ') {
14722 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14723 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14724 writer->pos += 2;
14725 pindex += 2;
14726 }
14727 arg->width -= 2;
14728 if (arg->width < 0)
14729 arg->width = 0;
14730 len -= 2;
14731 }
14732
14733 /* Pad left with the fill character if needed */
14734 if (arg->width > len && !(arg->flags & F_LJUST)) {
14735 sublen = arg->width - len;
14736 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14737 writer->pos += sublen;
14738 arg->width = len;
14739 }
14740
14741 /* If padding with spaces: write sign if needed and/or numeric prefix if
14742 the alternate form is used */
14743 if (fill == ' ') {
14744 if (arg->sign) {
14745 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14746 writer->pos += 1;
14747 }
14748 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14749 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14750 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14751 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14752 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14753 writer->pos += 2;
14754 pindex += 2;
14755 }
14756 }
14757
14758 /* Write characters */
14759 if (len) {
14760 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14761 str, pindex, len);
14762 writer->pos += len;
14763 }
14764
14765 /* Pad right with the fill character if needed */
14766 if (arg->width > len) {
14767 sublen = arg->width - len;
14768 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14769 writer->pos += sublen;
14770 }
14771 return 0;
14772}
14773
14774/* Helper of PyUnicode_Format(): format one arg.
14775 Return 0 on success, raise an exception and return -1 on error. */
14776static int
14777unicode_format_arg(struct unicode_formatter_t *ctx)
14778{
14779 struct unicode_format_arg_t arg;
14780 PyObject *str;
14781 int ret;
14782
Victor Stinner8dbd4212012-12-04 09:30:24 +010014783 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14784 arg.flags = 0;
14785 arg.width = -1;
14786 arg.prec = -1;
14787 arg.sign = 0;
14788 str = NULL;
14789
Victor Stinnera47082312012-10-04 02:19:54 +020014790 ret = unicode_format_arg_parse(ctx, &arg);
14791 if (ret == -1)
14792 return -1;
14793
14794 ret = unicode_format_arg_format(ctx, &arg, &str);
14795 if (ret == -1)
14796 return -1;
14797
14798 if (ret != 1) {
14799 ret = unicode_format_arg_output(ctx, &arg, str);
14800 Py_DECREF(str);
14801 if (ret == -1)
14802 return -1;
14803 }
14804
14805 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14806 PyErr_SetString(PyExc_TypeError,
14807 "not all arguments converted during string formatting");
14808 return -1;
14809 }
14810 return 0;
14811}
14812
Alexander Belopolsky40018472011-02-26 01:02:56 +000014813PyObject *
14814PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014815{
Victor Stinnera47082312012-10-04 02:19:54 +020014816 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014817
Guido van Rossumd57fd912000-03-10 22:53:23 +000014818 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014819 PyErr_BadInternalCall();
14820 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014821 }
Victor Stinnera47082312012-10-04 02:19:54 +020014822
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014823 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014824 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014825
14826 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014827 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14828 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14829 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14830 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014831
Victor Stinner8f674cc2013-04-17 23:02:17 +020014832 _PyUnicodeWriter_Init(&ctx.writer);
14833 ctx.writer.min_length = ctx.fmtcnt + 100;
14834 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014835
Guido van Rossumd57fd912000-03-10 22:53:23 +000014836 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014837 ctx.arglen = PyTuple_Size(args);
14838 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014839 }
14840 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014841 ctx.arglen = -1;
14842 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014843 }
Victor Stinnera47082312012-10-04 02:19:54 +020014844 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014845 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014846 ctx.dict = args;
14847 else
14848 ctx.dict = NULL;
14849 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014850
Victor Stinnera47082312012-10-04 02:19:54 +020014851 while (--ctx.fmtcnt >= 0) {
14852 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014853 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014854
14855 nonfmtpos = ctx.fmtpos++;
14856 while (ctx.fmtcnt >= 0 &&
14857 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14858 ctx.fmtpos++;
14859 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014860 }
Victor Stinnera47082312012-10-04 02:19:54 +020014861 if (ctx.fmtcnt < 0) {
14862 ctx.fmtpos--;
14863 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014864 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014865
Victor Stinnercfc4c132013-04-03 01:48:39 +020014866 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14867 nonfmtpos, ctx.fmtpos) < 0)
14868 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014869 }
14870 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014871 ctx.fmtpos++;
14872 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014873 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014874 }
14875 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014876
Victor Stinnera47082312012-10-04 02:19:54 +020014877 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014878 PyErr_SetString(PyExc_TypeError,
14879 "not all arguments converted during string formatting");
14880 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014881 }
14882
Victor Stinnera47082312012-10-04 02:19:54 +020014883 if (ctx.args_owned) {
14884 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014885 }
Victor Stinnera47082312012-10-04 02:19:54 +020014886 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014887
Benjamin Peterson29060642009-01-31 22:14:21 +000014888 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014889 _PyUnicodeWriter_Dealloc(&ctx.writer);
14890 if (ctx.args_owned) {
14891 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014892 }
14893 return NULL;
14894}
14895
Jeremy Hylton938ace62002-07-17 16:30:39 +000014896static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014897unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14898
Tim Peters6d6c1a32001-08-02 04:15:00 +000014899static PyObject *
14900unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14901{
Benjamin Peterson29060642009-01-31 22:14:21 +000014902 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014903 static char *kwlist[] = {"object", "encoding", "errors", 0};
14904 char *encoding = NULL;
14905 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014906
Benjamin Peterson14339b62009-01-31 16:36:08 +000014907 if (type != &PyUnicode_Type)
14908 return unicode_subtype_new(type, args, kwds);
14909 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014910 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014911 return NULL;
14912 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014913 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014914 if (encoding == NULL && errors == NULL)
14915 return PyObject_Str(x);
14916 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014917 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014918}
14919
Guido van Rossume023fe02001-08-30 03:12:59 +000014920static PyObject *
14921unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14922{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014923 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014924 Py_ssize_t length, char_size;
14925 int share_wstr, share_utf8;
14926 unsigned int kind;
14927 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014928
Benjamin Peterson14339b62009-01-31 16:36:08 +000014929 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014930
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014931 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014932 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014933 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014934 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014935 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014936 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014937 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014938 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014939
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014940 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014941 if (self == NULL) {
14942 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014943 return NULL;
14944 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014945 kind = PyUnicode_KIND(unicode);
14946 length = PyUnicode_GET_LENGTH(unicode);
14947
14948 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014949#ifdef Py_DEBUG
14950 _PyUnicode_HASH(self) = -1;
14951#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014952 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014953#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014954 _PyUnicode_STATE(self).interned = 0;
14955 _PyUnicode_STATE(self).kind = kind;
14956 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014957 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014958 _PyUnicode_STATE(self).ready = 1;
14959 _PyUnicode_WSTR(self) = NULL;
14960 _PyUnicode_UTF8_LENGTH(self) = 0;
14961 _PyUnicode_UTF8(self) = NULL;
14962 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014963 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014964
14965 share_utf8 = 0;
14966 share_wstr = 0;
14967 if (kind == PyUnicode_1BYTE_KIND) {
14968 char_size = 1;
14969 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14970 share_utf8 = 1;
14971 }
14972 else if (kind == PyUnicode_2BYTE_KIND) {
14973 char_size = 2;
14974 if (sizeof(wchar_t) == 2)
14975 share_wstr = 1;
14976 }
14977 else {
14978 assert(kind == PyUnicode_4BYTE_KIND);
14979 char_size = 4;
14980 if (sizeof(wchar_t) == 4)
14981 share_wstr = 1;
14982 }
14983
14984 /* Ensure we won't overflow the length. */
14985 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14986 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014987 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014988 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014989 data = PyObject_MALLOC((length + 1) * char_size);
14990 if (data == NULL) {
14991 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014992 goto onError;
14993 }
14994
Victor Stinnerc3c74152011-10-02 20:39:55 +020014995 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014996 if (share_utf8) {
14997 _PyUnicode_UTF8_LENGTH(self) = length;
14998 _PyUnicode_UTF8(self) = data;
14999 }
15000 if (share_wstr) {
15001 _PyUnicode_WSTR_LENGTH(self) = length;
15002 _PyUnicode_WSTR(self) = (wchar_t *)data;
15003 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015004
Christian Heimesf051e432016-09-13 20:22:02 +020015005 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015006 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015007 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015008#ifdef Py_DEBUG
15009 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15010#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015011 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015012 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015013
15014onError:
15015 Py_DECREF(unicode);
15016 Py_DECREF(self);
15017 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015018}
15019
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015020PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015021"str(object='') -> str\n\
15022str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015023\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015024Create a new string object from the given object. If encoding or\n\
15025errors is specified, then the object must expose a data buffer\n\
15026that will be decoded using the given encoding and error handler.\n\
15027Otherwise, returns the result of object.__str__() (if defined)\n\
15028or repr(object).\n\
15029encoding defaults to sys.getdefaultencoding().\n\
15030errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015031
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015032static PyObject *unicode_iter(PyObject *seq);
15033
Guido van Rossumd57fd912000-03-10 22:53:23 +000015034PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015035 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015036 "str", /* tp_name */
15037 sizeof(PyUnicodeObject), /* tp_size */
15038 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015039 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015040 (destructor)unicode_dealloc, /* tp_dealloc */
15041 0, /* tp_print */
15042 0, /* tp_getattr */
15043 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015044 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015045 unicode_repr, /* tp_repr */
15046 &unicode_as_number, /* tp_as_number */
15047 &unicode_as_sequence, /* tp_as_sequence */
15048 &unicode_as_mapping, /* tp_as_mapping */
15049 (hashfunc) unicode_hash, /* tp_hash*/
15050 0, /* tp_call*/
15051 (reprfunc) unicode_str, /* tp_str */
15052 PyObject_GenericGetAttr, /* tp_getattro */
15053 0, /* tp_setattro */
15054 0, /* tp_as_buffer */
15055 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015056 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015057 unicode_doc, /* tp_doc */
15058 0, /* tp_traverse */
15059 0, /* tp_clear */
15060 PyUnicode_RichCompare, /* tp_richcompare */
15061 0, /* tp_weaklistoffset */
15062 unicode_iter, /* tp_iter */
15063 0, /* tp_iternext */
15064 unicode_methods, /* tp_methods */
15065 0, /* tp_members */
15066 0, /* tp_getset */
15067 &PyBaseObject_Type, /* tp_base */
15068 0, /* tp_dict */
15069 0, /* tp_descr_get */
15070 0, /* tp_descr_set */
15071 0, /* tp_dictoffset */
15072 0, /* tp_init */
15073 0, /* tp_alloc */
15074 unicode_new, /* tp_new */
15075 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015076};
15077
15078/* Initialize the Unicode implementation */
15079
Victor Stinner3a50e702011-10-18 21:21:00 +020015080int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015081{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015082 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015083 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015084 0x000A, /* LINE FEED */
15085 0x000D, /* CARRIAGE RETURN */
15086 0x001C, /* FILE SEPARATOR */
15087 0x001D, /* GROUP SEPARATOR */
15088 0x001E, /* RECORD SEPARATOR */
15089 0x0085, /* NEXT LINE */
15090 0x2028, /* LINE SEPARATOR */
15091 0x2029, /* PARAGRAPH SEPARATOR */
15092 };
15093
Fred Drakee4315f52000-05-09 19:53:39 +000015094 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015095 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015096 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015097 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015098 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015099
Guido van Rossumcacfc072002-05-24 19:01:59 +000015100 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015101 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015102
15103 /* initialize the linebreak bloom filter */
15104 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015105 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015106 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015107
Christian Heimes26532f72013-07-20 14:57:16 +020015108 if (PyType_Ready(&EncodingMapType) < 0)
15109 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015110
Benjamin Petersonc4311282012-10-30 23:21:10 -040015111 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15112 Py_FatalError("Can't initialize field name iterator type");
15113
15114 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15115 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015116
Victor Stinner3a50e702011-10-18 21:21:00 +020015117 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015118}
15119
15120/* Finalize the Unicode implementation */
15121
Christian Heimesa156e092008-02-16 07:38:31 +000015122int
15123PyUnicode_ClearFreeList(void)
15124{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015125 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015126}
15127
Guido van Rossumd57fd912000-03-10 22:53:23 +000015128void
Thomas Wouters78890102000-07-22 19:25:51 +000015129_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015130{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015131 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015132
Serhiy Storchaka05997252013-01-26 12:14:02 +020015133 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015134
Serhiy Storchaka05997252013-01-26 12:14:02 +020015135 for (i = 0; i < 256; i++)
15136 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015137 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015138 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015139}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015140
Walter Dörwald16807132007-05-25 13:52:07 +000015141void
15142PyUnicode_InternInPlace(PyObject **p)
15143{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015144 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015145 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015146#ifdef Py_DEBUG
15147 assert(s != NULL);
15148 assert(_PyUnicode_CHECK(s));
15149#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015150 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015151 return;
15152#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015153 /* If it's a subclass, we don't really know what putting
15154 it in the interned dict might do. */
15155 if (!PyUnicode_CheckExact(s))
15156 return;
15157 if (PyUnicode_CHECK_INTERNED(s))
15158 return;
15159 if (interned == NULL) {
15160 interned = PyDict_New();
15161 if (interned == NULL) {
15162 PyErr_Clear(); /* Don't leave an exception */
15163 return;
15164 }
15165 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015166 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015167 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015168 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015169 if (t == NULL) {
15170 PyErr_Clear();
15171 return;
15172 }
15173 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015174 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015175 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015176 return;
15177 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015178 /* The two references in interned are not counted by refcnt.
15179 The deallocator will take care of this */
15180 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015181 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015182}
15183
15184void
15185PyUnicode_InternImmortal(PyObject **p)
15186{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015187 PyUnicode_InternInPlace(p);
15188 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015189 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015190 Py_INCREF(*p);
15191 }
Walter Dörwald16807132007-05-25 13:52:07 +000015192}
15193
15194PyObject *
15195PyUnicode_InternFromString(const char *cp)
15196{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015197 PyObject *s = PyUnicode_FromString(cp);
15198 if (s == NULL)
15199 return NULL;
15200 PyUnicode_InternInPlace(&s);
15201 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015202}
15203
Alexander Belopolsky40018472011-02-26 01:02:56 +000015204void
15205_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015206{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015207 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015208 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015209 Py_ssize_t i, n;
15210 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015211
Benjamin Peterson14339b62009-01-31 16:36:08 +000015212 if (interned == NULL || !PyDict_Check(interned))
15213 return;
15214 keys = PyDict_Keys(interned);
15215 if (keys == NULL || !PyList_Check(keys)) {
15216 PyErr_Clear();
15217 return;
15218 }
Walter Dörwald16807132007-05-25 13:52:07 +000015219
Benjamin Peterson14339b62009-01-31 16:36:08 +000015220 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15221 detector, interned unicode strings are not forcibly deallocated;
15222 rather, we give them their stolen references back, and then clear
15223 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015224
Benjamin Peterson14339b62009-01-31 16:36:08 +000015225 n = PyList_GET_SIZE(keys);
15226 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015227 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015228 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015229 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015230 if (PyUnicode_READY(s) == -1) {
15231 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015232 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015234 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015235 case SSTATE_NOT_INTERNED:
15236 /* XXX Shouldn't happen */
15237 break;
15238 case SSTATE_INTERNED_IMMORTAL:
15239 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015240 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015241 break;
15242 case SSTATE_INTERNED_MORTAL:
15243 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015244 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015245 break;
15246 default:
15247 Py_FatalError("Inconsistent interned string state.");
15248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015249 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015250 }
15251 fprintf(stderr, "total size of all interned strings: "
15252 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15253 "mortal/immortal\n", mortal_size, immortal_size);
15254 Py_DECREF(keys);
15255 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015256 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015257}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015258
15259
15260/********************* Unicode Iterator **************************/
15261
15262typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015263 PyObject_HEAD
15264 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015265 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015266} unicodeiterobject;
15267
15268static void
15269unicodeiter_dealloc(unicodeiterobject *it)
15270{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015271 _PyObject_GC_UNTRACK(it);
15272 Py_XDECREF(it->it_seq);
15273 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015274}
15275
15276static int
15277unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15278{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015279 Py_VISIT(it->it_seq);
15280 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015281}
15282
15283static PyObject *
15284unicodeiter_next(unicodeiterobject *it)
15285{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015286 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015287
Benjamin Peterson14339b62009-01-31 16:36:08 +000015288 assert(it != NULL);
15289 seq = it->it_seq;
15290 if (seq == NULL)
15291 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015292 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015294 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15295 int kind = PyUnicode_KIND(seq);
15296 void *data = PyUnicode_DATA(seq);
15297 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15298 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015299 if (item != NULL)
15300 ++it->it_index;
15301 return item;
15302 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015303
Benjamin Peterson14339b62009-01-31 16:36:08 +000015304 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015305 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015306 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015307}
15308
15309static PyObject *
15310unicodeiter_len(unicodeiterobject *it)
15311{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015312 Py_ssize_t len = 0;
15313 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015314 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015315 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015316}
15317
15318PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15319
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015320static PyObject *
15321unicodeiter_reduce(unicodeiterobject *it)
15322{
15323 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015324 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015325 it->it_seq, it->it_index);
15326 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015327 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015328 if (u == NULL)
15329 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015330 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015331 }
15332}
15333
15334PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15335
15336static PyObject *
15337unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15338{
15339 Py_ssize_t index = PyLong_AsSsize_t(state);
15340 if (index == -1 && PyErr_Occurred())
15341 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015342 if (it->it_seq != NULL) {
15343 if (index < 0)
15344 index = 0;
15345 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15346 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15347 it->it_index = index;
15348 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015349 Py_RETURN_NONE;
15350}
15351
15352PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15353
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015354static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015355 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015356 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015357 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15358 reduce_doc},
15359 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15360 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015361 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015362};
15363
15364PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015365 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15366 "str_iterator", /* tp_name */
15367 sizeof(unicodeiterobject), /* tp_basicsize */
15368 0, /* tp_itemsize */
15369 /* methods */
15370 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15371 0, /* tp_print */
15372 0, /* tp_getattr */
15373 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015374 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015375 0, /* tp_repr */
15376 0, /* tp_as_number */
15377 0, /* tp_as_sequence */
15378 0, /* tp_as_mapping */
15379 0, /* tp_hash */
15380 0, /* tp_call */
15381 0, /* tp_str */
15382 PyObject_GenericGetAttr, /* tp_getattro */
15383 0, /* tp_setattro */
15384 0, /* tp_as_buffer */
15385 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15386 0, /* tp_doc */
15387 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15388 0, /* tp_clear */
15389 0, /* tp_richcompare */
15390 0, /* tp_weaklistoffset */
15391 PyObject_SelfIter, /* tp_iter */
15392 (iternextfunc)unicodeiter_next, /* tp_iternext */
15393 unicodeiter_methods, /* tp_methods */
15394 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015395};
15396
15397static PyObject *
15398unicode_iter(PyObject *seq)
15399{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015400 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015401
Benjamin Peterson14339b62009-01-31 16:36:08 +000015402 if (!PyUnicode_Check(seq)) {
15403 PyErr_BadInternalCall();
15404 return NULL;
15405 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015406 if (PyUnicode_READY(seq) == -1)
15407 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015408 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15409 if (it == NULL)
15410 return NULL;
15411 it->it_index = 0;
15412 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015413 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015414 _PyObject_GC_TRACK(it);
15415 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015416}
15417
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015418
15419size_t
15420Py_UNICODE_strlen(const Py_UNICODE *u)
15421{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015422 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015423}
15424
15425Py_UNICODE*
15426Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15427{
15428 Py_UNICODE *u = s1;
15429 while ((*u++ = *s2++));
15430 return s1;
15431}
15432
15433Py_UNICODE*
15434Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15435{
15436 Py_UNICODE *u = s1;
15437 while ((*u++ = *s2++))
15438 if (n-- == 0)
15439 break;
15440 return s1;
15441}
15442
15443Py_UNICODE*
15444Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15445{
15446 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015447 u1 += wcslen(u1);
15448 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015449 return s1;
15450}
15451
15452int
15453Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15454{
15455 while (*s1 && *s2 && *s1 == *s2)
15456 s1++, s2++;
15457 if (*s1 && *s2)
15458 return (*s1 < *s2) ? -1 : +1;
15459 if (*s1)
15460 return 1;
15461 if (*s2)
15462 return -1;
15463 return 0;
15464}
15465
15466int
15467Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15468{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015469 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015470 for (; n != 0; n--) {
15471 u1 = *s1;
15472 u2 = *s2;
15473 if (u1 != u2)
15474 return (u1 < u2) ? -1 : +1;
15475 if (u1 == '\0')
15476 return 0;
15477 s1++;
15478 s2++;
15479 }
15480 return 0;
15481}
15482
15483Py_UNICODE*
15484Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15485{
15486 const Py_UNICODE *p;
15487 for (p = s; *p; p++)
15488 if (*p == c)
15489 return (Py_UNICODE*)p;
15490 return NULL;
15491}
15492
15493Py_UNICODE*
15494Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15495{
15496 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015497 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015498 while (p != s) {
15499 p--;
15500 if (*p == c)
15501 return (Py_UNICODE*)p;
15502 }
15503 return NULL;
15504}
Victor Stinner331ea922010-08-10 16:37:20 +000015505
Victor Stinner71133ff2010-09-01 23:43:53 +000015506Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015507PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015508{
Victor Stinner577db2c2011-10-11 22:12:48 +020015509 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015510 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015512 if (!PyUnicode_Check(unicode)) {
15513 PyErr_BadArgument();
15514 return NULL;
15515 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015516 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015517 if (u == NULL)
15518 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015519 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015520 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015521 PyErr_NoMemory();
15522 return NULL;
15523 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015524 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015525 size *= sizeof(Py_UNICODE);
15526 copy = PyMem_Malloc(size);
15527 if (copy == NULL) {
15528 PyErr_NoMemory();
15529 return NULL;
15530 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015531 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015532 return copy;
15533}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015534
Georg Brandl66c221e2010-10-14 07:04:07 +000015535/* A _string module, to export formatter_parser and formatter_field_name_split
15536 to the string.Formatter class implemented in Python. */
15537
15538static PyMethodDef _string_methods[] = {
15539 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15540 METH_O, PyDoc_STR("split the argument as a field name")},
15541 {"formatter_parser", (PyCFunction) formatter_parser,
15542 METH_O, PyDoc_STR("parse the argument as a format string")},
15543 {NULL, NULL}
15544};
15545
15546static struct PyModuleDef _string_module = {
15547 PyModuleDef_HEAD_INIT,
15548 "_string",
15549 PyDoc_STR("string helper module"),
15550 0,
15551 _string_methods,
15552 NULL,
15553 NULL,
15554 NULL,
15555 NULL
15556};
15557
15558PyMODINIT_FUNC
15559PyInit__string(void)
15560{
15561 return PyModule_Create(&_string_module);
15562}
15563
15564
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015565#ifdef __cplusplus
15566}
15567#endif