blob: e0c3bfecdd8372a5948d2148de0021c85b3090ee [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
Benjamin Petersonbac79492012-01-14 13:34:47 -05001032 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +01001033 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001034
1035 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1036 if (copy == NULL)
1037 return NULL;
1038
1039 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001040 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001041 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001042 }
1043 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001044 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001045
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001046 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001047 if (w == NULL)
1048 return NULL;
1049 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1050 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001051 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
1052 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001053 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001054 }
1055}
1056
Guido van Rossumd57fd912000-03-10 22:53:23 +00001057/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001058 Ux0000 terminated; some code (e.g. new_identifier)
1059 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001060
1061 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001062 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001063
1064*/
1065
Alexander Belopolsky40018472011-02-26 01:02:56 +00001066static PyUnicodeObject *
1067_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001068{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001069 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001071
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001073 if (length == 0 && unicode_empty != NULL) {
1074 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001075 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001076 }
1077
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001078 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001079 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001080 return (PyUnicodeObject *)PyErr_NoMemory();
1081 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 if (length < 0) {
1083 PyErr_SetString(PyExc_SystemError,
1084 "Negative size passed to _PyUnicode_New");
1085 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001086 }
1087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001088 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1089 if (unicode == NULL)
1090 return NULL;
1091 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001092
1093 _PyUnicode_WSTR_LENGTH(unicode) = length;
1094 _PyUnicode_HASH(unicode) = -1;
1095 _PyUnicode_STATE(unicode).interned = 0;
1096 _PyUnicode_STATE(unicode).kind = 0;
1097 _PyUnicode_STATE(unicode).compact = 0;
1098 _PyUnicode_STATE(unicode).ready = 0;
1099 _PyUnicode_STATE(unicode).ascii = 0;
1100 _PyUnicode_DATA_ANY(unicode) = NULL;
1101 _PyUnicode_LENGTH(unicode) = 0;
1102 _PyUnicode_UTF8(unicode) = NULL;
1103 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001105 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1106 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001107 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001108 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001109 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001111
Jeremy Hyltond8082792003-09-16 19:41:39 +00001112 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001113 * the caller fails before initializing str -- unicode_resize()
1114 * reads str[0], and the Keep-Alive optimization can keep memory
1115 * allocated for str alive across a call to unicode_dealloc(unicode).
1116 * We don't want unicode_resize to read uninitialized memory in
1117 * that case.
1118 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 _PyUnicode_WSTR(unicode)[0] = 0;
1120 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001121
Victor Stinner7931d9a2011-11-04 00:22:48 +01001122 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001123 return unicode;
1124}
1125
Victor Stinnerf42dc442011-10-02 23:33:16 +02001126static const char*
1127unicode_kind_name(PyObject *unicode)
1128{
Victor Stinner42dfd712011-10-03 14:41:45 +02001129 /* don't check consistency: unicode_kind_name() is called from
1130 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001131 if (!PyUnicode_IS_COMPACT(unicode))
1132 {
1133 if (!PyUnicode_IS_READY(unicode))
1134 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001135 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001136 {
1137 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001138 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001139 return "legacy ascii";
1140 else
1141 return "legacy latin1";
1142 case PyUnicode_2BYTE_KIND:
1143 return "legacy UCS2";
1144 case PyUnicode_4BYTE_KIND:
1145 return "legacy UCS4";
1146 default:
1147 return "<legacy invalid kind>";
1148 }
1149 }
1150 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001151 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001152 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001153 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001154 return "ascii";
1155 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001156 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001157 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001158 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001159 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001160 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001161 default:
1162 return "<invalid compact kind>";
1163 }
1164}
1165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001167/* Functions wrapping macros for use in debugger */
1168char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001169 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001170}
1171
1172void *_PyUnicode_compact_data(void *unicode) {
1173 return _PyUnicode_COMPACT_DATA(unicode);
1174}
1175void *_PyUnicode_data(void *unicode){
1176 printf("obj %p\n", unicode);
1177 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1178 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1179 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1180 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1181 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1182 return PyUnicode_DATA(unicode);
1183}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001184
1185void
1186_PyUnicode_Dump(PyObject *op)
1187{
1188 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001189 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1190 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1191 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001192
Victor Stinnera849a4b2011-10-03 12:12:11 +02001193 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001194 {
1195 if (ascii->state.ascii)
1196 data = (ascii + 1);
1197 else
1198 data = (compact + 1);
1199 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001200 else
1201 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001202 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1203 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001204
Victor Stinnera849a4b2011-10-03 12:12:11 +02001205 if (ascii->wstr == data)
1206 printf("shared ");
1207 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001208
Victor Stinnera3b334d2011-10-03 13:53:37 +02001209 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001210 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001211 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1212 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001213 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1214 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001215 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001216 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001217}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001218#endif
1219
1220PyObject *
1221PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1222{
1223 PyObject *obj;
1224 PyCompactUnicodeObject *unicode;
1225 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001226 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001227 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228 Py_ssize_t char_size;
1229 Py_ssize_t struct_size;
1230
1231 /* Optimization for empty strings */
1232 if (size == 0 && unicode_empty != NULL) {
1233 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001234 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001235 }
1236
Victor Stinner9e9d6892011-10-04 01:02:02 +02001237 is_ascii = 0;
1238 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001239 struct_size = sizeof(PyCompactUnicodeObject);
1240 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001241 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001242 char_size = 1;
1243 is_ascii = 1;
1244 struct_size = sizeof(PyASCIIObject);
1245 }
1246 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001247 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001248 char_size = 1;
1249 }
1250 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001251 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001252 char_size = 2;
1253 if (sizeof(wchar_t) == 2)
1254 is_sharing = 1;
1255 }
1256 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001257 if (maxchar > MAX_UNICODE) {
1258 PyErr_SetString(PyExc_SystemError,
1259 "invalid maximum character passed to PyUnicode_New");
1260 return NULL;
1261 }
Victor Stinner8f825062012-04-27 13:55:39 +02001262 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001263 char_size = 4;
1264 if (sizeof(wchar_t) == 4)
1265 is_sharing = 1;
1266 }
1267
1268 /* Ensure we won't overflow the size. */
1269 if (size < 0) {
1270 PyErr_SetString(PyExc_SystemError,
1271 "Negative size passed to PyUnicode_New");
1272 return NULL;
1273 }
1274 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1275 return PyErr_NoMemory();
1276
1277 /* Duplicated allocation code from _PyObject_New() instead of a call to
1278 * PyObject_New() so we are able to allocate space for the object and
1279 * it's data buffer.
1280 */
1281 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1282 if (obj == NULL)
1283 return PyErr_NoMemory();
1284 obj = PyObject_INIT(obj, &PyUnicode_Type);
1285 if (obj == NULL)
1286 return NULL;
1287
1288 unicode = (PyCompactUnicodeObject *)obj;
1289 if (is_ascii)
1290 data = ((PyASCIIObject*)obj) + 1;
1291 else
1292 data = unicode + 1;
1293 _PyUnicode_LENGTH(unicode) = size;
1294 _PyUnicode_HASH(unicode) = -1;
1295 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001296 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297 _PyUnicode_STATE(unicode).compact = 1;
1298 _PyUnicode_STATE(unicode).ready = 1;
1299 _PyUnicode_STATE(unicode).ascii = is_ascii;
1300 if (is_ascii) {
1301 ((char*)data)[size] = 0;
1302 _PyUnicode_WSTR(unicode) = NULL;
1303 }
Victor Stinner8f825062012-04-27 13:55:39 +02001304 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001305 ((char*)data)[size] = 0;
1306 _PyUnicode_WSTR(unicode) = NULL;
1307 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001308 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001309 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001310 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311 else {
1312 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001313 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001314 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001316 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 ((Py_UCS4*)data)[size] = 0;
1318 if (is_sharing) {
1319 _PyUnicode_WSTR_LENGTH(unicode) = size;
1320 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1321 }
1322 else {
1323 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1324 _PyUnicode_WSTR(unicode) = NULL;
1325 }
1326 }
Victor Stinner8f825062012-04-27 13:55:39 +02001327#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001328 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001329#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001330 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001331 return obj;
1332}
1333
1334#if SIZEOF_WCHAR_T == 2
1335/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1336 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001337 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338
1339 This function assumes that unicode can hold one more code point than wstr
1340 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001341static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001343 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344{
1345 const wchar_t *iter;
1346 Py_UCS4 *ucs4_out;
1347
Victor Stinner910337b2011-10-03 03:20:16 +02001348 assert(unicode != NULL);
1349 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1351 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1352
1353 for (iter = begin; iter < end; ) {
1354 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1355 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001356 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1357 && (iter+1) < end
1358 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001359 {
Victor Stinner551ac952011-11-29 22:58:13 +01001360 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001361 iter += 2;
1362 }
1363 else {
1364 *ucs4_out++ = *iter;
1365 iter++;
1366 }
1367 }
1368 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1369 _PyUnicode_GET_LENGTH(unicode)));
1370
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371}
1372#endif
1373
Victor Stinnercd9950f2011-10-02 00:34:53 +02001374static int
Victor Stinner488fa492011-12-12 00:01:39 +01001375unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001376{
Victor Stinner488fa492011-12-12 00:01:39 +01001377 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001378 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001379 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001380 return -1;
1381 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001382 return 0;
1383}
1384
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001385static int
1386_copy_characters(PyObject *to, Py_ssize_t to_start,
1387 PyObject *from, Py_ssize_t from_start,
1388 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001390 unsigned int from_kind, to_kind;
1391 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001392
Victor Stinneree4544c2012-05-09 22:24:08 +02001393 assert(0 <= how_many);
1394 assert(0 <= from_start);
1395 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001396 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001397 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001398 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399
Victor Stinnerd3f08822012-05-29 12:57:52 +02001400 assert(PyUnicode_Check(to));
1401 assert(PyUnicode_IS_READY(to));
1402 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1403
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001404 if (how_many == 0)
1405 return 0;
1406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001408 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001409 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001410 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411
Victor Stinnerf1852262012-06-16 16:38:26 +02001412#ifdef Py_DEBUG
1413 if (!check_maxchar
1414 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1415 {
1416 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1417 Py_UCS4 ch;
1418 Py_ssize_t i;
1419 for (i=0; i < how_many; i++) {
1420 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1421 assert(ch <= to_maxchar);
1422 }
1423 }
1424#endif
1425
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001426 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001427 if (check_maxchar
1428 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1429 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001430 /* Writing Latin-1 characters into an ASCII string requires to
1431 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001432 Py_UCS4 max_char;
1433 max_char = ucs1lib_find_max_char(from_data,
1434 (Py_UCS1*)from_data + how_many);
1435 if (max_char >= 128)
1436 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001437 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001438 Py_MEMCPY((char*)to_data + to_kind * to_start,
1439 (char*)from_data + from_kind * from_start,
1440 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001441 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001442 else if (from_kind == PyUnicode_1BYTE_KIND
1443 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001444 {
1445 _PyUnicode_CONVERT_BYTES(
1446 Py_UCS1, Py_UCS2,
1447 PyUnicode_1BYTE_DATA(from) + from_start,
1448 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1449 PyUnicode_2BYTE_DATA(to) + to_start
1450 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001451 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001452 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001453 && to_kind == PyUnicode_4BYTE_KIND)
1454 {
1455 _PyUnicode_CONVERT_BYTES(
1456 Py_UCS1, Py_UCS4,
1457 PyUnicode_1BYTE_DATA(from) + from_start,
1458 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1459 PyUnicode_4BYTE_DATA(to) + to_start
1460 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001461 }
1462 else if (from_kind == PyUnicode_2BYTE_KIND
1463 && to_kind == PyUnicode_4BYTE_KIND)
1464 {
1465 _PyUnicode_CONVERT_BYTES(
1466 Py_UCS2, Py_UCS4,
1467 PyUnicode_2BYTE_DATA(from) + from_start,
1468 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1469 PyUnicode_4BYTE_DATA(to) + to_start
1470 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001471 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001472 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001473 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1474
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001475 if (!check_maxchar) {
1476 if (from_kind == PyUnicode_2BYTE_KIND
1477 && to_kind == PyUnicode_1BYTE_KIND)
1478 {
1479 _PyUnicode_CONVERT_BYTES(
1480 Py_UCS2, Py_UCS1,
1481 PyUnicode_2BYTE_DATA(from) + from_start,
1482 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1483 PyUnicode_1BYTE_DATA(to) + to_start
1484 );
1485 }
1486 else if (from_kind == PyUnicode_4BYTE_KIND
1487 && to_kind == PyUnicode_1BYTE_KIND)
1488 {
1489 _PyUnicode_CONVERT_BYTES(
1490 Py_UCS4, Py_UCS1,
1491 PyUnicode_4BYTE_DATA(from) + from_start,
1492 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1493 PyUnicode_1BYTE_DATA(to) + to_start
1494 );
1495 }
1496 else if (from_kind == PyUnicode_4BYTE_KIND
1497 && to_kind == PyUnicode_2BYTE_KIND)
1498 {
1499 _PyUnicode_CONVERT_BYTES(
1500 Py_UCS4, Py_UCS2,
1501 PyUnicode_4BYTE_DATA(from) + from_start,
1502 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1503 PyUnicode_2BYTE_DATA(to) + to_start
1504 );
1505 }
1506 else {
1507 assert(0);
1508 return -1;
1509 }
1510 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001511 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001512 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001513 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001514 Py_ssize_t i;
1515
Victor Stinnera0702ab2011-09-29 14:14:38 +02001516 for (i=0; i < how_many; i++) {
1517 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001518 if (ch > to_maxchar)
1519 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001520 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1521 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001522 }
1523 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001524 return 0;
1525}
1526
Victor Stinnerd3f08822012-05-29 12:57:52 +02001527void
1528_PyUnicode_FastCopyCharacters(
1529 PyObject *to, Py_ssize_t to_start,
1530 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001531{
1532 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1533}
1534
1535Py_ssize_t
1536PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1537 PyObject *from, Py_ssize_t from_start,
1538 Py_ssize_t how_many)
1539{
1540 int err;
1541
1542 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1543 PyErr_BadInternalCall();
1544 return -1;
1545 }
1546
Benjamin Petersonbac79492012-01-14 13:34:47 -05001547 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001548 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001549 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001550 return -1;
1551
Victor Stinnerd3f08822012-05-29 12:57:52 +02001552 if (from_start < 0) {
1553 PyErr_SetString(PyExc_IndexError, "string index out of range");
1554 return -1;
1555 }
1556 if (to_start < 0) {
1557 PyErr_SetString(PyExc_IndexError, "string index out of range");
1558 return -1;
1559 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001560 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1561 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1562 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001563 "Cannot write %zi characters at %zi "
1564 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001565 how_many, to_start, PyUnicode_GET_LENGTH(to));
1566 return -1;
1567 }
1568
1569 if (how_many == 0)
1570 return 0;
1571
Victor Stinner488fa492011-12-12 00:01:39 +01001572 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001573 return -1;
1574
1575 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1576 if (err) {
1577 PyErr_Format(PyExc_SystemError,
1578 "Cannot copy %s characters "
1579 "into a string of %s characters",
1580 unicode_kind_name(from),
1581 unicode_kind_name(to));
1582 return -1;
1583 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001584 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001585}
1586
Victor Stinner17222162011-09-28 22:15:37 +02001587/* Find the maximum code point and count the number of surrogate pairs so a
1588 correct string length can be computed before converting a string to UCS4.
1589 This function counts single surrogates as a character and not as a pair.
1590
1591 Return 0 on success, or -1 on error. */
1592static int
1593find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1594 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001595{
1596 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001597 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598
Victor Stinnerc53be962011-10-02 21:33:54 +02001599 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600 *num_surrogates = 0;
1601 *maxchar = 0;
1602
1603 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001604#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001605 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1606 && (iter+1) < end
1607 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1608 {
1609 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1610 ++(*num_surrogates);
1611 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001612 }
1613 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001614#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001615 {
1616 ch = *iter;
1617 iter++;
1618 }
1619 if (ch > *maxchar) {
1620 *maxchar = ch;
1621 if (*maxchar > MAX_UNICODE) {
1622 PyErr_Format(PyExc_ValueError,
1623 "character U+%x is not in range [U+0000; U+10ffff]",
1624 ch);
1625 return -1;
1626 }
1627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001628 }
1629 return 0;
1630}
1631
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001632int
1633_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001634{
1635 wchar_t *end;
1636 Py_UCS4 maxchar = 0;
1637 Py_ssize_t num_surrogates;
1638#if SIZEOF_WCHAR_T == 2
1639 Py_ssize_t length_wo_surrogates;
1640#endif
1641
Georg Brandl7597add2011-10-05 16:36:47 +02001642 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001643 strings were created using _PyObject_New() and where no canonical
1644 representation (the str field) has been set yet aka strings
1645 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001646 assert(_PyUnicode_CHECK(unicode));
1647 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001648 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001649 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001650 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001651 /* Actually, it should neither be interned nor be anything else: */
1652 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001654 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001655 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001656 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658
1659 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001660 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1661 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001662 PyErr_NoMemory();
1663 return -1;
1664 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001665 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001666 _PyUnicode_WSTR(unicode), end,
1667 PyUnicode_1BYTE_DATA(unicode));
1668 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1669 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1670 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1671 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001672 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001673 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001674 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001675 }
1676 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001677 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001678 _PyUnicode_UTF8(unicode) = NULL;
1679 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001680 }
1681 PyObject_FREE(_PyUnicode_WSTR(unicode));
1682 _PyUnicode_WSTR(unicode) = NULL;
1683 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1684 }
1685 /* In this case we might have to convert down from 4-byte native
1686 wchar_t to 2-byte unicode. */
1687 else if (maxchar < 65536) {
1688 assert(num_surrogates == 0 &&
1689 "FindMaxCharAndNumSurrogatePairs() messed up");
1690
Victor Stinner506f5922011-09-28 22:34:18 +02001691#if SIZEOF_WCHAR_T == 2
1692 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001693 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001694 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1695 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1696 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001697 _PyUnicode_UTF8(unicode) = NULL;
1698 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001699#else
1700 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001701 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001702 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001703 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001704 PyErr_NoMemory();
1705 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706 }
Victor Stinner506f5922011-09-28 22:34:18 +02001707 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1708 _PyUnicode_WSTR(unicode), end,
1709 PyUnicode_2BYTE_DATA(unicode));
1710 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1711 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1712 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001713 _PyUnicode_UTF8(unicode) = NULL;
1714 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001715 PyObject_FREE(_PyUnicode_WSTR(unicode));
1716 _PyUnicode_WSTR(unicode) = NULL;
1717 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1718#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001719 }
1720 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1721 else {
1722#if SIZEOF_WCHAR_T == 2
1723 /* in case the native representation is 2-bytes, we need to allocate a
1724 new normalized 4-byte version. */
1725 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001726 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1727 PyErr_NoMemory();
1728 return -1;
1729 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001730 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1731 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001732 PyErr_NoMemory();
1733 return -1;
1734 }
1735 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1736 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001737 _PyUnicode_UTF8(unicode) = NULL;
1738 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001739 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1740 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001741 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001742 PyObject_FREE(_PyUnicode_WSTR(unicode));
1743 _PyUnicode_WSTR(unicode) = NULL;
1744 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1745#else
1746 assert(num_surrogates == 0);
1747
Victor Stinnerc3c74152011-10-02 20:39:55 +02001748 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001749 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001750 _PyUnicode_UTF8(unicode) = NULL;
1751 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1753#endif
1754 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1755 }
1756 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001757 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 return 0;
1759}
1760
Alexander Belopolsky40018472011-02-26 01:02:56 +00001761static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001762unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001763{
Walter Dörwald16807132007-05-25 13:52:07 +00001764 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001765 case SSTATE_NOT_INTERNED:
1766 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001767
Benjamin Peterson29060642009-01-31 22:14:21 +00001768 case SSTATE_INTERNED_MORTAL:
1769 /* revive dead object temporarily for DelItem */
1770 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001771 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001772 Py_FatalError(
1773 "deletion of interned string failed");
1774 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001775
Benjamin Peterson29060642009-01-31 22:14:21 +00001776 case SSTATE_INTERNED_IMMORTAL:
1777 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001778
Benjamin Peterson29060642009-01-31 22:14:21 +00001779 default:
1780 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001781 }
1782
Victor Stinner03490912011-10-03 23:45:12 +02001783 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001784 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001785 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001786 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001787 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1788 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001789
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001790 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001791}
1792
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001793#ifdef Py_DEBUG
1794static int
1795unicode_is_singleton(PyObject *unicode)
1796{
1797 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1798 if (unicode == unicode_empty)
1799 return 1;
1800 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1801 {
1802 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1803 if (ch < 256 && unicode_latin1[ch] == unicode)
1804 return 1;
1805 }
1806 return 0;
1807}
1808#endif
1809
Alexander Belopolsky40018472011-02-26 01:02:56 +00001810static int
Victor Stinner488fa492011-12-12 00:01:39 +01001811unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001812{
Victor Stinner488fa492011-12-12 00:01:39 +01001813 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001814 if (Py_REFCNT(unicode) != 1)
1815 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001816 if (_PyUnicode_HASH(unicode) != -1)
1817 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001818 if (PyUnicode_CHECK_INTERNED(unicode))
1819 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001820 if (!PyUnicode_CheckExact(unicode))
1821 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001822#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001823 /* singleton refcount is greater than 1 */
1824 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001825#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001826 return 1;
1827}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001828
Victor Stinnerfe226c02011-10-03 03:52:20 +02001829static int
1830unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1831{
1832 PyObject *unicode;
1833 Py_ssize_t old_length;
1834
1835 assert(p_unicode != NULL);
1836 unicode = *p_unicode;
1837
1838 assert(unicode != NULL);
1839 assert(PyUnicode_Check(unicode));
1840 assert(0 <= length);
1841
Victor Stinner910337b2011-10-03 03:20:16 +02001842 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001843 old_length = PyUnicode_WSTR_LENGTH(unicode);
1844 else
1845 old_length = PyUnicode_GET_LENGTH(unicode);
1846 if (old_length == length)
1847 return 0;
1848
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001849 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001850 _Py_INCREF_UNICODE_EMPTY();
1851 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001852 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001853 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001854 return 0;
1855 }
1856
Victor Stinner488fa492011-12-12 00:01:39 +01001857 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001858 PyObject *copy = resize_copy(unicode, length);
1859 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001860 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001861 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001862 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001863 }
1864
Victor Stinnerfe226c02011-10-03 03:52:20 +02001865 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001866 PyObject *new_unicode = resize_compact(unicode, length);
1867 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001868 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001869 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001870 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001871 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001872 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001873}
1874
Alexander Belopolsky40018472011-02-26 01:02:56 +00001875int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001876PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001877{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001878 PyObject *unicode;
1879 if (p_unicode == NULL) {
1880 PyErr_BadInternalCall();
1881 return -1;
1882 }
1883 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001884 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001885 {
1886 PyErr_BadInternalCall();
1887 return -1;
1888 }
1889 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001890}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001891
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001892/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001893
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001894 WARNING: The function doesn't copy the terminating null character and
1895 doesn't check the maximum character (may write a latin1 character in an
1896 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001897static void
1898unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1899 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001900{
1901 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1902 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001903 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001904
1905 switch (kind) {
1906 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001907 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001908#ifdef Py_DEBUG
1909 if (PyUnicode_IS_ASCII(unicode)) {
1910 Py_UCS4 maxchar = ucs1lib_find_max_char(
1911 (const Py_UCS1*)str,
1912 (const Py_UCS1*)str + len);
1913 assert(maxchar < 128);
1914 }
1915#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001916 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001917 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001918 }
1919 case PyUnicode_2BYTE_KIND: {
1920 Py_UCS2 *start = (Py_UCS2 *)data + index;
1921 Py_UCS2 *ucs2 = start;
1922 assert(index <= PyUnicode_GET_LENGTH(unicode));
1923
Victor Stinner184252a2012-06-16 02:57:41 +02001924 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001925 *ucs2 = (Py_UCS2)*str;
1926
1927 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001928 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001929 }
1930 default: {
1931 Py_UCS4 *start = (Py_UCS4 *)data + index;
1932 Py_UCS4 *ucs4 = start;
1933 assert(kind == PyUnicode_4BYTE_KIND);
1934 assert(index <= PyUnicode_GET_LENGTH(unicode));
1935
Victor Stinner184252a2012-06-16 02:57:41 +02001936 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001937 *ucs4 = (Py_UCS4)*str;
1938
1939 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001940 }
1941 }
1942}
1943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001944static PyObject*
1945get_latin1_char(unsigned char ch)
1946{
Victor Stinnera464fc12011-10-02 20:39:30 +02001947 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001949 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950 if (!unicode)
1951 return NULL;
1952 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001953 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 unicode_latin1[ch] = unicode;
1955 }
1956 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001957 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001958}
1959
Victor Stinner985a82a2014-01-03 12:53:47 +01001960static PyObject*
1961unicode_char(Py_UCS4 ch)
1962{
1963 PyObject *unicode;
1964
1965 assert(ch <= MAX_UNICODE);
1966
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001967 if (ch < 256)
1968 return get_latin1_char(ch);
1969
Victor Stinner985a82a2014-01-03 12:53:47 +01001970 unicode = PyUnicode_New(1, ch);
1971 if (unicode == NULL)
1972 return NULL;
1973 switch (PyUnicode_KIND(unicode)) {
1974 case PyUnicode_1BYTE_KIND:
1975 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1976 break;
1977 case PyUnicode_2BYTE_KIND:
1978 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1979 break;
1980 default:
1981 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{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001991 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992 Py_UCS4 maxchar = 0;
1993 Py_ssize_t num_surrogates;
1994
1995 if (u == NULL)
1996 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001997
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001998 /* If the Unicode data is known at construction time, we can apply
1999 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002001 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002002 if (size == 0)
2003 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002005 /* Single character Unicode objects in the Latin-1 range are
2006 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002007 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 return get_latin1_char((unsigned char)*u);
2009
2010 /* If not empty and not single character, copy the Unicode data
2011 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002012 if (find_maxchar_surrogates(u, u + size,
2013 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014 return NULL;
2015
Victor Stinner8faf8212011-12-08 22:14:11 +01002016 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002017 if (!unicode)
2018 return NULL;
2019
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002020 switch (PyUnicode_KIND(unicode)) {
2021 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002022 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002023 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2024 break;
2025 case PyUnicode_2BYTE_KIND:
2026#if Py_UNICODE_SIZE == 2
2027 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
2028#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002029 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002030 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2031#endif
2032 break;
2033 case PyUnicode_4BYTE_KIND:
2034#if SIZEOF_WCHAR_T == 2
2035 /* This is the only case which has to process surrogates, thus
2036 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002037 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002038#else
2039 assert(num_surrogates == 0);
2040 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
2041#endif
2042 break;
2043 default:
2044 assert(0 && "Impossible state");
2045 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002046
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002047 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002048}
2049
Alexander Belopolsky40018472011-02-26 01:02:56 +00002050PyObject *
2051PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002052{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002053 if (size < 0) {
2054 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002055 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002056 return NULL;
2057 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002058 if (u != NULL)
2059 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2060 else
2061 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002062}
2063
Alexander Belopolsky40018472011-02-26 01:02:56 +00002064PyObject *
2065PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002066{
2067 size_t size = strlen(u);
2068 if (size > PY_SSIZE_T_MAX) {
2069 PyErr_SetString(PyExc_OverflowError, "input too long");
2070 return NULL;
2071 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002072 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002073}
2074
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002075PyObject *
2076_PyUnicode_FromId(_Py_Identifier *id)
2077{
2078 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002079 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2080 strlen(id->string),
2081 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002082 if (!id->object)
2083 return NULL;
2084 PyUnicode_InternInPlace(&id->object);
2085 assert(!id->next);
2086 id->next = static_strings;
2087 static_strings = id;
2088 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002089 return id->object;
2090}
2091
2092void
2093_PyUnicode_ClearStaticStrings()
2094{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002095 _Py_Identifier *tmp, *s = static_strings;
2096 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002097 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002098 tmp = s->next;
2099 s->next = NULL;
2100 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002101 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002102 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002103}
2104
Benjamin Peterson0df54292012-03-26 14:50:32 -04002105/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002106
Victor Stinnerd3f08822012-05-29 12:57:52 +02002107PyObject*
2108_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002109{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002110 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002111 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002112 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002113#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002114 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002115#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002116 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002117 }
Victor Stinner785938e2011-12-11 20:09:03 +01002118 unicode = PyUnicode_New(size, 127);
2119 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002120 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002121 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2122 assert(_PyUnicode_CheckConsistency(unicode, 1));
2123 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002124}
2125
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002126static Py_UCS4
2127kind_maxchar_limit(unsigned int kind)
2128{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002129 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002130 case PyUnicode_1BYTE_KIND:
2131 return 0x80;
2132 case PyUnicode_2BYTE_KIND:
2133 return 0x100;
2134 case PyUnicode_4BYTE_KIND:
2135 return 0x10000;
2136 default:
2137 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002138 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002139 }
2140}
2141
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -07002142static inline Py_UCS4
Victor Stinnere6abb482012-05-02 01:15:40 +02002143align_maxchar(Py_UCS4 maxchar)
2144{
2145 if (maxchar <= 127)
2146 return 127;
2147 else if (maxchar <= 255)
2148 return 255;
2149 else if (maxchar <= 65535)
2150 return 65535;
2151 else
2152 return MAX_UNICODE;
2153}
2154
Victor Stinner702c7342011-10-05 13:50:52 +02002155static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002156_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002157{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002158 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002159 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002160
Serhiy Storchaka678db842013-01-26 12:16:36 +02002161 if (size == 0)
2162 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002163 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002164 if (size == 1)
2165 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002166
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002167 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002168 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002169 if (!res)
2170 return NULL;
2171 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002172 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002174}
2175
Victor Stinnere57b1c02011-09-28 22:20:48 +02002176static PyObject*
2177_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002178{
2179 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002180 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002181
Serhiy Storchaka678db842013-01-26 12:16:36 +02002182 if (size == 0)
2183 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002184 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002185 if (size == 1)
2186 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002187
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002188 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002189 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002190 if (!res)
2191 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002192 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002193 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002194 else {
2195 _PyUnicode_CONVERT_BYTES(
2196 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2197 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002198 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002199 return res;
2200}
2201
Victor Stinnere57b1c02011-09-28 22:20:48 +02002202static PyObject*
2203_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002204{
2205 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002206 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002207
Serhiy Storchaka678db842013-01-26 12:16:36 +02002208 if (size == 0)
2209 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002210 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002211 if (size == 1)
2212 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002213
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002214 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002215 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 if (!res)
2217 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002218 if (max_char < 256)
2219 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2220 PyUnicode_1BYTE_DATA(res));
2221 else if (max_char < 0x10000)
2222 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2223 PyUnicode_2BYTE_DATA(res));
2224 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002225 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002226 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002227 return res;
2228}
2229
2230PyObject*
2231PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2232{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002233 if (size < 0) {
2234 PyErr_SetString(PyExc_ValueError, "size must be positive");
2235 return NULL;
2236 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002237 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002238 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002239 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002241 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002242 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002243 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002244 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002245 PyErr_SetString(PyExc_SystemError, "invalid kind");
2246 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002248}
2249
Victor Stinnerece58de2012-04-23 23:36:38 +02002250Py_UCS4
2251_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2252{
2253 enum PyUnicode_Kind kind;
2254 void *startptr, *endptr;
2255
2256 assert(PyUnicode_IS_READY(unicode));
2257 assert(0 <= start);
2258 assert(end <= PyUnicode_GET_LENGTH(unicode));
2259 assert(start <= end);
2260
2261 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2262 return PyUnicode_MAX_CHAR_VALUE(unicode);
2263
2264 if (start == end)
2265 return 127;
2266
Victor Stinner94d558b2012-04-27 22:26:58 +02002267 if (PyUnicode_IS_ASCII(unicode))
2268 return 127;
2269
Victor Stinnerece58de2012-04-23 23:36:38 +02002270 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002271 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002272 endptr = (char *)startptr + end * kind;
2273 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002274 switch(kind) {
2275 case PyUnicode_1BYTE_KIND:
2276 return ucs1lib_find_max_char(startptr, endptr);
2277 case PyUnicode_2BYTE_KIND:
2278 return ucs2lib_find_max_char(startptr, endptr);
2279 case PyUnicode_4BYTE_KIND:
2280 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002281 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002282 assert(0);
2283 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002284 }
2285}
2286
Victor Stinner25a4b292011-10-06 12:31:55 +02002287/* Ensure that a string uses the most efficient storage, if it is not the
2288 case: create a new string with of the right kind. Write NULL into *p_unicode
2289 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002290static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002291unicode_adjust_maxchar(PyObject **p_unicode)
2292{
2293 PyObject *unicode, *copy;
2294 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002295 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002296 unsigned int kind;
2297
2298 assert(p_unicode != NULL);
2299 unicode = *p_unicode;
2300 assert(PyUnicode_IS_READY(unicode));
2301 if (PyUnicode_IS_ASCII(unicode))
2302 return;
2303
2304 len = PyUnicode_GET_LENGTH(unicode);
2305 kind = PyUnicode_KIND(unicode);
2306 if (kind == PyUnicode_1BYTE_KIND) {
2307 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002308 max_char = ucs1lib_find_max_char(u, u + len);
2309 if (max_char >= 128)
2310 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002311 }
2312 else if (kind == PyUnicode_2BYTE_KIND) {
2313 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002314 max_char = ucs2lib_find_max_char(u, u + len);
2315 if (max_char >= 256)
2316 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002317 }
2318 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002319 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002320 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002321 max_char = ucs4lib_find_max_char(u, u + len);
2322 if (max_char >= 0x10000)
2323 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002324 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002325 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002326 if (copy != NULL)
2327 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002328 Py_DECREF(unicode);
2329 *p_unicode = copy;
2330}
2331
Victor Stinner034f6cf2011-09-30 02:26:44 +02002332PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002333_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002334{
Victor Stinner87af4f22011-11-21 23:03:47 +01002335 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002336 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002337
Victor Stinner034f6cf2011-09-30 02:26:44 +02002338 if (!PyUnicode_Check(unicode)) {
2339 PyErr_BadInternalCall();
2340 return NULL;
2341 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002342 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002343 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002344
Victor Stinner87af4f22011-11-21 23:03:47 +01002345 length = PyUnicode_GET_LENGTH(unicode);
2346 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002347 if (!copy)
2348 return NULL;
2349 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2350
Victor Stinner87af4f22011-11-21 23:03:47 +01002351 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2352 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002353 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002354 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002355}
2356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002357
Victor Stinnerbc603d12011-10-02 01:00:40 +02002358/* Widen Unicode objects to larger buffers. Don't write terminating null
2359 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002360
2361void*
2362_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2363{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002364 Py_ssize_t len;
2365 void *result;
2366 unsigned int skind;
2367
Benjamin Petersonbac79492012-01-14 13:34:47 -05002368 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002369 return NULL;
2370
2371 len = PyUnicode_GET_LENGTH(s);
2372 skind = PyUnicode_KIND(s);
2373 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002374 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375 return NULL;
2376 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002377 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002378 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002379 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002380 if (!result)
2381 return PyErr_NoMemory();
2382 assert(skind == PyUnicode_1BYTE_KIND);
2383 _PyUnicode_CONVERT_BYTES(
2384 Py_UCS1, Py_UCS2,
2385 PyUnicode_1BYTE_DATA(s),
2386 PyUnicode_1BYTE_DATA(s) + len,
2387 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002388 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002389 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002390 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002391 if (!result)
2392 return PyErr_NoMemory();
2393 if (skind == PyUnicode_2BYTE_KIND) {
2394 _PyUnicode_CONVERT_BYTES(
2395 Py_UCS2, Py_UCS4,
2396 PyUnicode_2BYTE_DATA(s),
2397 PyUnicode_2BYTE_DATA(s) + len,
2398 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002400 else {
2401 assert(skind == PyUnicode_1BYTE_KIND);
2402 _PyUnicode_CONVERT_BYTES(
2403 Py_UCS1, Py_UCS4,
2404 PyUnicode_1BYTE_DATA(s),
2405 PyUnicode_1BYTE_DATA(s) + len,
2406 result);
2407 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002408 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002409 default:
2410 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002411 }
Victor Stinner01698042011-10-04 00:04:26 +02002412 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 return NULL;
2414}
2415
2416static Py_UCS4*
2417as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2418 int copy_null)
2419{
2420 int kind;
2421 void *data;
2422 Py_ssize_t len, targetlen;
2423 if (PyUnicode_READY(string) == -1)
2424 return NULL;
2425 kind = PyUnicode_KIND(string);
2426 data = PyUnicode_DATA(string);
2427 len = PyUnicode_GET_LENGTH(string);
2428 targetlen = len;
2429 if (copy_null)
2430 targetlen++;
2431 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002432 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 if (!target) {
2434 PyErr_NoMemory();
2435 return NULL;
2436 }
2437 }
2438 else {
2439 if (targetsize < targetlen) {
2440 PyErr_Format(PyExc_SystemError,
2441 "string is longer than the buffer");
2442 if (copy_null && 0 < targetsize)
2443 target[0] = 0;
2444 return NULL;
2445 }
2446 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002447 if (kind == PyUnicode_1BYTE_KIND) {
2448 Py_UCS1 *start = (Py_UCS1 *) data;
2449 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002450 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002451 else if (kind == PyUnicode_2BYTE_KIND) {
2452 Py_UCS2 *start = (Py_UCS2 *) data;
2453 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2454 }
2455 else {
2456 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002458 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 if (copy_null)
2460 target[len] = 0;
2461 return target;
2462}
2463
2464Py_UCS4*
2465PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2466 int copy_null)
2467{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002468 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002469 PyErr_BadInternalCall();
2470 return NULL;
2471 }
2472 return as_ucs4(string, target, targetsize, copy_null);
2473}
2474
2475Py_UCS4*
2476PyUnicode_AsUCS4Copy(PyObject *string)
2477{
2478 return as_ucs4(string, NULL, 0, 1);
2479}
2480
2481#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002482
Alexander Belopolsky40018472011-02-26 01:02:56 +00002483PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002484PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002485{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002486 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002487 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002488 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002489 PyErr_BadInternalCall();
2490 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002491 }
2492
Martin v. Löwis790465f2008-04-05 20:41:37 +00002493 if (size == -1) {
2494 size = wcslen(w);
2495 }
2496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002497 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002498}
2499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002501
Victor Stinner15a11362012-10-06 23:48:20 +02002502/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002503 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2504 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2505#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002506
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002507static int
2508unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2509 Py_ssize_t width, Py_ssize_t precision)
2510{
2511 Py_ssize_t length, fill, arglen;
2512 Py_UCS4 maxchar;
2513
2514 if (PyUnicode_READY(str) == -1)
2515 return -1;
2516
2517 length = PyUnicode_GET_LENGTH(str);
2518 if ((precision == -1 || precision >= length)
2519 && width <= length)
2520 return _PyUnicodeWriter_WriteStr(writer, str);
2521
2522 if (precision != -1)
2523 length = Py_MIN(precision, length);
2524
2525 arglen = Py_MAX(length, width);
2526 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2527 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2528 else
2529 maxchar = writer->maxchar;
2530
2531 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2532 return -1;
2533
2534 if (width > length) {
2535 fill = width - length;
2536 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2537 return -1;
2538 writer->pos += fill;
2539 }
2540
2541 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2542 str, 0, length);
2543 writer->pos += length;
2544 return 0;
2545}
2546
2547static int
2548unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2549 Py_ssize_t width, Py_ssize_t precision)
2550{
2551 /* UTF-8 */
2552 Py_ssize_t length;
2553 PyObject *unicode;
2554 int res;
2555
2556 length = strlen(str);
2557 if (precision != -1)
2558 length = Py_MIN(length, precision);
2559 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2560 if (unicode == NULL)
2561 return -1;
2562
2563 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2564 Py_DECREF(unicode);
2565 return res;
2566}
2567
Victor Stinner96865452011-03-01 23:44:09 +00002568static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002569unicode_fromformat_arg(_PyUnicodeWriter *writer,
2570 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002571{
Victor Stinnere215d962012-10-06 23:03:36 +02002572 const char *p;
2573 Py_ssize_t len;
2574 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002575 Py_ssize_t width;
2576 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002577 int longflag;
2578 int longlongflag;
2579 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002580 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002581
2582 p = f;
2583 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002584 zeropad = 0;
2585 if (*f == '0') {
2586 zeropad = 1;
2587 f++;
2588 }
Victor Stinner96865452011-03-01 23:44:09 +00002589
2590 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002591 width = -1;
2592 if (Py_ISDIGIT((unsigned)*f)) {
2593 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002594 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002595 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002596 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002597 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002598 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002599 return NULL;
2600 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002601 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002602 f++;
2603 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002604 }
2605 precision = -1;
2606 if (*f == '.') {
2607 f++;
2608 if (Py_ISDIGIT((unsigned)*f)) {
2609 precision = (*f - '0');
2610 f++;
2611 while (Py_ISDIGIT((unsigned)*f)) {
2612 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2613 PyErr_SetString(PyExc_ValueError,
2614 "precision too big");
2615 return NULL;
2616 }
2617 precision = (precision * 10) + (*f - '0');
2618 f++;
2619 }
2620 }
Victor Stinner96865452011-03-01 23:44:09 +00002621 if (*f == '%') {
2622 /* "%.3%s" => f points to "3" */
2623 f--;
2624 }
2625 }
2626 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002627 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002628 f--;
2629 }
Victor Stinner96865452011-03-01 23:44:09 +00002630
2631 /* Handle %ld, %lu, %lld and %llu. */
2632 longflag = 0;
2633 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002634 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002635 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002636 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002637 longflag = 1;
2638 ++f;
2639 }
Victor Stinner96865452011-03-01 23:44:09 +00002640 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002641 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002642 longlongflag = 1;
2643 f += 2;
2644 }
Victor Stinner96865452011-03-01 23:44:09 +00002645 }
2646 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002647 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002648 size_tflag = 1;
2649 ++f;
2650 }
Victor Stinnere215d962012-10-06 23:03:36 +02002651
2652 if (f[1] == '\0')
2653 writer->overallocate = 0;
2654
2655 switch (*f) {
2656 case 'c':
2657 {
2658 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002659 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002660 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002661 "character argument not in range(0x110000)");
2662 return NULL;
2663 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002664 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002665 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002666 break;
2667 }
2668
2669 case 'i':
2670 case 'd':
2671 case 'u':
2672 case 'x':
2673 {
2674 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002675 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002676 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002677
2678 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002679 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002680 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002681 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002682 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002683 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002684 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002685 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002686 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002687 va_arg(*vargs, size_t));
2688 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002689 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002690 va_arg(*vargs, unsigned int));
2691 }
2692 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002693 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002694 }
2695 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002696 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002697 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002698 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002699 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002700 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002701 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002702 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002703 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002704 va_arg(*vargs, Py_ssize_t));
2705 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002706 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002707 va_arg(*vargs, int));
2708 }
2709 assert(len >= 0);
2710
Victor Stinnere215d962012-10-06 23:03:36 +02002711 if (precision < len)
2712 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002713
2714 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002715 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2716 return NULL;
2717
Victor Stinnere215d962012-10-06 23:03:36 +02002718 if (width > precision) {
2719 Py_UCS4 fillchar;
2720 fill = width - precision;
2721 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002722 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2723 return NULL;
2724 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002725 }
Victor Stinner15a11362012-10-06 23:48:20 +02002726 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002727 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002728 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2729 return NULL;
2730 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002731 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002732
Victor Stinner4a587072013-11-19 12:54:53 +01002733 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2734 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002735 break;
2736 }
2737
2738 case 'p':
2739 {
2740 char number[MAX_LONG_LONG_CHARS];
2741
2742 len = sprintf(number, "%p", va_arg(*vargs, void*));
2743 assert(len >= 0);
2744
2745 /* %p is ill-defined: ensure leading 0x. */
2746 if (number[1] == 'X')
2747 number[1] = 'x';
2748 else if (number[1] != 'x') {
2749 memmove(number + 2, number,
2750 strlen(number) + 1);
2751 number[0] = '0';
2752 number[1] = 'x';
2753 len += 2;
2754 }
2755
Victor Stinner4a587072013-11-19 12:54:53 +01002756 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002757 return NULL;
2758 break;
2759 }
2760
2761 case 's':
2762 {
2763 /* UTF-8 */
2764 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002765 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002766 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002767 break;
2768 }
2769
2770 case 'U':
2771 {
2772 PyObject *obj = va_arg(*vargs, PyObject *);
2773 assert(obj && _PyUnicode_CHECK(obj));
2774
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002775 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002776 return NULL;
2777 break;
2778 }
2779
2780 case 'V':
2781 {
2782 PyObject *obj = va_arg(*vargs, PyObject *);
2783 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002784 if (obj) {
2785 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002786 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002787 return NULL;
2788 }
2789 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002790 assert(str != NULL);
2791 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002792 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002793 }
2794 break;
2795 }
2796
2797 case 'S':
2798 {
2799 PyObject *obj = va_arg(*vargs, PyObject *);
2800 PyObject *str;
2801 assert(obj);
2802 str = PyObject_Str(obj);
2803 if (!str)
2804 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002805 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002806 Py_DECREF(str);
2807 return NULL;
2808 }
2809 Py_DECREF(str);
2810 break;
2811 }
2812
2813 case 'R':
2814 {
2815 PyObject *obj = va_arg(*vargs, PyObject *);
2816 PyObject *repr;
2817 assert(obj);
2818 repr = PyObject_Repr(obj);
2819 if (!repr)
2820 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002821 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002822 Py_DECREF(repr);
2823 return NULL;
2824 }
2825 Py_DECREF(repr);
2826 break;
2827 }
2828
2829 case 'A':
2830 {
2831 PyObject *obj = va_arg(*vargs, PyObject *);
2832 PyObject *ascii;
2833 assert(obj);
2834 ascii = PyObject_ASCII(obj);
2835 if (!ascii)
2836 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002837 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002838 Py_DECREF(ascii);
2839 return NULL;
2840 }
2841 Py_DECREF(ascii);
2842 break;
2843 }
2844
2845 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002846 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002847 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002848 break;
2849
2850 default:
2851 /* if we stumble upon an unknown formatting code, copy the rest
2852 of the format string to the output string. (we cannot just
2853 skip the code, since there's no way to know what's in the
2854 argument list) */
2855 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002856 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002857 return NULL;
2858 f = p+len;
2859 return f;
2860 }
2861
2862 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002863 return f;
2864}
2865
Walter Dörwaldd2034312007-05-18 16:29:38 +00002866PyObject *
2867PyUnicode_FromFormatV(const char *format, va_list vargs)
2868{
Victor Stinnere215d962012-10-06 23:03:36 +02002869 va_list vargs2;
2870 const char *f;
2871 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002872
Victor Stinner8f674cc2013-04-17 23:02:17 +02002873 _PyUnicodeWriter_Init(&writer);
2874 writer.min_length = strlen(format) + 100;
2875 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002876
2877 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2878 Copy it to be able to pass a reference to a subfunction. */
2879 Py_VA_COPY(vargs2, vargs);
2880
2881 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002882 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002883 f = unicode_fromformat_arg(&writer, f, &vargs2);
2884 if (f == NULL)
2885 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002886 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002887 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002888 const char *p;
2889 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002890
Victor Stinnere215d962012-10-06 23:03:36 +02002891 p = f;
2892 do
2893 {
2894 if ((unsigned char)*p > 127) {
2895 PyErr_Format(PyExc_ValueError,
2896 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2897 "string, got a non-ASCII byte: 0x%02x",
2898 (unsigned char)*p);
2899 return NULL;
2900 }
2901 p++;
2902 }
2903 while (*p != '\0' && *p != '%');
2904 len = p - f;
2905
2906 if (*p == '\0')
2907 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002908
2909 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002910 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002911
2912 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002913 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002914 }
Victor Stinnere215d962012-10-06 23:03:36 +02002915 return _PyUnicodeWriter_Finish(&writer);
2916
2917 fail:
2918 _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;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002966 Py_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 Stinner942889a2016-09-05 15:40:10 -07003098/* Normalize an encoding name: C implementation of
3099 encodings.normalize_encoding(). Return 1 on success, or 0 on error (encoding
3100 is 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,
3217 Py_TYPE(unicode)->tp_name, 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{
3234 PyObject *v;
3235
3236 if (!PyUnicode_Check(unicode)) {
3237 PyErr_BadArgument();
3238 goto onError;
3239 }
3240
3241 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003242 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003243
3244 /* Decode via the codec registry */
3245 v = PyCodec_Decode(unicode, encoding, errors);
3246 if (v == NULL)
3247 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003248 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003249
Benjamin Peterson29060642009-01-31 22:14:21 +00003250 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003251 return NULL;
3252}
3253
Alexander Belopolsky40018472011-02-26 01:02:56 +00003254PyObject *
3255PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003256 const char *encoding,
3257 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003258{
3259 PyObject *v;
3260
3261 if (!PyUnicode_Check(unicode)) {
3262 PyErr_BadArgument();
3263 goto onError;
3264 }
3265
3266 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003267 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003268
3269 /* Decode via the codec registry */
3270 v = PyCodec_Decode(unicode, encoding, errors);
3271 if (v == NULL)
3272 goto onError;
3273 if (!PyUnicode_Check(v)) {
3274 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003275 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3276 "use codecs.decode() to decode to arbitrary types",
3277 encoding,
3278 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003279 Py_DECREF(v);
3280 goto onError;
3281 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003282 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003283
Benjamin Peterson29060642009-01-31 22:14:21 +00003284 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003285 return NULL;
3286}
3287
Alexander Belopolsky40018472011-02-26 01:02:56 +00003288PyObject *
3289PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003290 Py_ssize_t size,
3291 const char *encoding,
3292 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003293{
3294 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003295
Guido van Rossumd57fd912000-03-10 22:53:23 +00003296 unicode = PyUnicode_FromUnicode(s, size);
3297 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003298 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003299 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3300 Py_DECREF(unicode);
3301 return v;
3302}
3303
Alexander Belopolsky40018472011-02-26 01:02:56 +00003304PyObject *
3305PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003306 const char *encoding,
3307 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003308{
3309 PyObject *v;
3310
3311 if (!PyUnicode_Check(unicode)) {
3312 PyErr_BadArgument();
3313 goto onError;
3314 }
3315
3316 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003317 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003318
3319 /* Encode via the codec registry */
3320 v = PyCodec_Encode(unicode, encoding, errors);
3321 if (v == NULL)
3322 goto onError;
3323 return v;
3324
Benjamin Peterson29060642009-01-31 22:14:21 +00003325 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003326 return NULL;
3327}
3328
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003329static size_t
3330wcstombs_errorpos(const wchar_t *wstr)
3331{
3332 size_t len;
3333#if SIZEOF_WCHAR_T == 2
3334 wchar_t buf[3];
3335#else
3336 wchar_t buf[2];
3337#endif
3338 char outbuf[MB_LEN_MAX];
3339 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003340
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003341#if SIZEOF_WCHAR_T == 2
3342 buf[2] = 0;
3343#else
3344 buf[1] = 0;
3345#endif
3346 start = wstr;
3347 while (*wstr != L'\0')
3348 {
3349 previous = wstr;
3350#if SIZEOF_WCHAR_T == 2
3351 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3352 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3353 {
3354 buf[0] = wstr[0];
3355 buf[1] = wstr[1];
3356 wstr += 2;
3357 }
3358 else {
3359 buf[0] = *wstr;
3360 buf[1] = 0;
3361 wstr++;
3362 }
3363#else
3364 buf[0] = *wstr;
3365 wstr++;
3366#endif
3367 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003368 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003369 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003370 }
3371
3372 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003373 return 0;
3374}
3375
Victor Stinner1b579672011-12-17 05:47:23 +01003376static int
3377locale_error_handler(const char *errors, int *surrogateescape)
3378{
Victor Stinner50149202015-09-22 00:26:54 +02003379 _Py_error_handler error_handler = get_error_handler(errors);
3380 switch (error_handler)
3381 {
3382 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003383 *surrogateescape = 0;
3384 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003385 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003386 *surrogateescape = 1;
3387 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003388 default:
3389 PyErr_Format(PyExc_ValueError,
3390 "only 'strict' and 'surrogateescape' error handlers "
3391 "are supported, not '%s'",
3392 errors);
3393 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003394 }
Victor Stinner1b579672011-12-17 05:47:23 +01003395}
3396
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003397PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003398PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003399{
3400 Py_ssize_t wlen, wlen2;
3401 wchar_t *wstr;
3402 PyObject *bytes = NULL;
3403 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003404 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003405 PyObject *exc;
3406 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003407 int surrogateescape;
3408
3409 if (locale_error_handler(errors, &surrogateescape) < 0)
3410 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003411
3412 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3413 if (wstr == NULL)
3414 return NULL;
3415
3416 wlen2 = wcslen(wstr);
3417 if (wlen2 != wlen) {
3418 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003419 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003420 return NULL;
3421 }
3422
3423 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003424 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003425 char *str;
3426
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003427 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003428 if (str == NULL) {
3429 if (error_pos == (size_t)-1) {
3430 PyErr_NoMemory();
3431 PyMem_Free(wstr);
3432 return NULL;
3433 }
3434 else {
3435 goto encode_error;
3436 }
3437 }
3438 PyMem_Free(wstr);
3439
3440 bytes = PyBytes_FromString(str);
3441 PyMem_Free(str);
3442 }
3443 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003444 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003445 size_t len, len2;
3446
3447 len = wcstombs(NULL, wstr, 0);
3448 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003449 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003450 goto encode_error;
3451 }
3452
3453 bytes = PyBytes_FromStringAndSize(NULL, len);
3454 if (bytes == NULL) {
3455 PyMem_Free(wstr);
3456 return NULL;
3457 }
3458
3459 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3460 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003461 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003462 goto encode_error;
3463 }
3464 PyMem_Free(wstr);
3465 }
3466 return bytes;
3467
3468encode_error:
3469 errmsg = strerror(errno);
3470 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003471
3472 if (error_pos == (size_t)-1)
3473 error_pos = wcstombs_errorpos(wstr);
3474
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003475 PyMem_Free(wstr);
3476 Py_XDECREF(bytes);
3477
Victor Stinner2f197072011-12-17 07:08:30 +01003478 if (errmsg != NULL) {
3479 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003480 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003481 if (wstr != NULL) {
3482 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003483 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003484 } else
3485 errmsg = NULL;
3486 }
3487 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003488 reason = PyUnicode_FromString(
3489 "wcstombs() encountered an unencodable "
3490 "wide character");
3491 if (reason == NULL)
3492 return NULL;
3493
3494 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3495 "locale", unicode,
3496 (Py_ssize_t)error_pos,
3497 (Py_ssize_t)(error_pos+1),
3498 reason);
3499 Py_DECREF(reason);
3500 if (exc != NULL) {
3501 PyCodec_StrictErrors(exc);
3502 Py_XDECREF(exc);
3503 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003504 return NULL;
3505}
3506
Victor Stinnerad158722010-10-27 00:25:46 +00003507PyObject *
3508PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003509{
Steve Dowercc16be82016-09-08 10:35:16 -07003510#if defined(__APPLE__)
3511 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003512#else
Victor Stinner793b5312011-04-27 00:24:21 +02003513 PyInterpreterState *interp = PyThreadState_GET()->interp;
3514 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3515 cannot use it to encode and decode filenames before it is loaded. Load
3516 the Python codec requires to encode at least its own filename. Use the C
3517 version of the locale codec until the codec registry is initialized and
3518 the Python codec is loaded.
3519
3520 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3521 cannot only rely on it: check also interp->fscodec_initialized for
3522 subinterpreters. */
3523 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003524 return PyUnicode_AsEncodedString(unicode,
3525 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003526 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003527 }
3528 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003529 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003530 }
Victor Stinnerad158722010-10-27 00:25:46 +00003531#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003532}
3533
Alexander Belopolsky40018472011-02-26 01:02:56 +00003534PyObject *
3535PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003536 const char *encoding,
3537 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003538{
3539 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003540 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003541
Guido van Rossumd57fd912000-03-10 22:53:23 +00003542 if (!PyUnicode_Check(unicode)) {
3543 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003544 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003545 }
Fred Drakee4315f52000-05-09 19:53:39 +00003546
Victor Stinner942889a2016-09-05 15:40:10 -07003547 if (encoding == NULL) {
3548 return _PyUnicode_AsUTF8String(unicode, errors);
3549 }
3550
Fred Drakee4315f52000-05-09 19:53:39 +00003551 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003552 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3553 char *lower = buflower;
3554
3555 /* Fast paths */
3556 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3557 lower += 3;
3558 if (*lower == '_') {
3559 /* Match "utf8" and "utf_8" */
3560 lower++;
3561 }
3562
3563 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003564 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003565 }
3566 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3567 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3568 }
3569 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3570 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3571 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003572 }
Victor Stinner942889a2016-09-05 15:40:10 -07003573 else {
3574 if (strcmp(lower, "ascii") == 0
3575 || strcmp(lower, "us_ascii") == 0) {
3576 return _PyUnicode_AsASCIIString(unicode, errors);
3577 }
Steve Dowercc16be82016-09-08 10:35:16 -07003578#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003579 else if (strcmp(lower, "mbcs") == 0) {
3580 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3581 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003582#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003583 else if (strcmp(lower, "latin1") == 0 ||
3584 strcmp(lower, "latin_1") == 0 ||
3585 strcmp(lower, "iso_8859_1") == 0 ||
3586 strcmp(lower, "iso8859_1") == 0) {
3587 return _PyUnicode_AsLatin1String(unicode, errors);
3588 }
3589 }
Victor Stinner37296e82010-06-10 13:36:23 +00003590 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003591
3592 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003593 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003594 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003595 return NULL;
3596
3597 /* The normal path */
3598 if (PyBytes_Check(v))
3599 return v;
3600
3601 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003602 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003603 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003604 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003605
3606 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003607 "encoder %s returned bytearray instead of bytes; "
3608 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003609 encoding);
3610 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003611 Py_DECREF(v);
3612 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003613 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003614
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003615 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3616 Py_DECREF(v);
3617 return b;
3618 }
3619
3620 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003621 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3622 "use codecs.encode() to encode to arbitrary types",
3623 encoding,
3624 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003625 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003626 return NULL;
3627}
3628
Alexander Belopolsky40018472011-02-26 01:02:56 +00003629PyObject *
3630PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003631 const char *encoding,
3632 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003633{
3634 PyObject *v;
3635
3636 if (!PyUnicode_Check(unicode)) {
3637 PyErr_BadArgument();
3638 goto onError;
3639 }
3640
3641 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003642 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003643
3644 /* Encode via the codec registry */
3645 v = PyCodec_Encode(unicode, encoding, errors);
3646 if (v == NULL)
3647 goto onError;
3648 if (!PyUnicode_Check(v)) {
3649 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003650 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3651 "use codecs.encode() to encode to arbitrary types",
3652 encoding,
3653 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003654 Py_DECREF(v);
3655 goto onError;
3656 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003657 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003658
Benjamin Peterson29060642009-01-31 22:14:21 +00003659 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003660 return NULL;
3661}
3662
Victor Stinner2f197072011-12-17 07:08:30 +01003663static size_t
3664mbstowcs_errorpos(const char *str, size_t len)
3665{
3666#ifdef HAVE_MBRTOWC
3667 const char *start = str;
3668 mbstate_t mbs;
3669 size_t converted;
3670 wchar_t ch;
3671
3672 memset(&mbs, 0, sizeof mbs);
3673 while (len)
3674 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003675 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003676 if (converted == 0)
3677 /* Reached end of string */
3678 break;
3679 if (converted == (size_t)-1 || converted == (size_t)-2) {
3680 /* Conversion error or incomplete character */
3681 return str - start;
3682 }
3683 else {
3684 str += converted;
3685 len -= converted;
3686 }
3687 }
3688 /* failed to find the undecodable byte sequence */
3689 return 0;
3690#endif
3691 return 0;
3692}
3693
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003694PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003695PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003696 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003697{
3698 wchar_t smallbuf[256];
3699 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3700 wchar_t *wstr;
3701 size_t wlen, wlen2;
3702 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003703 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003704 size_t error_pos;
3705 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003706 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3707 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003708
3709 if (locale_error_handler(errors, &surrogateescape) < 0)
3710 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003711
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003712 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3713 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003714 return NULL;
3715 }
3716
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003717 if (surrogateescape) {
3718 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003719 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003720 if (wstr == NULL) {
3721 if (wlen == (size_t)-1)
3722 PyErr_NoMemory();
3723 else
3724 PyErr_SetFromErrno(PyExc_OSError);
3725 return NULL;
3726 }
3727
3728 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003729 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003730 }
3731 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003732 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003733#ifndef HAVE_BROKEN_MBSTOWCS
3734 wlen = mbstowcs(NULL, str, 0);
3735#else
3736 wlen = len;
3737#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003738 if (wlen == (size_t)-1)
3739 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003740 if (wlen+1 <= smallbuf_len) {
3741 wstr = smallbuf;
3742 }
3743 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003744 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003745 if (!wstr)
3746 return PyErr_NoMemory();
3747 }
3748
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003749 wlen2 = mbstowcs(wstr, str, wlen+1);
3750 if (wlen2 == (size_t)-1) {
3751 if (wstr != smallbuf)
3752 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003753 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003754 }
3755#ifdef HAVE_BROKEN_MBSTOWCS
3756 assert(wlen2 == wlen);
3757#endif
3758 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3759 if (wstr != smallbuf)
3760 PyMem_Free(wstr);
3761 }
3762 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003763
3764decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003765 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003766 errmsg = strerror(errno);
3767 assert(errmsg != NULL);
3768
3769 error_pos = mbstowcs_errorpos(str, len);
3770 if (errmsg != NULL) {
3771 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003772 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003773 if (wstr != NULL) {
3774 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003775 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003776 }
Victor Stinner2f197072011-12-17 07:08:30 +01003777 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003778 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003779 reason = PyUnicode_FromString(
3780 "mbstowcs() encountered an invalid multibyte sequence");
3781 if (reason == NULL)
3782 return NULL;
3783
3784 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3785 "locale", str, len,
3786 (Py_ssize_t)error_pos,
3787 (Py_ssize_t)(error_pos+1),
3788 reason);
3789 Py_DECREF(reason);
3790 if (exc != NULL) {
3791 PyCodec_StrictErrors(exc);
3792 Py_XDECREF(exc);
3793 }
3794 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003795}
3796
3797PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003798PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003799{
3800 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003801 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003802}
3803
3804
3805PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003806PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003807 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003808 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3809}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003810
Christian Heimes5894ba72007-11-04 11:43:14 +00003811PyObject*
3812PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3813{
Steve Dowercc16be82016-09-08 10:35:16 -07003814#if defined(__APPLE__)
3815 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003816#else
Victor Stinner793b5312011-04-27 00:24:21 +02003817 PyInterpreterState *interp = PyThreadState_GET()->interp;
3818 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3819 cannot use it to encode and decode filenames before it is loaded. Load
3820 the Python codec requires to encode at least its own filename. Use the C
3821 version of the locale codec until the codec registry is initialized and
3822 the Python codec is loaded.
3823
3824 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3825 cannot only rely on it: check also interp->fscodec_initialized for
3826 subinterpreters. */
3827 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dowercc16be82016-09-08 10:35:16 -07003828 PyObject *res = PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003829 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003830 Py_FileSystemDefaultEncodeErrors);
3831#ifdef MS_WINDOWS
3832 if (!res && PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
3833 PyObject *exc, *val, *tb;
3834 PyErr_Fetch(&exc, &val, &tb);
3835 PyErr_Format(PyExc_RuntimeError,
3836 "filesystem path bytes were not correctly encoded with '%s'. " \
3837 "Please report this at http://bugs.python.org/issue27781",
3838 Py_FileSystemDefaultEncoding);
3839 _PyErr_ChainExceptions(exc, val, tb);
3840 }
3841#endif
3842 return res;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003843 }
3844 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003845 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003846 }
Victor Stinnerad158722010-10-27 00:25:46 +00003847#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003848}
3849
Martin v. Löwis011e8422009-05-05 04:43:17 +00003850
3851int
3852PyUnicode_FSConverter(PyObject* arg, void* addr)
3853{
Brett Cannonec6ce872016-09-06 15:50:29 -07003854 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003855 PyObject *output = NULL;
3856 Py_ssize_t size;
3857 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003858 if (arg == NULL) {
3859 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003860 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003861 return 1;
3862 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003863 path = PyOS_FSPath(arg);
3864 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003865 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003866 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003867 if (PyBytes_Check(path)) {
3868 output = path;
3869 }
3870 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3871 output = PyUnicode_EncodeFSDefault(path);
3872 Py_DECREF(path);
3873 if (!output) {
3874 return 0;
3875 }
3876 assert(PyBytes_Check(output));
3877 }
3878
Victor Stinner0ea2a462010-04-30 00:22:08 +00003879 size = PyBytes_GET_SIZE(output);
3880 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003881 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003882 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003883 Py_DECREF(output);
3884 return 0;
3885 }
3886 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003887 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003888}
3889
3890
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003891int
3892PyUnicode_FSDecoder(PyObject* arg, void* addr)
3893{
Brett Cannona5711202016-09-06 19:36:01 -07003894 int is_buffer = 0;
3895 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003896 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003897 if (arg == NULL) {
3898 Py_DECREF(*(PyObject**)addr);
3899 return 1;
3900 }
Brett Cannona5711202016-09-06 19:36:01 -07003901
3902 is_buffer = PyObject_CheckBuffer(arg);
3903 if (!is_buffer) {
3904 path = PyOS_FSPath(arg);
3905 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003906 return 0;
3907 }
Brett Cannona5711202016-09-06 19:36:01 -07003908 }
3909 else {
3910 path = arg;
3911 Py_INCREF(arg);
3912 }
3913
3914 if (PyUnicode_Check(path)) {
3915 if (PyUnicode_READY(path) == -1) {
3916 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003917 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003918 }
3919 output = path;
3920 }
3921 else if (PyBytes_Check(path) || is_buffer) {
3922 PyObject *path_bytes = NULL;
3923
3924 if (!PyBytes_Check(path) &&
3925 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3926 "path should be string, bytes, or os.PathLike, not %.200s",
3927 Py_TYPE(arg)->tp_name)) {
3928 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003929 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003930 }
3931 path_bytes = PyBytes_FromObject(path);
3932 Py_DECREF(path);
3933 if (!path_bytes) {
3934 return 0;
3935 }
3936 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3937 PyBytes_GET_SIZE(path_bytes));
3938 Py_DECREF(path_bytes);
3939 if (!output) {
3940 return 0;
3941 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003942 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003943 else {
3944 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003945 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003946 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003947 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003948 return 0;
3949 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003950 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003951 Py_DECREF(output);
3952 return 0;
3953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003955 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003956 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003957 Py_DECREF(output);
3958 return 0;
3959 }
3960 *(PyObject**)addr = output;
3961 return Py_CLEANUP_SUPPORTED;
3962}
3963
3964
Martin v. Löwis5b222132007-06-10 09:51:05 +00003965char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003966PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003967{
Christian Heimesf3863112007-11-22 07:46:41 +00003968 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003969
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003970 if (!PyUnicode_Check(unicode)) {
3971 PyErr_BadArgument();
3972 return NULL;
3973 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003974 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003975 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003976
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003977 if (PyUnicode_UTF8(unicode) == NULL) {
3978 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003979 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003980 if (bytes == NULL)
3981 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003982 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3983 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003984 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003985 Py_DECREF(bytes);
3986 return NULL;
3987 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003988 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3989 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3990 PyBytes_AS_STRING(bytes),
3991 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003992 Py_DECREF(bytes);
3993 }
3994
3995 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003996 *psize = PyUnicode_UTF8_LENGTH(unicode);
3997 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003998}
3999
4000char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004001PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004002{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4004}
4005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004006Py_UNICODE *
4007PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4008{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004009 const unsigned char *one_byte;
4010#if SIZEOF_WCHAR_T == 4
4011 const Py_UCS2 *two_bytes;
4012#else
4013 const Py_UCS4 *four_bytes;
4014 const Py_UCS4 *ucs4_end;
4015 Py_ssize_t num_surrogates;
4016#endif
4017 wchar_t *w;
4018 wchar_t *wchar_end;
4019
4020 if (!PyUnicode_Check(unicode)) {
4021 PyErr_BadArgument();
4022 return NULL;
4023 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004024 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004025 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004026 assert(_PyUnicode_KIND(unicode) != 0);
4027 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004028
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004029 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004030#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004031 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4032 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004033 num_surrogates = 0;
4034
4035 for (; four_bytes < ucs4_end; ++four_bytes) {
4036 if (*four_bytes > 0xFFFF)
4037 ++num_surrogates;
4038 }
4039
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004040 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4041 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4042 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004043 PyErr_NoMemory();
4044 return NULL;
4045 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004046 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004047
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004048 w = _PyUnicode_WSTR(unicode);
4049 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4050 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004051 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4052 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004053 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004054 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004055 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4056 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004057 }
4058 else
4059 *w = *four_bytes;
4060
4061 if (w > wchar_end) {
4062 assert(0 && "Miscalculated string end");
4063 }
4064 }
4065 *w = 0;
4066#else
4067 /* sizeof(wchar_t) == 4 */
4068 Py_FatalError("Impossible unicode object state, wstr and str "
4069 "should share memory already.");
4070 return NULL;
4071#endif
4072 }
4073 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004074 if ((size_t)_PyUnicode_LENGTH(unicode) >
4075 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4076 PyErr_NoMemory();
4077 return NULL;
4078 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004079 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4080 (_PyUnicode_LENGTH(unicode) + 1));
4081 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004082 PyErr_NoMemory();
4083 return NULL;
4084 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004085 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4086 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4087 w = _PyUnicode_WSTR(unicode);
4088 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004089
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004090 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4091 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004092 for (; w < wchar_end; ++one_byte, ++w)
4093 *w = *one_byte;
4094 /* null-terminate the wstr */
4095 *w = 0;
4096 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004097 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004098#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004099 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004100 for (; w < wchar_end; ++two_bytes, ++w)
4101 *w = *two_bytes;
4102 /* null-terminate the wstr */
4103 *w = 0;
4104#else
4105 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004106 PyObject_FREE(_PyUnicode_WSTR(unicode));
4107 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004108 Py_FatalError("Impossible unicode object state, wstr "
4109 "and str should share memory already.");
4110 return NULL;
4111#endif
4112 }
4113 else {
4114 assert(0 && "This should never happen.");
4115 }
4116 }
4117 }
4118 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004119 *size = PyUnicode_WSTR_LENGTH(unicode);
4120 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004121}
4122
Alexander Belopolsky40018472011-02-26 01:02:56 +00004123Py_UNICODE *
4124PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004125{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004126 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004127}
4128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004129
Alexander Belopolsky40018472011-02-26 01:02:56 +00004130Py_ssize_t
4131PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004132{
4133 if (!PyUnicode_Check(unicode)) {
4134 PyErr_BadArgument();
4135 goto onError;
4136 }
4137 return PyUnicode_GET_SIZE(unicode);
4138
Benjamin Peterson29060642009-01-31 22:14:21 +00004139 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004140 return -1;
4141}
4142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004143Py_ssize_t
4144PyUnicode_GetLength(PyObject *unicode)
4145{
Victor Stinner07621332012-06-16 04:53:46 +02004146 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004147 PyErr_BadArgument();
4148 return -1;
4149 }
Victor Stinner07621332012-06-16 04:53:46 +02004150 if (PyUnicode_READY(unicode) == -1)
4151 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004152 return PyUnicode_GET_LENGTH(unicode);
4153}
4154
4155Py_UCS4
4156PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4157{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004158 void *data;
4159 int kind;
4160
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004161 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4162 PyErr_BadArgument();
4163 return (Py_UCS4)-1;
4164 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004165 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004166 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004167 return (Py_UCS4)-1;
4168 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004169 data = PyUnicode_DATA(unicode);
4170 kind = PyUnicode_KIND(unicode);
4171 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004172}
4173
4174int
4175PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4176{
4177 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004178 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004179 return -1;
4180 }
Victor Stinner488fa492011-12-12 00:01:39 +01004181 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004182 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004183 PyErr_SetString(PyExc_IndexError, "string index out of range");
4184 return -1;
4185 }
Victor Stinner488fa492011-12-12 00:01:39 +01004186 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004187 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004188 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4189 PyErr_SetString(PyExc_ValueError, "character out of range");
4190 return -1;
4191 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004192 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4193 index, ch);
4194 return 0;
4195}
4196
Alexander Belopolsky40018472011-02-26 01:02:56 +00004197const char *
4198PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004199{
Victor Stinner42cb4622010-09-01 19:39:01 +00004200 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004201}
4202
Victor Stinner554f3f02010-06-16 23:33:54 +00004203/* create or adjust a UnicodeDecodeError */
4204static void
4205make_decode_exception(PyObject **exceptionObject,
4206 const char *encoding,
4207 const char *input, Py_ssize_t length,
4208 Py_ssize_t startpos, Py_ssize_t endpos,
4209 const char *reason)
4210{
4211 if (*exceptionObject == NULL) {
4212 *exceptionObject = PyUnicodeDecodeError_Create(
4213 encoding, input, length, startpos, endpos, reason);
4214 }
4215 else {
4216 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4217 goto onError;
4218 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4219 goto onError;
4220 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4221 goto onError;
4222 }
4223 return;
4224
4225onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004226 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004227}
4228
Steve Dowercc16be82016-09-08 10:35:16 -07004229#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004230/* error handling callback helper:
4231 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004232 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004233 and adjust various state variables.
4234 return 0 on success, -1 on error
4235*/
4236
Alexander Belopolsky40018472011-02-26 01:02:56 +00004237static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004238unicode_decode_call_errorhandler_wchar(
4239 const char *errors, PyObject **errorHandler,
4240 const char *encoding, const char *reason,
4241 const char **input, const char **inend, Py_ssize_t *startinpos,
4242 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4243 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004244{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004245 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004246
4247 PyObject *restuple = NULL;
4248 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004249 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004250 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004251 Py_ssize_t requiredsize;
4252 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004253 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004254 wchar_t *repwstr;
4255 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004256
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004257 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4258 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004259
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004260 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004261 *errorHandler = PyCodec_LookupError(errors);
4262 if (*errorHandler == NULL)
4263 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004264 }
4265
Victor Stinner554f3f02010-06-16 23:33:54 +00004266 make_decode_exception(exceptionObject,
4267 encoding,
4268 *input, *inend - *input,
4269 *startinpos, *endinpos,
4270 reason);
4271 if (*exceptionObject == NULL)
4272 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004273
4274 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4275 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004276 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004277 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004278 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004279 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004280 }
4281 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004282 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004283
4284 /* Copy back the bytes variables, which might have been modified by the
4285 callback */
4286 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4287 if (!inputobj)
4288 goto onError;
4289 if (!PyBytes_Check(inputobj)) {
4290 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4291 }
4292 *input = PyBytes_AS_STRING(inputobj);
4293 insize = PyBytes_GET_SIZE(inputobj);
4294 *inend = *input + insize;
4295 /* we can DECREF safely, as the exception has another reference,
4296 so the object won't go away. */
4297 Py_DECREF(inputobj);
4298
4299 if (newpos<0)
4300 newpos = insize+newpos;
4301 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004302 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004303 goto onError;
4304 }
4305
4306 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4307 if (repwstr == NULL)
4308 goto onError;
4309 /* need more space? (at least enough for what we
4310 have+the replacement+the rest of the string (starting
4311 at the new input position), so we won't have to check space
4312 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004313 requiredsize = *outpos;
4314 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4315 goto overflow;
4316 requiredsize += repwlen;
4317 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4318 goto overflow;
4319 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004320 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004321 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004322 requiredsize = 2*outsize;
4323 if (unicode_resize(output, requiredsize) < 0)
4324 goto onError;
4325 }
4326 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4327 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004328 *endinpos = newpos;
4329 *inptr = *input + newpos;
4330
4331 /* we made it! */
4332 Py_XDECREF(restuple);
4333 return 0;
4334
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004335 overflow:
4336 PyErr_SetString(PyExc_OverflowError,
4337 "decoded result is too long for a Python string");
4338
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004339 onError:
4340 Py_XDECREF(restuple);
4341 return -1;
4342}
Steve Dowercc16be82016-09-08 10:35:16 -07004343#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004344
4345static int
4346unicode_decode_call_errorhandler_writer(
4347 const char *errors, PyObject **errorHandler,
4348 const char *encoding, const char *reason,
4349 const char **input, const char **inend, Py_ssize_t *startinpos,
4350 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4351 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4352{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004353 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004354
4355 PyObject *restuple = NULL;
4356 PyObject *repunicode = NULL;
4357 Py_ssize_t insize;
4358 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004359 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004360 PyObject *inputobj = NULL;
4361
4362 if (*errorHandler == NULL) {
4363 *errorHandler = PyCodec_LookupError(errors);
4364 if (*errorHandler == NULL)
4365 goto onError;
4366 }
4367
4368 make_decode_exception(exceptionObject,
4369 encoding,
4370 *input, *inend - *input,
4371 *startinpos, *endinpos,
4372 reason);
4373 if (*exceptionObject == NULL)
4374 goto onError;
4375
4376 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4377 if (restuple == NULL)
4378 goto onError;
4379 if (!PyTuple_Check(restuple)) {
4380 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4381 goto onError;
4382 }
4383 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004384 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004385
4386 /* Copy back the bytes variables, which might have been modified by the
4387 callback */
4388 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4389 if (!inputobj)
4390 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004391 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004392 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004393 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004394 *input = PyBytes_AS_STRING(inputobj);
4395 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004396 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004397 /* we can DECREF safely, as the exception has another reference,
4398 so the object won't go away. */
4399 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004400
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004401 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004402 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004403 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004404 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004405 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004406 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004407
Victor Stinner8f674cc2013-04-17 23:02:17 +02004408 if (PyUnicode_READY(repunicode) < 0)
4409 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004410 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004411 if (replen > 1) {
4412 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004413 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004414 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4415 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4416 goto onError;
4417 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004418 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004419 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004420
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004421 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004422 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004423
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004424 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004425 Py_XDECREF(restuple);
4426 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004427
Benjamin Peterson29060642009-01-31 22:14:21 +00004428 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004429 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004430 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004431}
4432
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004433/* --- UTF-7 Codec -------------------------------------------------------- */
4434
Antoine Pitrou244651a2009-05-04 18:56:13 +00004435/* See RFC2152 for details. We encode conservatively and decode liberally. */
4436
4437/* Three simple macros defining base-64. */
4438
4439/* Is c a base-64 character? */
4440
4441#define IS_BASE64(c) \
4442 (((c) >= 'A' && (c) <= 'Z') || \
4443 ((c) >= 'a' && (c) <= 'z') || \
4444 ((c) >= '0' && (c) <= '9') || \
4445 (c) == '+' || (c) == '/')
4446
4447/* given that c is a base-64 character, what is its base-64 value? */
4448
4449#define FROM_BASE64(c) \
4450 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4451 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4452 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4453 (c) == '+' ? 62 : 63)
4454
4455/* What is the base-64 character of the bottom 6 bits of n? */
4456
4457#define TO_BASE64(n) \
4458 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4459
4460/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4461 * decoded as itself. We are permissive on decoding; the only ASCII
4462 * byte not decoding to itself is the + which begins a base64
4463 * string. */
4464
4465#define DECODE_DIRECT(c) \
4466 ((c) <= 127 && (c) != '+')
4467
4468/* The UTF-7 encoder treats ASCII characters differently according to
4469 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4470 * the above). See RFC2152. This array identifies these different
4471 * sets:
4472 * 0 : "Set D"
4473 * alphanumeric and '(),-./:?
4474 * 1 : "Set O"
4475 * !"#$%&*;<=>@[]^_`{|}
4476 * 2 : "whitespace"
4477 * ht nl cr sp
4478 * 3 : special (must be base64 encoded)
4479 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4480 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004481
Tim Petersced69f82003-09-16 20:30:58 +00004482static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004483char utf7_category[128] = {
4484/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4485 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4486/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4487 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4488/* sp ! " # $ % & ' ( ) * + , - . / */
4489 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4490/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4491 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4492/* @ A B C D E F G H I J K L M N O */
4493 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4494/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4495 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4496/* ` a b c d e f g h i j k l m n o */
4497 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4498/* p q r s t u v w x y z { | } ~ del */
4499 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004500};
4501
Antoine Pitrou244651a2009-05-04 18:56:13 +00004502/* ENCODE_DIRECT: this character should be encoded as itself. The
4503 * answer depends on whether we are encoding set O as itself, and also
4504 * on whether we are encoding whitespace as itself. RFC2152 makes it
4505 * clear that the answers to these questions vary between
4506 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004507
Antoine Pitrou244651a2009-05-04 18:56:13 +00004508#define ENCODE_DIRECT(c, directO, directWS) \
4509 ((c) < 128 && (c) > 0 && \
4510 ((utf7_category[(c)] == 0) || \
4511 (directWS && (utf7_category[(c)] == 2)) || \
4512 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004513
Alexander Belopolsky40018472011-02-26 01:02:56 +00004514PyObject *
4515PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004516 Py_ssize_t size,
4517 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004518{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004519 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4520}
4521
Antoine Pitrou244651a2009-05-04 18:56:13 +00004522/* The decoder. The only state we preserve is our read position,
4523 * i.e. how many characters we have consumed. So if we end in the
4524 * middle of a shift sequence we have to back off the read position
4525 * and the output to the beginning of the sequence, otherwise we lose
4526 * all the shift state (seen bits, number of bits seen, high
4527 * surrogate). */
4528
Alexander Belopolsky40018472011-02-26 01:02:56 +00004529PyObject *
4530PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004531 Py_ssize_t size,
4532 const char *errors,
4533 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004534{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004535 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004536 Py_ssize_t startinpos;
4537 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004539 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004540 const char *errmsg = "";
4541 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004542 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004543 unsigned int base64bits = 0;
4544 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004545 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004546 PyObject *errorHandler = NULL;
4547 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004548
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004549 if (size == 0) {
4550 if (consumed)
4551 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004552 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004553 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004554
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004555 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004556 _PyUnicodeWriter_Init(&writer);
4557 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004558
4559 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004560 e = s + size;
4561
4562 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004563 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004564 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004565 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004566
Antoine Pitrou244651a2009-05-04 18:56:13 +00004567 if (inShift) { /* in a base-64 section */
4568 if (IS_BASE64(ch)) { /* consume a base-64 character */
4569 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4570 base64bits += 6;
4571 s++;
4572 if (base64bits >= 16) {
4573 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004574 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 base64bits -= 16;
4576 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004577 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004578 if (surrogate) {
4579 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004580 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4581 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004582 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004583 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004585 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004586 }
4587 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004588 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004589 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004590 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004591 }
4592 }
Victor Stinner551ac952011-11-29 22:58:13 +01004593 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004594 /* first surrogate */
4595 surrogate = outCh;
4596 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004597 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004598 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004599 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004600 }
4601 }
4602 }
4603 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004604 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004605 if (base64bits > 0) { /* left-over bits */
4606 if (base64bits >= 6) {
4607 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004608 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004609 errmsg = "partial character in shift sequence";
4610 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004611 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004612 else {
4613 /* Some bits remain; they should be zero */
4614 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004615 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004616 errmsg = "non-zero padding bits in shift sequence";
4617 goto utf7Error;
4618 }
4619 }
4620 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004621 if (surrogate && DECODE_DIRECT(ch)) {
4622 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4623 goto onError;
4624 }
4625 surrogate = 0;
4626 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004627 /* '-' is absorbed; other terminating
4628 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004629 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004630 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004631 }
4632 }
4633 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004634 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004635 s++; /* consume '+' */
4636 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004637 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004638 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004639 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004640 }
4641 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004642 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004643 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004644 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004645 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004646 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004647 }
4648 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004649 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004650 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004651 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004652 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004653 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004654 else {
4655 startinpos = s-starts;
4656 s++;
4657 errmsg = "unexpected special character";
4658 goto utf7Error;
4659 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004660 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004661utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004662 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004663 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004664 errors, &errorHandler,
4665 "utf7", errmsg,
4666 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004667 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004668 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004669 }
4670
Antoine Pitrou244651a2009-05-04 18:56:13 +00004671 /* end of string */
4672
4673 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4674 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004675 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004676 if (surrogate ||
4677 (base64bits >= 6) ||
4678 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004679 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004680 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004681 errors, &errorHandler,
4682 "utf7", "unterminated shift sequence",
4683 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004684 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004685 goto onError;
4686 if (s < e)
4687 goto restart;
4688 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004689 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004690
4691 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004692 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004693 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004694 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004695 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004696 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004697 writer.kind, writer.data, shiftOutStart);
4698 Py_XDECREF(errorHandler);
4699 Py_XDECREF(exc);
4700 _PyUnicodeWriter_Dealloc(&writer);
4701 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004702 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004703 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004704 }
4705 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004706 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004707 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004708 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004709
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004710 Py_XDECREF(errorHandler);
4711 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004712 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004713
Benjamin Peterson29060642009-01-31 22:14:21 +00004714 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004715 Py_XDECREF(errorHandler);
4716 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004717 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004718 return NULL;
4719}
4720
4721
Alexander Belopolsky40018472011-02-26 01:02:56 +00004722PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004723_PyUnicode_EncodeUTF7(PyObject *str,
4724 int base64SetO,
4725 int base64WhiteSpace,
4726 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004727{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004728 int kind;
4729 void *data;
4730 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004731 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004732 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004733 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004734 unsigned int base64bits = 0;
4735 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004736 char * out;
4737 char * start;
4738
Benjamin Petersonbac79492012-01-14 13:34:47 -05004739 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004740 return NULL;
4741 kind = PyUnicode_KIND(str);
4742 data = PyUnicode_DATA(str);
4743 len = PyUnicode_GET_LENGTH(str);
4744
4745 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004746 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004747
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004748 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004749 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004750 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004751 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004752 if (v == NULL)
4753 return NULL;
4754
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004755 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004756 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004757 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004758
Antoine Pitrou244651a2009-05-04 18:56:13 +00004759 if (inShift) {
4760 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4761 /* shifting out */
4762 if (base64bits) { /* output remaining bits */
4763 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4764 base64buffer = 0;
4765 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004766 }
4767 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004768 /* Characters not in the BASE64 set implicitly unshift the sequence
4769 so no '-' is required, except if the character is itself a '-' */
4770 if (IS_BASE64(ch) || ch == '-') {
4771 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004772 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004773 *out++ = (char) ch;
4774 }
4775 else {
4776 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004777 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004778 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004779 else { /* not in a shift sequence */
4780 if (ch == '+') {
4781 *out++ = '+';
4782 *out++ = '-';
4783 }
4784 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4785 *out++ = (char) ch;
4786 }
4787 else {
4788 *out++ = '+';
4789 inShift = 1;
4790 goto encode_char;
4791 }
4792 }
4793 continue;
4794encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004795 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004796 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004797
Antoine Pitrou244651a2009-05-04 18:56:13 +00004798 /* code first surrogate */
4799 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004800 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004801 while (base64bits >= 6) {
4802 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4803 base64bits -= 6;
4804 }
4805 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004806 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004807 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004808 base64bits += 16;
4809 base64buffer = (base64buffer << 16) | ch;
4810 while (base64bits >= 6) {
4811 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4812 base64bits -= 6;
4813 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004814 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004815 if (base64bits)
4816 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4817 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004818 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004819 if (_PyBytes_Resize(&v, out - start) < 0)
4820 return NULL;
4821 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004822}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004823PyObject *
4824PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4825 Py_ssize_t size,
4826 int base64SetO,
4827 int base64WhiteSpace,
4828 const char *errors)
4829{
4830 PyObject *result;
4831 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4832 if (tmp == NULL)
4833 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004834 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004835 base64WhiteSpace, errors);
4836 Py_DECREF(tmp);
4837 return result;
4838}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004839
Antoine Pitrou244651a2009-05-04 18:56:13 +00004840#undef IS_BASE64
4841#undef FROM_BASE64
4842#undef TO_BASE64
4843#undef DECODE_DIRECT
4844#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004845
Guido van Rossumd57fd912000-03-10 22:53:23 +00004846/* --- UTF-8 Codec -------------------------------------------------------- */
4847
Alexander Belopolsky40018472011-02-26 01:02:56 +00004848PyObject *
4849PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004850 Py_ssize_t size,
4851 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004852{
Walter Dörwald69652032004-09-07 20:24:22 +00004853 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4854}
4855
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004856#include "stringlib/asciilib.h"
4857#include "stringlib/codecs.h"
4858#include "stringlib/undef.h"
4859
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004860#include "stringlib/ucs1lib.h"
4861#include "stringlib/codecs.h"
4862#include "stringlib/undef.h"
4863
4864#include "stringlib/ucs2lib.h"
4865#include "stringlib/codecs.h"
4866#include "stringlib/undef.h"
4867
4868#include "stringlib/ucs4lib.h"
4869#include "stringlib/codecs.h"
4870#include "stringlib/undef.h"
4871
Antoine Pitrouab868312009-01-10 15:40:25 +00004872/* Mask to quickly check whether a C 'long' contains a
4873 non-ASCII, UTF8-encoded char. */
4874#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004875# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004876#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004877# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004878#else
4879# error C 'long' size should be either 4 or 8!
4880#endif
4881
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004882static Py_ssize_t
4883ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004884{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004885 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004886 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004887
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004888 /*
4889 * Issue #17237: m68k is a bit different from most architectures in
4890 * that objects do not use "natural alignment" - for example, int and
4891 * long are only aligned at 2-byte boundaries. Therefore the assert()
4892 * won't work; also, tests have shown that skipping the "optimised
4893 * version" will even speed up m68k.
4894 */
4895#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004896#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004897 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4898 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004899 /* Fast path, see in STRINGLIB(utf8_decode) for
4900 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004901 /* Help allocation */
4902 const char *_p = p;
4903 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004904 while (_p < aligned_end) {
4905 unsigned long value = *(const unsigned long *) _p;
4906 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004907 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004908 *((unsigned long *)q) = value;
4909 _p += SIZEOF_LONG;
4910 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004911 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004912 p = _p;
4913 while (p < end) {
4914 if ((unsigned char)*p & 0x80)
4915 break;
4916 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004917 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004918 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004919 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004920#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004921#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004922 while (p < end) {
4923 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4924 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004925 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004926 /* Help allocation */
4927 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004928 while (_p < aligned_end) {
4929 unsigned long value = *(unsigned long *) _p;
4930 if (value & ASCII_CHAR_MASK)
4931 break;
4932 _p += SIZEOF_LONG;
4933 }
4934 p = _p;
4935 if (_p == end)
4936 break;
4937 }
4938 if ((unsigned char)*p & 0x80)
4939 break;
4940 ++p;
4941 }
4942 memcpy(dest, start, p - start);
4943 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004944}
Antoine Pitrouab868312009-01-10 15:40:25 +00004945
Victor Stinner785938e2011-12-11 20:09:03 +01004946PyObject *
4947PyUnicode_DecodeUTF8Stateful(const char *s,
4948 Py_ssize_t size,
4949 const char *errors,
4950 Py_ssize_t *consumed)
4951{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004952 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004953 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004954 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004955
4956 Py_ssize_t startinpos;
4957 Py_ssize_t endinpos;
4958 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004959 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004960 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004961 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004962
4963 if (size == 0) {
4964 if (consumed)
4965 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004966 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004967 }
4968
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004969 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4970 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004971 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004972 *consumed = 1;
4973 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004974 }
4975
Victor Stinner8f674cc2013-04-17 23:02:17 +02004976 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004977 writer.min_length = size;
4978 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004979 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004980
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004981 writer.pos = ascii_decode(s, end, writer.data);
4982 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004983 while (s < end) {
4984 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004985 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004986
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004987 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004988 if (PyUnicode_IS_ASCII(writer.buffer))
4989 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004990 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004991 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004992 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004993 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004994 } else {
4995 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004996 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004997 }
4998
4999 switch (ch) {
5000 case 0:
5001 if (s == end || consumed)
5002 goto End;
5003 errmsg = "unexpected end of data";
5004 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005005 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005006 break;
5007 case 1:
5008 errmsg = "invalid start byte";
5009 startinpos = s - starts;
5010 endinpos = startinpos + 1;
5011 break;
5012 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005013 case 3:
5014 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005015 errmsg = "invalid continuation byte";
5016 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005017 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005018 break;
5019 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005020 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005021 goto onError;
5022 continue;
5023 }
5024
Victor Stinner1d65d912015-10-05 13:43:50 +02005025 if (error_handler == _Py_ERROR_UNKNOWN)
5026 error_handler = get_error_handler(errors);
5027
5028 switch (error_handler) {
5029 case _Py_ERROR_IGNORE:
5030 s += (endinpos - startinpos);
5031 break;
5032
5033 case _Py_ERROR_REPLACE:
5034 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5035 goto onError;
5036 s += (endinpos - startinpos);
5037 break;
5038
5039 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005040 {
5041 Py_ssize_t i;
5042
Victor Stinner1d65d912015-10-05 13:43:50 +02005043 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5044 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005045 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005046 ch = (Py_UCS4)(unsigned char)(starts[i]);
5047 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5048 ch + 0xdc00);
5049 writer.pos++;
5050 }
5051 s += (endinpos - startinpos);
5052 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005053 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005054
5055 default:
5056 if (unicode_decode_call_errorhandler_writer(
5057 errors, &error_handler_obj,
5058 "utf-8", errmsg,
5059 &starts, &end, &startinpos, &endinpos, &exc, &s,
5060 &writer))
5061 goto onError;
5062 }
Victor Stinner785938e2011-12-11 20:09:03 +01005063 }
5064
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005065End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005066 if (consumed)
5067 *consumed = s - starts;
5068
Victor Stinner1d65d912015-10-05 13:43:50 +02005069 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005070 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005071 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005072
5073onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005074 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005075 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005076 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005077 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005078}
5079
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005080#ifdef __APPLE__
5081
5082/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005083 used to decode the command line arguments on Mac OS X.
5084
5085 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005086 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005087
5088wchar_t*
5089_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5090{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005091 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005092 wchar_t *unicode;
5093 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005094
5095 /* Note: size will always be longer than the resulting Unicode
5096 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005097 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005098 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005099 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005100 if (!unicode)
5101 return NULL;
5102
5103 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005104 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005105 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005106 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005107 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005108#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005109 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005110#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005111 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005112#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005113 if (ch > 0xFF) {
5114#if SIZEOF_WCHAR_T == 4
5115 assert(0);
5116#else
5117 assert(Py_UNICODE_IS_SURROGATE(ch));
5118 /* compute and append the two surrogates: */
5119 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5120 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5121#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005122 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005123 else {
5124 if (!ch && s == e)
5125 break;
5126 /* surrogateescape */
5127 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5128 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005129 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005130 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005131 return unicode;
5132}
5133
5134#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005136/* Primary internal function which creates utf8 encoded bytes objects.
5137
5138 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005139 and allocate exactly as much space needed at the end. Else allocate the
5140 maximum possible needed (4 result bytes per Unicode character), and return
5141 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005142*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005143PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005144_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005145{
Victor Stinner6099a032011-12-18 14:22:26 +01005146 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005147 void *data;
5148 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005149
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005150 if (!PyUnicode_Check(unicode)) {
5151 PyErr_BadArgument();
5152 return NULL;
5153 }
5154
5155 if (PyUnicode_READY(unicode) == -1)
5156 return NULL;
5157
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005158 if (PyUnicode_UTF8(unicode))
5159 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5160 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005161
5162 kind = PyUnicode_KIND(unicode);
5163 data = PyUnicode_DATA(unicode);
5164 size = PyUnicode_GET_LENGTH(unicode);
5165
Benjamin Petersonead6b532011-12-20 17:23:42 -06005166 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005167 default:
5168 assert(0);
5169 case PyUnicode_1BYTE_KIND:
5170 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5171 assert(!PyUnicode_IS_ASCII(unicode));
5172 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5173 case PyUnicode_2BYTE_KIND:
5174 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5175 case PyUnicode_4BYTE_KIND:
5176 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005177 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005178}
5179
Alexander Belopolsky40018472011-02-26 01:02:56 +00005180PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005181PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5182 Py_ssize_t size,
5183 const char *errors)
5184{
5185 PyObject *v, *unicode;
5186
5187 unicode = PyUnicode_FromUnicode(s, size);
5188 if (unicode == NULL)
5189 return NULL;
5190 v = _PyUnicode_AsUTF8String(unicode, errors);
5191 Py_DECREF(unicode);
5192 return v;
5193}
5194
5195PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005196PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005197{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005198 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005199}
5200
Walter Dörwald41980ca2007-08-16 21:55:45 +00005201/* --- UTF-32 Codec ------------------------------------------------------- */
5202
5203PyObject *
5204PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005205 Py_ssize_t size,
5206 const char *errors,
5207 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005208{
5209 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5210}
5211
5212PyObject *
5213PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005214 Py_ssize_t size,
5215 const char *errors,
5216 int *byteorder,
5217 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005218{
5219 const char *starts = s;
5220 Py_ssize_t startinpos;
5221 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005222 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005223 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005224 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005225 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005226 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005227 PyObject *errorHandler = NULL;
5228 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005229
Walter Dörwald41980ca2007-08-16 21:55:45 +00005230 q = (unsigned char *)s;
5231 e = q + size;
5232
5233 if (byteorder)
5234 bo = *byteorder;
5235
5236 /* Check for BOM marks (U+FEFF) in the input and adjust current
5237 byte order setting accordingly. In native mode, the leading BOM
5238 mark is skipped, in all other modes, it is copied to the output
5239 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005240 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005241 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005242 if (bom == 0x0000FEFF) {
5243 bo = -1;
5244 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005246 else if (bom == 0xFFFE0000) {
5247 bo = 1;
5248 q += 4;
5249 }
5250 if (byteorder)
5251 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005252 }
5253
Victor Stinnere64322e2012-10-30 23:12:47 +01005254 if (q == e) {
5255 if (consumed)
5256 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005257 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005258 }
5259
Victor Stinnere64322e2012-10-30 23:12:47 +01005260#ifdef WORDS_BIGENDIAN
5261 le = bo < 0;
5262#else
5263 le = bo <= 0;
5264#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005265 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005266
Victor Stinner8f674cc2013-04-17 23:02:17 +02005267 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005268 writer.min_length = (e - q + 3) / 4;
5269 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005270 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005271
Victor Stinnere64322e2012-10-30 23:12:47 +01005272 while (1) {
5273 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005274 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005275
Victor Stinnere64322e2012-10-30 23:12:47 +01005276 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005277 enum PyUnicode_Kind kind = writer.kind;
5278 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005279 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005280 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005281 if (le) {
5282 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005283 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005284 if (ch > maxch)
5285 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005286 if (kind != PyUnicode_1BYTE_KIND &&
5287 Py_UNICODE_IS_SURROGATE(ch))
5288 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005289 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005290 q += 4;
5291 } while (q <= last);
5292 }
5293 else {
5294 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005295 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005296 if (ch > maxch)
5297 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005298 if (kind != PyUnicode_1BYTE_KIND &&
5299 Py_UNICODE_IS_SURROGATE(ch))
5300 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005301 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005302 q += 4;
5303 } while (q <= last);
5304 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005305 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005306 }
5307
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005308 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005309 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005310 startinpos = ((const char *)q) - starts;
5311 endinpos = startinpos + 4;
5312 }
5313 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005314 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005315 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005316 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005317 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005318 startinpos = ((const char *)q) - starts;
5319 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005320 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005321 else {
5322 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005323 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005324 goto onError;
5325 q += 4;
5326 continue;
5327 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005328 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005329 startinpos = ((const char *)q) - starts;
5330 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005331 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005332
5333 /* The remaining input chars are ignored if the callback
5334 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005335 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005337 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005339 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005341 }
5342
Walter Dörwald41980ca2007-08-16 21:55:45 +00005343 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005344 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005345
Walter Dörwald41980ca2007-08-16 21:55:45 +00005346 Py_XDECREF(errorHandler);
5347 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005348 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005349
Benjamin Peterson29060642009-01-31 22:14:21 +00005350 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005351 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005352 Py_XDECREF(errorHandler);
5353 Py_XDECREF(exc);
5354 return NULL;
5355}
5356
5357PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005358_PyUnicode_EncodeUTF32(PyObject *str,
5359 const char *errors,
5360 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005361{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005362 enum PyUnicode_Kind kind;
5363 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005364 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005365 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005366 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005367#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005368 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005369#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005370 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005371#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005372 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005373 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005374 PyObject *errorHandler = NULL;
5375 PyObject *exc = NULL;
5376 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005377
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005378 if (!PyUnicode_Check(str)) {
5379 PyErr_BadArgument();
5380 return NULL;
5381 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005382 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005383 return NULL;
5384 kind = PyUnicode_KIND(str);
5385 data = PyUnicode_DATA(str);
5386 len = PyUnicode_GET_LENGTH(str);
5387
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005388 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005389 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005390 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005391 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005392 if (v == NULL)
5393 return NULL;
5394
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005395 /* output buffer is 4-bytes aligned */
5396 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005397 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005398 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005399 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005400 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005401 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005402
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005403 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005404 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005405 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005406 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005407 else
5408 encoding = "utf-32";
5409
5410 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005411 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5412 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005413 }
5414
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005415 pos = 0;
5416 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005417 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005418
5419 if (kind == PyUnicode_2BYTE_KIND) {
5420 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5421 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005422 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005423 else {
5424 assert(kind == PyUnicode_4BYTE_KIND);
5425 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5426 &out, native_ordering);
5427 }
5428 if (pos == len)
5429 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005430
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005431 rep = unicode_encode_call_errorhandler(
5432 errors, &errorHandler,
5433 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005434 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005435 if (!rep)
5436 goto error;
5437
5438 if (PyBytes_Check(rep)) {
5439 repsize = PyBytes_GET_SIZE(rep);
5440 if (repsize & 3) {
5441 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005442 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005443 "surrogates not allowed");
5444 goto error;
5445 }
5446 moreunits = repsize / 4;
5447 }
5448 else {
5449 assert(PyUnicode_Check(rep));
5450 if (PyUnicode_READY(rep) < 0)
5451 goto error;
5452 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5453 if (!PyUnicode_IS_ASCII(rep)) {
5454 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005455 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005456 "surrogates not allowed");
5457 goto error;
5458 }
5459 }
5460
5461 /* four bytes are reserved for each surrogate */
5462 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005463 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005464 Py_ssize_t morebytes = 4 * (moreunits - 1);
5465 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5466 /* integer overflow */
5467 PyErr_NoMemory();
5468 goto error;
5469 }
5470 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5471 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005472 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005473 }
5474
5475 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005476 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5477 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005478 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005479 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005480 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5481 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005482 }
5483
5484 Py_CLEAR(rep);
5485 }
5486
5487 /* Cut back to size actually needed. This is necessary for, for example,
5488 encoding of a string containing isolated surrogates and the 'ignore'
5489 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005490 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005491 if (nsize != PyBytes_GET_SIZE(v))
5492 _PyBytes_Resize(&v, nsize);
5493 Py_XDECREF(errorHandler);
5494 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005495 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005496 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005497 error:
5498 Py_XDECREF(rep);
5499 Py_XDECREF(errorHandler);
5500 Py_XDECREF(exc);
5501 Py_XDECREF(v);
5502 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005503}
5504
Alexander Belopolsky40018472011-02-26 01:02:56 +00005505PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005506PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5507 Py_ssize_t size,
5508 const char *errors,
5509 int byteorder)
5510{
5511 PyObject *result;
5512 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5513 if (tmp == NULL)
5514 return NULL;
5515 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5516 Py_DECREF(tmp);
5517 return result;
5518}
5519
5520PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005521PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005522{
Victor Stinnerb960b342011-11-20 19:12:52 +01005523 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005524}
5525
Guido van Rossumd57fd912000-03-10 22:53:23 +00005526/* --- UTF-16 Codec ------------------------------------------------------- */
5527
Tim Peters772747b2001-08-09 22:21:55 +00005528PyObject *
5529PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005530 Py_ssize_t size,
5531 const char *errors,
5532 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005533{
Walter Dörwald69652032004-09-07 20:24:22 +00005534 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5535}
5536
5537PyObject *
5538PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005539 Py_ssize_t size,
5540 const char *errors,
5541 int *byteorder,
5542 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005543{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005544 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005545 Py_ssize_t startinpos;
5546 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005547 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005548 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005549 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005550 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005551 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005552 PyObject *errorHandler = NULL;
5553 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005554 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005555
Tim Peters772747b2001-08-09 22:21:55 +00005556 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005557 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005558
5559 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005560 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005561
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005562 /* Check for BOM marks (U+FEFF) in the input and adjust current
5563 byte order setting accordingly. In native mode, the leading BOM
5564 mark is skipped, in all other modes, it is copied to the output
5565 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005566 if (bo == 0 && size >= 2) {
5567 const Py_UCS4 bom = (q[1] << 8) | q[0];
5568 if (bom == 0xFEFF) {
5569 q += 2;
5570 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005571 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005572 else if (bom == 0xFFFE) {
5573 q += 2;
5574 bo = 1;
5575 }
5576 if (byteorder)
5577 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005578 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005579
Antoine Pitrou63065d72012-05-15 23:48:04 +02005580 if (q == e) {
5581 if (consumed)
5582 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005583 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005584 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005585
Christian Heimes743e0cd2012-10-17 23:52:17 +02005586#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005587 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005588 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005589#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005590 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005591 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005592#endif
Tim Peters772747b2001-08-09 22:21:55 +00005593
Antoine Pitrou63065d72012-05-15 23:48:04 +02005594 /* Note: size will always be longer than the resulting Unicode
5595 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005596 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005597 writer.min_length = (e - q + 1) / 2;
5598 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005599 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005600
Antoine Pitrou63065d72012-05-15 23:48:04 +02005601 while (1) {
5602 Py_UCS4 ch = 0;
5603 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005604 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005605 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005606 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005607 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005608 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005609 native_ordering);
5610 else
5611 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005612 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005613 native_ordering);
5614 } else if (kind == PyUnicode_2BYTE_KIND) {
5615 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005616 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005617 native_ordering);
5618 } else {
5619 assert(kind == PyUnicode_4BYTE_KIND);
5620 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005621 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005622 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005623 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005624 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005625
Antoine Pitrou63065d72012-05-15 23:48:04 +02005626 switch (ch)
5627 {
5628 case 0:
5629 /* remaining byte at the end? (size should be even) */
5630 if (q == e || consumed)
5631 goto End;
5632 errmsg = "truncated data";
5633 startinpos = ((const char *)q) - starts;
5634 endinpos = ((const char *)e) - starts;
5635 break;
5636 /* The remaining input chars are ignored if the callback
5637 chooses to skip the input */
5638 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005639 q -= 2;
5640 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005641 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005642 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005643 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005644 endinpos = ((const char *)e) - starts;
5645 break;
5646 case 2:
5647 errmsg = "illegal encoding";
5648 startinpos = ((const char *)q) - 2 - starts;
5649 endinpos = startinpos + 2;
5650 break;
5651 case 3:
5652 errmsg = "illegal UTF-16 surrogate";
5653 startinpos = ((const char *)q) - 4 - starts;
5654 endinpos = startinpos + 2;
5655 break;
5656 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005657 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005658 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005659 continue;
5660 }
5661
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005662 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005663 errors,
5664 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005665 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005666 &starts,
5667 (const char **)&e,
5668 &startinpos,
5669 &endinpos,
5670 &exc,
5671 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005672 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005673 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005674 }
5675
Antoine Pitrou63065d72012-05-15 23:48:04 +02005676End:
Walter Dörwald69652032004-09-07 20:24:22 +00005677 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005678 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005679
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005680 Py_XDECREF(errorHandler);
5681 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005682 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005683
Benjamin Peterson29060642009-01-31 22:14:21 +00005684 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005685 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005686 Py_XDECREF(errorHandler);
5687 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005688 return NULL;
5689}
5690
Tim Peters772747b2001-08-09 22:21:55 +00005691PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005692_PyUnicode_EncodeUTF16(PyObject *str,
5693 const char *errors,
5694 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005695{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005696 enum PyUnicode_Kind kind;
5697 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005698 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005699 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005700 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005701 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005702#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005703 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005704#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005705 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005706#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005707 const char *encoding;
5708 Py_ssize_t nsize, pos;
5709 PyObject *errorHandler = NULL;
5710 PyObject *exc = NULL;
5711 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005712
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005713 if (!PyUnicode_Check(str)) {
5714 PyErr_BadArgument();
5715 return NULL;
5716 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005717 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005718 return NULL;
5719 kind = PyUnicode_KIND(str);
5720 data = PyUnicode_DATA(str);
5721 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005722
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005723 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005724 if (kind == PyUnicode_4BYTE_KIND) {
5725 const Py_UCS4 *in = (const Py_UCS4 *)data;
5726 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005727 while (in < end) {
5728 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005729 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005730 }
5731 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005732 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005733 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005734 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005735 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005736 nsize = len + pairs + (byteorder == 0);
5737 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005738 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005739 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005740 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005741
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005742 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005743 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005744 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005745 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005746 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005747 }
5748 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005749 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005750 }
Tim Peters772747b2001-08-09 22:21:55 +00005751
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005752 if (kind == PyUnicode_1BYTE_KIND) {
5753 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5754 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005755 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005756
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005757 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005758 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005759 }
5760 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005761 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005762 }
5763 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005764 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005765 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005766
5767 pos = 0;
5768 while (pos < len) {
5769 Py_ssize_t repsize, moreunits;
5770
5771 if (kind == PyUnicode_2BYTE_KIND) {
5772 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5773 &out, native_ordering);
5774 }
5775 else {
5776 assert(kind == PyUnicode_4BYTE_KIND);
5777 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5778 &out, native_ordering);
5779 }
5780 if (pos == len)
5781 break;
5782
5783 rep = unicode_encode_call_errorhandler(
5784 errors, &errorHandler,
5785 encoding, "surrogates not allowed",
5786 str, &exc, pos, pos + 1, &pos);
5787 if (!rep)
5788 goto error;
5789
5790 if (PyBytes_Check(rep)) {
5791 repsize = PyBytes_GET_SIZE(rep);
5792 if (repsize & 1) {
5793 raise_encode_exception(&exc, encoding,
5794 str, pos - 1, pos,
5795 "surrogates not allowed");
5796 goto error;
5797 }
5798 moreunits = repsize / 2;
5799 }
5800 else {
5801 assert(PyUnicode_Check(rep));
5802 if (PyUnicode_READY(rep) < 0)
5803 goto error;
5804 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5805 if (!PyUnicode_IS_ASCII(rep)) {
5806 raise_encode_exception(&exc, encoding,
5807 str, pos - 1, pos,
5808 "surrogates not allowed");
5809 goto error;
5810 }
5811 }
5812
5813 /* two bytes are reserved for each surrogate */
5814 if (moreunits > 1) {
5815 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5816 Py_ssize_t morebytes = 2 * (moreunits - 1);
5817 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5818 /* integer overflow */
5819 PyErr_NoMemory();
5820 goto error;
5821 }
5822 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5823 goto error;
5824 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5825 }
5826
5827 if (PyBytes_Check(rep)) {
5828 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5829 out += moreunits;
5830 } else /* rep is unicode */ {
5831 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5832 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5833 &out, native_ordering);
5834 }
5835
5836 Py_CLEAR(rep);
5837 }
5838
5839 /* Cut back to size actually needed. This is necessary for, for example,
5840 encoding of a string containing isolated surrogates and the 'ignore' handler
5841 is used. */
5842 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5843 if (nsize != PyBytes_GET_SIZE(v))
5844 _PyBytes_Resize(&v, nsize);
5845 Py_XDECREF(errorHandler);
5846 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005847 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005848 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005849 error:
5850 Py_XDECREF(rep);
5851 Py_XDECREF(errorHandler);
5852 Py_XDECREF(exc);
5853 Py_XDECREF(v);
5854 return NULL;
5855#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005856}
5857
Alexander Belopolsky40018472011-02-26 01:02:56 +00005858PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005859PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5860 Py_ssize_t size,
5861 const char *errors,
5862 int byteorder)
5863{
5864 PyObject *result;
5865 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5866 if (tmp == NULL)
5867 return NULL;
5868 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5869 Py_DECREF(tmp);
5870 return result;
5871}
5872
5873PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005874PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005876 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877}
5878
5879/* --- Unicode Escape Codec ----------------------------------------------- */
5880
Fredrik Lundh06d12682001-01-24 07:59:11 +00005881static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005882
Alexander Belopolsky40018472011-02-26 01:02:56 +00005883PyObject *
5884PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005885 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005886 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005887{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005888 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005889 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005891 PyObject *errorHandler = NULL;
5892 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005893
Victor Stinner62ec3312016-09-06 17:04:34 -07005894 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005895 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005896 }
5897 /* Escaped strings will always be longer than the resulting
5898 Unicode string, so we start with size here and then reduce the
5899 length after conversion to the true value.
5900 (but if the error callback returns a long replacement string
5901 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005902 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005903 writer.min_length = size;
5904 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5905 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005906 }
5907
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908 end = s + size;
5909 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005910 unsigned char c = (unsigned char) *s++;
5911 Py_UCS4 ch;
5912 int count;
5913 Py_ssize_t startinpos;
5914 Py_ssize_t endinpos;
5915 const char *message;
5916
5917#define WRITE_ASCII_CHAR(ch) \
5918 do { \
5919 assert(ch <= 127); \
5920 assert(writer.pos < writer.size); \
5921 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5922 } while(0)
5923
5924#define WRITE_CHAR(ch) \
5925 do { \
5926 if (ch <= writer.maxchar) { \
5927 assert(writer.pos < writer.size); \
5928 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5929 } \
5930 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5931 goto onError; \
5932 } \
5933 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005934
5935 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005936 if (c != '\\') {
5937 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938 continue;
5939 }
5940
Victor Stinner62ec3312016-09-06 17:04:34 -07005941 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005942 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005943 if (s >= end) {
5944 message = "\\ at end of string";
5945 goto error;
5946 }
5947 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005948
Victor Stinner62ec3312016-09-06 17:04:34 -07005949 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005950 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005951
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005953 case '\n': continue;
5954 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5955 case '\'': WRITE_ASCII_CHAR('\''); continue;
5956 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5957 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005958 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005959 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5960 case 't': WRITE_ASCII_CHAR('\t'); continue;
5961 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5962 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005963 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005964 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005965 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005966 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969 case '0': case '1': case '2': case '3':
5970 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005971 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005972 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005973 ch = (ch<<3) + *s++ - '0';
5974 if (s < end && '0' <= *s && *s <= '7') {
5975 ch = (ch<<3) + *s++ - '0';
5976 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005978 WRITE_CHAR(ch);
5979 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980
Benjamin Peterson29060642009-01-31 22:14:21 +00005981 /* hex escapes */
5982 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005984 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005985 message = "truncated \\xXX escape";
5986 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987
Benjamin Peterson29060642009-01-31 22:14:21 +00005988 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005990 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005991 message = "truncated \\uXXXX escape";
5992 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993
Benjamin Peterson29060642009-01-31 22:14:21 +00005994 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005995 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005996 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005997 message = "truncated \\UXXXXXXXX escape";
5998 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07005999 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006000 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006001 ch <<= 4;
6002 if (c >= '0' && c <= '9') {
6003 ch += c - '0';
6004 }
6005 else if (c >= 'a' && c <= 'f') {
6006 ch += c - ('a' - 10);
6007 }
6008 else if (c >= 'A' && c <= 'F') {
6009 ch += c - ('A' - 10);
6010 }
6011 else {
6012 break;
6013 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006014 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006015 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006016 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006017 }
6018
6019 /* when we get here, ch is a 32-bit unicode character */
6020 if (ch > MAX_UNICODE) {
6021 message = "illegal Unicode character";
6022 goto error;
6023 }
6024
6025 WRITE_CHAR(ch);
6026 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006027
Benjamin Peterson29060642009-01-31 22:14:21 +00006028 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006029 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006030 if (ucnhash_CAPI == NULL) {
6031 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006032 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6033 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006034 if (ucnhash_CAPI == NULL) {
6035 PyErr_SetString(
6036 PyExc_UnicodeError,
6037 "\\N escapes not supported (can't load unicodedata module)"
6038 );
6039 goto onError;
6040 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006041 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006042
6043 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006044 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006045 const char *start = ++s;
6046 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006047 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006048 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006049 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006050 namelen = s - start;
6051 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006052 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006053 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006054 ch = 0xffffffff; /* in case 'getcode' messes up */
6055 if (namelen <= INT_MAX &&
6056 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6057 &ch, 0)) {
6058 assert(ch <= MAX_UNICODE);
6059 WRITE_CHAR(ch);
6060 continue;
6061 }
6062 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006063 }
6064 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006065 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006066
6067 default:
R David Murray110b6fe2016-09-08 15:34:08 -04006068 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6069 "invalid escape sequence '\\%c'", c) < 0)
6070 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006071 WRITE_ASCII_CHAR('\\');
6072 WRITE_CHAR(c);
6073 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006075
6076 error:
6077 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006078 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006079 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006080 errors, &errorHandler,
6081 "unicodeescape", message,
6082 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006083 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006084 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006085 }
6086 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6087 goto onError;
6088 }
6089
6090#undef WRITE_ASCII_CHAR
6091#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006092 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006093
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006094 Py_XDECREF(errorHandler);
6095 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006096 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006097
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006099 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006100 Py_XDECREF(errorHandler);
6101 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006102 return NULL;
6103}
6104
6105/* Return a Unicode-Escape string version of the Unicode object.
6106
6107 If quotes is true, the string is enclosed in u"" or u'' quotes as
6108 appropriate.
6109
6110*/
6111
Alexander Belopolsky40018472011-02-26 01:02:56 +00006112PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006113PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006114{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006115 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006116 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006117 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006118 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006119 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006120 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006121
Ezio Melottie7f90372012-10-05 03:33:31 +03006122 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006123 escape.
6124
Ezio Melottie7f90372012-10-05 03:33:31 +03006125 For UCS1 strings it's '\xxx', 4 bytes per source character.
6126 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6127 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006128 */
6129
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006130 if (!PyUnicode_Check(unicode)) {
6131 PyErr_BadArgument();
6132 return NULL;
6133 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006134 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006135 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006136 }
Victor Stinner358af132015-10-12 22:36:57 +02006137
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006138 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006139 if (len == 0) {
6140 return PyBytes_FromStringAndSize(NULL, 0);
6141 }
6142
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006143 kind = PyUnicode_KIND(unicode);
6144 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006145 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6146 bytes, and 1 byte characters 4. */
6147 expandsize = kind * 2 + 2;
6148 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize) {
6149 return PyErr_NoMemory();
6150 }
6151 repr = PyBytes_FromStringAndSize(NULL, 2 + expandsize * len + 1);
6152 if (repr == NULL) {
6153 return NULL;
6154 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006155
Victor Stinner62ec3312016-09-06 17:04:34 -07006156 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006157 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006158 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006159
Victor Stinner62ec3312016-09-06 17:04:34 -07006160 /* U+0000-U+00ff range */
6161 if (ch < 0x100) {
6162 if (ch >= ' ' && ch < 127) {
6163 if (ch != '\\') {
6164 /* Copy printable US ASCII as-is */
6165 *p++ = (char) ch;
6166 }
6167 /* Escape backslashes */
6168 else {
6169 *p++ = '\\';
6170 *p++ = '\\';
6171 }
6172 }
Victor Stinner358af132015-10-12 22:36:57 +02006173
Victor Stinner62ec3312016-09-06 17:04:34 -07006174 /* Map special whitespace to '\t', \n', '\r' */
6175 else if (ch == '\t') {
6176 *p++ = '\\';
6177 *p++ = 't';
6178 }
6179 else if (ch == '\n') {
6180 *p++ = '\\';
6181 *p++ = 'n';
6182 }
6183 else if (ch == '\r') {
6184 *p++ = '\\';
6185 *p++ = 'r';
6186 }
6187
6188 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6189 else {
6190 *p++ = '\\';
6191 *p++ = 'x';
6192 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6193 *p++ = Py_hexdigits[ch & 0x000F];
6194 }
Tim Petersced69f82003-09-16 20:30:58 +00006195 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006196 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6197 else if (ch < 0x10000) {
6198 /* U+0100-U+ffff */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199 *p++ = '\\';
6200 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006201 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6202 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6203 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6204 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006205 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006206 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6207 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006208
Victor Stinner62ec3312016-09-06 17:04:34 -07006209 /* Make sure that the first two digits are zero */
6210 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006211 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006212 *p++ = 'U';
6213 *p++ = '0';
6214 *p++ = '0';
6215 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6216 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6217 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6218 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6219 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6220 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006221 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006222 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006223
Victor Stinner62ec3312016-09-06 17:04:34 -07006224 assert(p - PyBytes_AS_STRING(repr) > 0);
6225 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6226 return NULL;
6227 }
6228 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006229}
6230
Alexander Belopolsky40018472011-02-26 01:02:56 +00006231PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006232PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6233 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006235 PyObject *result;
6236 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006237 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006238 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006239 }
6240
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006241 result = PyUnicode_AsUnicodeEscapeString(tmp);
6242 Py_DECREF(tmp);
6243 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244}
6245
6246/* --- Raw Unicode Escape Codec ------------------------------------------- */
6247
Alexander Belopolsky40018472011-02-26 01:02:56 +00006248PyObject *
6249PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006250 Py_ssize_t size,
6251 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006252{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006253 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006254 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006255 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006256 PyObject *errorHandler = NULL;
6257 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006258
Victor Stinner62ec3312016-09-06 17:04:34 -07006259 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006260 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006261 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006262
Guido van Rossumd57fd912000-03-10 22:53:23 +00006263 /* Escaped strings will always be longer than the resulting
6264 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006265 length after conversion to the true value. (But decoding error
6266 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006267 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006268 writer.min_length = size;
6269 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6270 goto onError;
6271 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006272
Guido van Rossumd57fd912000-03-10 22:53:23 +00006273 end = s + size;
6274 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006275 unsigned char c = (unsigned char) *s++;
6276 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006277 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006278 Py_ssize_t startinpos;
6279 Py_ssize_t endinpos;
6280 const char *message;
6281
6282#define WRITE_CHAR(ch) \
6283 do { \
6284 if (ch <= writer.maxchar) { \
6285 assert(writer.pos < writer.size); \
6286 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6287 } \
6288 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6289 goto onError; \
6290 } \
6291 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006292
Benjamin Peterson29060642009-01-31 22:14:21 +00006293 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006294 if (c != '\\' || s >= end) {
6295 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006296 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006297 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006298
Victor Stinner62ec3312016-09-06 17:04:34 -07006299 c = (unsigned char) *s++;
6300 if (c == 'u') {
6301 count = 4;
6302 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006303 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006304 else if (c == 'U') {
6305 count = 8;
6306 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006307 }
6308 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006309 assert(writer.pos < writer.size);
6310 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6311 WRITE_CHAR(c);
6312 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006313 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006314 startinpos = s - starts - 2;
6315
6316 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6317 for (ch = 0; count && s < end; ++s, --count) {
6318 c = (unsigned char)*s;
6319 ch <<= 4;
6320 if (c >= '0' && c <= '9') {
6321 ch += c - '0';
6322 }
6323 else if (c >= 'a' && c <= 'f') {
6324 ch += c - ('a' - 10);
6325 }
6326 else if (c >= 'A' && c <= 'F') {
6327 ch += c - ('A' - 10);
6328 }
6329 else {
6330 break;
6331 }
6332 }
6333 if (!count) {
6334 if (ch <= MAX_UNICODE) {
6335 WRITE_CHAR(ch);
6336 continue;
6337 }
6338 message = "\\Uxxxxxxxx out of range";
6339 }
6340
6341 endinpos = s-starts;
6342 writer.min_length = end - s + writer.pos;
6343 if (unicode_decode_call_errorhandler_writer(
6344 errors, &errorHandler,
6345 "rawunicodeescape", message,
6346 &starts, &end, &startinpos, &endinpos, &exc, &s,
6347 &writer)) {
6348 goto onError;
6349 }
6350 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6351 goto onError;
6352 }
6353
6354#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006355 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006356 Py_XDECREF(errorHandler);
6357 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006358 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006359
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006361 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006362 Py_XDECREF(errorHandler);
6363 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006364 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006365
Guido van Rossumd57fd912000-03-10 22:53:23 +00006366}
6367
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006368
Alexander Belopolsky40018472011-02-26 01:02:56 +00006369PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006370PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006371{
Victor Stinner62ec3312016-09-06 17:04:34 -07006372 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006373 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006374 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006375 int kind;
6376 void *data;
6377 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006378
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006379 if (!PyUnicode_Check(unicode)) {
6380 PyErr_BadArgument();
6381 return NULL;
6382 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006383 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006384 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006385 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006386 kind = PyUnicode_KIND(unicode);
6387 data = PyUnicode_DATA(unicode);
6388 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006389 if (kind == PyUnicode_1BYTE_KIND) {
6390 return PyBytes_FromStringAndSize(data, len);
6391 }
Victor Stinner0e368262011-11-10 20:12:49 +01006392
Victor Stinner62ec3312016-09-06 17:04:34 -07006393 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6394 bytes, and 1 byte characters 4. */
6395 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006396
Victor Stinner62ec3312016-09-06 17:04:34 -07006397 if (len > PY_SSIZE_T_MAX / expandsize) {
6398 return PyErr_NoMemory();
6399 }
6400 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6401 if (repr == NULL) {
6402 return NULL;
6403 }
6404 if (len == 0) {
6405 return repr;
6406 }
6407
6408 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006409 for (pos = 0; pos < len; pos++) {
6410 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006411
Victor Stinner62ec3312016-09-06 17:04:34 -07006412 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6413 if (ch < 0x100) {
6414 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006415 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006416 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6417 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006418 *p++ = '\\';
6419 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006420 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6421 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6422 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6423 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006424 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006425 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6426 else {
6427 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6428 *p++ = '\\';
6429 *p++ = 'U';
6430 *p++ = '0';
6431 *p++ = '0';
6432 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6433 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6434 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6435 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6436 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6437 *p++ = Py_hexdigits[ch & 15];
6438 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006439 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006440
Victor Stinner62ec3312016-09-06 17:04:34 -07006441 assert(p > PyBytes_AS_STRING(repr));
6442 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6443 return NULL;
6444 }
6445 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006446}
6447
Alexander Belopolsky40018472011-02-26 01:02:56 +00006448PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006449PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6450 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006451{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006452 PyObject *result;
6453 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6454 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006455 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006456 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6457 Py_DECREF(tmp);
6458 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006459}
6460
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006461/* --- Unicode Internal Codec ------------------------------------------- */
6462
Alexander Belopolsky40018472011-02-26 01:02:56 +00006463PyObject *
6464_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006465 Py_ssize_t size,
6466 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006467{
6468 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006469 Py_ssize_t startinpos;
6470 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006471 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006472 const char *end;
6473 const char *reason;
6474 PyObject *errorHandler = NULL;
6475 PyObject *exc = NULL;
6476
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006477 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006478 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006479 1))
6480 return NULL;
6481
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006482 if (size == 0)
6483 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006484
Victor Stinner8f674cc2013-04-17 23:02:17 +02006485 _PyUnicodeWriter_Init(&writer);
6486 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6487 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006488 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006489 }
6490 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006491
Victor Stinner8f674cc2013-04-17 23:02:17 +02006492 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006493 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006494 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006495 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006496 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006497 endinpos = end-starts;
6498 reason = "truncated input";
6499 goto error;
6500 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006501 /* We copy the raw representation one byte at a time because the
6502 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006503 ((char *) &uch)[0] = s[0];
6504 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006505#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006506 ((char *) &uch)[2] = s[2];
6507 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006508#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006509 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006510#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006511 /* We have to sanity check the raw data, otherwise doom looms for
6512 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006513 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006514 endinpos = s - starts + Py_UNICODE_SIZE;
6515 reason = "illegal code point (> 0x10FFFF)";
6516 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006517 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006518#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006519 s += Py_UNICODE_SIZE;
6520#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006521 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006522 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006523 Py_UNICODE uch2;
6524 ((char *) &uch2)[0] = s[0];
6525 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006526 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006527 {
Victor Stinner551ac952011-11-29 22:58:13 +01006528 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006529 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006530 }
6531 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006532#endif
6533
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006534 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006535 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006536 continue;
6537
6538 error:
6539 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006540 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006541 errors, &errorHandler,
6542 "unicode_internal", reason,
6543 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006544 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006545 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006546 }
6547
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006548 Py_XDECREF(errorHandler);
6549 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006550 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006551
Benjamin Peterson29060642009-01-31 22:14:21 +00006552 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006553 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006554 Py_XDECREF(errorHandler);
6555 Py_XDECREF(exc);
6556 return NULL;
6557}
6558
Guido van Rossumd57fd912000-03-10 22:53:23 +00006559/* --- Latin-1 Codec ------------------------------------------------------ */
6560
Alexander Belopolsky40018472011-02-26 01:02:56 +00006561PyObject *
6562PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006563 Py_ssize_t size,
6564 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006565{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006566 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006567 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006568}
6569
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006570/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006571static void
6572make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006573 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006574 PyObject *unicode,
6575 Py_ssize_t startpos, Py_ssize_t endpos,
6576 const char *reason)
6577{
6578 if (*exceptionObject == NULL) {
6579 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006581 encoding, unicode, startpos, endpos, reason);
6582 }
6583 else {
6584 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6585 goto onError;
6586 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6587 goto onError;
6588 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6589 goto onError;
6590 return;
6591 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006592 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006593 }
6594}
6595
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006596/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006597static void
6598raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006599 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006600 PyObject *unicode,
6601 Py_ssize_t startpos, Py_ssize_t endpos,
6602 const char *reason)
6603{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006604 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006605 encoding, unicode, startpos, endpos, reason);
6606 if (*exceptionObject != NULL)
6607 PyCodec_StrictErrors(*exceptionObject);
6608}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609
6610/* error handling callback helper:
6611 build arguments, call the callback and check the arguments,
6612 put the result into newpos and return the replacement string, which
6613 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006614static PyObject *
6615unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006616 PyObject **errorHandler,
6617 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006618 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006619 Py_ssize_t startpos, Py_ssize_t endpos,
6620 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006621{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006622 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006623 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006624 PyObject *restuple;
6625 PyObject *resunicode;
6626
6627 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006629 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006630 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006631 }
6632
Benjamin Petersonbac79492012-01-14 13:34:47 -05006633 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006634 return NULL;
6635 len = PyUnicode_GET_LENGTH(unicode);
6636
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006637 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006638 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006639 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006640 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006641
6642 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006643 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006645 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006646 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006647 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006648 Py_DECREF(restuple);
6649 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006650 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006651 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006652 &resunicode, newpos)) {
6653 Py_DECREF(restuple);
6654 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006655 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006656 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6657 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6658 Py_DECREF(restuple);
6659 return NULL;
6660 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006661 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006662 *newpos = len + *newpos;
6663 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006664 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 Py_DECREF(restuple);
6666 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006667 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668 Py_INCREF(resunicode);
6669 Py_DECREF(restuple);
6670 return resunicode;
6671}
6672
Alexander Belopolsky40018472011-02-26 01:02:56 +00006673static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006674unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006675 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006676 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006677{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006678 /* input state */
6679 Py_ssize_t pos=0, size;
6680 int kind;
6681 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682 /* pointer into the output */
6683 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006684 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6685 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006686 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006687 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006688 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006689 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006690 /* output object */
6691 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006692
Benjamin Petersonbac79492012-01-14 13:34:47 -05006693 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006694 return NULL;
6695 size = PyUnicode_GET_LENGTH(unicode);
6696 kind = PyUnicode_KIND(unicode);
6697 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006698 /* allocate enough for a simple encoding without
6699 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006700 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006701 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006702
6703 _PyBytesWriter_Init(&writer);
6704 str = _PyBytesWriter_Alloc(&writer, size);
6705 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006706 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006707
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006708 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006709 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006710
Benjamin Peterson29060642009-01-31 22:14:21 +00006711 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006712 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006713 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006714 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006715 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006716 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006717 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006718 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006719 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006720 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006721 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006723
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006724 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006726
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006727 /* Only overallocate the buffer if it's not the last write */
6728 writer.overallocate = (collend < size);
6729
Benjamin Peterson29060642009-01-31 22:14:21 +00006730 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006731 if (error_handler == _Py_ERROR_UNKNOWN)
6732 error_handler = get_error_handler(errors);
6733
6734 switch (error_handler) {
6735 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006736 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006737 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006738
6739 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006740 memset(str, '?', collend - collstart);
6741 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006742 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006743 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006744 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006745 break;
Victor Stinner50149202015-09-22 00:26:54 +02006746
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006747 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006748 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006749 writer.min_size -= (collend - collstart);
6750 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006751 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006752 if (str == NULL)
6753 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006754 pos = collend;
6755 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006756
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006757 case _Py_ERROR_XMLCHARREFREPLACE:
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 = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006761 unicode, collstart, collend);
6762 if (str == NULL)
6763 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006764 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006765 break;
Victor Stinner50149202015-09-22 00:26:54 +02006766
Victor Stinnerc3713e92015-09-29 12:32:13 +02006767 case _Py_ERROR_SURROGATEESCAPE:
6768 for (i = collstart; i < collend; ++i) {
6769 ch = PyUnicode_READ(kind, data, i);
6770 if (ch < 0xdc80 || 0xdcff < ch) {
6771 /* Not a UTF-8b surrogate */
6772 break;
6773 }
6774 *str++ = (char)(ch - 0xdc00);
6775 ++pos;
6776 }
6777 if (i >= collend)
6778 break;
6779 collstart = pos;
6780 assert(collstart != collend);
6781 /* fallback to general error handling */
6782
Benjamin Peterson29060642009-01-31 22:14:21 +00006783 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006784 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6785 encoding, reason, unicode, &exc,
6786 collstart, collend, &newpos);
6787 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006788 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006789
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006790 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006791 writer.min_size -= 1;
6792
Victor Stinner6bd525b2015-10-09 13:10:05 +02006793 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006794 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006795 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006796 PyBytes_AS_STRING(rep),
6797 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006798 if (str == NULL)
6799 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006800 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006801 else {
6802 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006803
Victor Stinner6bd525b2015-10-09 13:10:05 +02006804 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006805 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006806
6807 if (PyUnicode_IS_ASCII(rep)) {
6808 /* Fast path: all characters are smaller than limit */
6809 assert(limit >= 128);
6810 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6811 str = _PyBytesWriter_WriteBytes(&writer, str,
6812 PyUnicode_DATA(rep),
6813 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006814 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006815 else {
6816 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6817
6818 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6819 if (str == NULL)
6820 goto onError;
6821
6822 /* check if there is anything unencodable in the
6823 replacement and copy it to the output */
6824 for (i = 0; repsize-->0; ++i, ++str) {
6825 ch = PyUnicode_READ_CHAR(rep, i);
6826 if (ch >= limit) {
6827 raise_encode_exception(&exc, encoding, unicode,
6828 pos, pos+1, reason);
6829 goto onError;
6830 }
6831 *str = (char)ch;
6832 }
6833 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006834 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006835 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006836 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006837 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006838
6839 /* If overallocation was disabled, ensure that it was the last
6840 write. Otherwise, we missed an optimization */
6841 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006842 }
6843 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006844
Victor Stinner50149202015-09-22 00:26:54 +02006845 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006846 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006847 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006848
6849 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006850 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006851 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006852 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006853 Py_XDECREF(exc);
6854 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006855}
6856
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006857/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006858PyObject *
6859PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006860 Py_ssize_t size,
6861 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006862{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006863 PyObject *result;
6864 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6865 if (unicode == NULL)
6866 return NULL;
6867 result = unicode_encode_ucs1(unicode, errors, 256);
6868 Py_DECREF(unicode);
6869 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006870}
6871
Alexander Belopolsky40018472011-02-26 01:02:56 +00006872PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006873_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006874{
6875 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006876 PyErr_BadArgument();
6877 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006878 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006879 if (PyUnicode_READY(unicode) == -1)
6880 return NULL;
6881 /* Fast path: if it is a one-byte string, construct
6882 bytes object directly. */
6883 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6884 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6885 PyUnicode_GET_LENGTH(unicode));
6886 /* Non-Latin-1 characters present. Defer to above function to
6887 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006888 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006889}
6890
6891PyObject*
6892PyUnicode_AsLatin1String(PyObject *unicode)
6893{
6894 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006895}
6896
6897/* --- 7-bit ASCII Codec -------------------------------------------------- */
6898
Alexander Belopolsky40018472011-02-26 01:02:56 +00006899PyObject *
6900PyUnicode_DecodeASCII(const char *s,
6901 Py_ssize_t size,
6902 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006903{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006904 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006905 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006906 int kind;
6907 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006908 Py_ssize_t startinpos;
6909 Py_ssize_t endinpos;
6910 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006911 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006912 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006913 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006914 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006915
Guido van Rossumd57fd912000-03-10 22:53:23 +00006916 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006917 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006918
Guido van Rossumd57fd912000-03-10 22:53:23 +00006919 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006920 if (size == 1 && (unsigned char)s[0] < 128)
6921 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006922
Victor Stinner8f674cc2013-04-17 23:02:17 +02006923 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006924 writer.min_length = size;
6925 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006926 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006927
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006928 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006929 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006930 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006931 writer.pos = outpos;
6932 if (writer.pos == size)
6933 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006934
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006935 s += writer.pos;
6936 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006937 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006938 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006939 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006940 PyUnicode_WRITE(kind, data, writer.pos, c);
6941 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006942 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006943 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006944 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006945
6946 /* byte outsize range 0x00..0x7f: call the error handler */
6947
6948 if (error_handler == _Py_ERROR_UNKNOWN)
6949 error_handler = get_error_handler(errors);
6950
6951 switch (error_handler)
6952 {
6953 case _Py_ERROR_REPLACE:
6954 case _Py_ERROR_SURROGATEESCAPE:
6955 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006956 but we may switch to UCS2 at the first write */
6957 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6958 goto onError;
6959 kind = writer.kind;
6960 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006961
6962 if (error_handler == _Py_ERROR_REPLACE)
6963 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6964 else
6965 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6966 writer.pos++;
6967 ++s;
6968 break;
6969
6970 case _Py_ERROR_IGNORE:
6971 ++s;
6972 break;
6973
6974 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006975 startinpos = s-starts;
6976 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006977 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006978 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006979 "ascii", "ordinal not in range(128)",
6980 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006981 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006982 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006983 kind = writer.kind;
6984 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006985 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006986 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006987 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006988 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006989 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006990
Benjamin Peterson29060642009-01-31 22:14:21 +00006991 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006992 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006993 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006994 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006995 return NULL;
6996}
6997
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006998/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006999PyObject *
7000PyUnicode_EncodeASCII(const Py_UNICODE *p,
7001 Py_ssize_t size,
7002 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007003{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007004 PyObject *result;
7005 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7006 if (unicode == NULL)
7007 return NULL;
7008 result = unicode_encode_ucs1(unicode, errors, 128);
7009 Py_DECREF(unicode);
7010 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007011}
7012
Alexander Belopolsky40018472011-02-26 01:02:56 +00007013PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007014_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007015{
7016 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007017 PyErr_BadArgument();
7018 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007019 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007020 if (PyUnicode_READY(unicode) == -1)
7021 return NULL;
7022 /* Fast path: if it is an ASCII-only string, construct bytes object
7023 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007024 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007025 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7026 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007027 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007028}
7029
7030PyObject *
7031PyUnicode_AsASCIIString(PyObject *unicode)
7032{
7033 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007034}
7035
Steve Dowercc16be82016-09-08 10:35:16 -07007036#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007037
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007038/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007039
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007040#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007041#define NEED_RETRY
7042#endif
7043
Victor Stinner3a50e702011-10-18 21:21:00 +02007044#ifndef WC_ERR_INVALID_CHARS
7045# define WC_ERR_INVALID_CHARS 0x0080
7046#endif
7047
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007048static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007049code_page_name(UINT code_page, PyObject **obj)
7050{
7051 *obj = NULL;
7052 if (code_page == CP_ACP)
7053 return "mbcs";
7054 if (code_page == CP_UTF7)
7055 return "CP_UTF7";
7056 if (code_page == CP_UTF8)
7057 return "CP_UTF8";
7058
7059 *obj = PyBytes_FromFormat("cp%u", code_page);
7060 if (*obj == NULL)
7061 return NULL;
7062 return PyBytes_AS_STRING(*obj);
7063}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007064
Victor Stinner3a50e702011-10-18 21:21:00 +02007065static DWORD
7066decode_code_page_flags(UINT code_page)
7067{
7068 if (code_page == CP_UTF7) {
7069 /* The CP_UTF7 decoder only supports flags=0 */
7070 return 0;
7071 }
7072 else
7073 return MB_ERR_INVALID_CHARS;
7074}
7075
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007076/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007077 * Decode a byte string from a Windows code page into unicode object in strict
7078 * mode.
7079 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007080 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7081 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007082 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007083static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007084decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007085 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007086 const char *in,
7087 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007088{
Victor Stinner3a50e702011-10-18 21:21:00 +02007089 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007090 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007091 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092
7093 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007094 assert(insize > 0);
7095 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7096 if (outsize <= 0)
7097 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007098
7099 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007100 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007101 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007102 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007103 if (*v == NULL)
7104 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007105 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007106 }
7107 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007108 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007109 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007110 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007111 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007112 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007113 }
7114
7115 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007116 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7117 if (outsize <= 0)
7118 goto error;
7119 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007120
Victor Stinner3a50e702011-10-18 21:21:00 +02007121error:
7122 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7123 return -2;
7124 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007125 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007126}
7127
Victor Stinner3a50e702011-10-18 21:21:00 +02007128/*
7129 * Decode a byte string from a code page into unicode object with an error
7130 * handler.
7131 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007132 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007133 * UnicodeDecodeError exception and returns -1 on error.
7134 */
7135static int
7136decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007137 PyObject **v,
7138 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007139 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007140{
7141 const char *startin = in;
7142 const char *endin = in + size;
7143 const DWORD flags = decode_code_page_flags(code_page);
7144 /* Ideally, we should get reason from FormatMessage. This is the Windows
7145 2000 English version of the message. */
7146 const char *reason = "No mapping for the Unicode character exists "
7147 "in the target code page.";
7148 /* each step cannot decode more than 1 character, but a character can be
7149 represented as a surrogate pair */
7150 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007151 int insize;
7152 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007153 PyObject *errorHandler = NULL;
7154 PyObject *exc = NULL;
7155 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007156 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007157 DWORD err;
7158 int ret = -1;
7159
7160 assert(size > 0);
7161
7162 encoding = code_page_name(code_page, &encoding_obj);
7163 if (encoding == NULL)
7164 return -1;
7165
Victor Stinner7d00cc12014-03-17 23:08:06 +01007166 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007167 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7168 UnicodeDecodeError. */
7169 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7170 if (exc != NULL) {
7171 PyCodec_StrictErrors(exc);
7172 Py_CLEAR(exc);
7173 }
7174 goto error;
7175 }
7176
7177 if (*v == NULL) {
7178 /* Create unicode object */
7179 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7180 PyErr_NoMemory();
7181 goto error;
7182 }
Victor Stinnerab595942011-12-17 04:59:06 +01007183 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007184 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007185 if (*v == NULL)
7186 goto error;
7187 startout = PyUnicode_AS_UNICODE(*v);
7188 }
7189 else {
7190 /* Extend unicode object */
7191 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7192 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7193 PyErr_NoMemory();
7194 goto error;
7195 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007196 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007197 goto error;
7198 startout = PyUnicode_AS_UNICODE(*v) + n;
7199 }
7200
7201 /* Decode the byte string character per character */
7202 out = startout;
7203 while (in < endin)
7204 {
7205 /* Decode a character */
7206 insize = 1;
7207 do
7208 {
7209 outsize = MultiByteToWideChar(code_page, flags,
7210 in, insize,
7211 buffer, Py_ARRAY_LENGTH(buffer));
7212 if (outsize > 0)
7213 break;
7214 err = GetLastError();
7215 if (err != ERROR_NO_UNICODE_TRANSLATION
7216 && err != ERROR_INSUFFICIENT_BUFFER)
7217 {
7218 PyErr_SetFromWindowsErr(0);
7219 goto error;
7220 }
7221 insize++;
7222 }
7223 /* 4=maximum length of a UTF-8 sequence */
7224 while (insize <= 4 && (in + insize) <= endin);
7225
7226 if (outsize <= 0) {
7227 Py_ssize_t startinpos, endinpos, outpos;
7228
Victor Stinner7d00cc12014-03-17 23:08:06 +01007229 /* last character in partial decode? */
7230 if (in + insize >= endin && !final)
7231 break;
7232
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 startinpos = in - startin;
7234 endinpos = startinpos + 1;
7235 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007236 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007237 errors, &errorHandler,
7238 encoding, reason,
7239 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007240 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 {
7242 goto error;
7243 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007244 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 }
7246 else {
7247 in += insize;
7248 memcpy(out, buffer, outsize * sizeof(wchar_t));
7249 out += outsize;
7250 }
7251 }
7252
7253 /* write a NUL character at the end */
7254 *out = 0;
7255
7256 /* Extend unicode object */
7257 outsize = out - startout;
7258 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007259 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007260 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007261 /* (in - startin) <= size and size is an int */
7262 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007263
7264error:
7265 Py_XDECREF(encoding_obj);
7266 Py_XDECREF(errorHandler);
7267 Py_XDECREF(exc);
7268 return ret;
7269}
7270
Victor Stinner3a50e702011-10-18 21:21:00 +02007271static PyObject *
7272decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007273 const char *s, Py_ssize_t size,
7274 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007275{
Victor Stinner76a31a62011-11-04 00:05:13 +01007276 PyObject *v = NULL;
7277 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007278
Victor Stinner3a50e702011-10-18 21:21:00 +02007279 if (code_page < 0) {
7280 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7281 return NULL;
7282 }
7283
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007284 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007285 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007286
Victor Stinner76a31a62011-11-04 00:05:13 +01007287 do
7288 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007289#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007290 if (size > INT_MAX) {
7291 chunk_size = INT_MAX;
7292 final = 0;
7293 done = 0;
7294 }
7295 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007296#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007297 {
7298 chunk_size = (int)size;
7299 final = (consumed == NULL);
7300 done = 1;
7301 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007302
Victor Stinner76a31a62011-11-04 00:05:13 +01007303 if (chunk_size == 0 && done) {
7304 if (v != NULL)
7305 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007306 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007307 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007308
Victor Stinner76a31a62011-11-04 00:05:13 +01007309 converted = decode_code_page_strict(code_page, &v,
7310 s, chunk_size);
7311 if (converted == -2)
7312 converted = decode_code_page_errors(code_page, &v,
7313 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007314 errors, final);
7315 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007316
7317 if (converted < 0) {
7318 Py_XDECREF(v);
7319 return NULL;
7320 }
7321
7322 if (consumed)
7323 *consumed += converted;
7324
7325 s += converted;
7326 size -= converted;
7327 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007328
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007329 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007330}
7331
Alexander Belopolsky40018472011-02-26 01:02:56 +00007332PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007333PyUnicode_DecodeCodePageStateful(int code_page,
7334 const char *s,
7335 Py_ssize_t size,
7336 const char *errors,
7337 Py_ssize_t *consumed)
7338{
7339 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7340}
7341
7342PyObject *
7343PyUnicode_DecodeMBCSStateful(const char *s,
7344 Py_ssize_t size,
7345 const char *errors,
7346 Py_ssize_t *consumed)
7347{
7348 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7349}
7350
7351PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007352PyUnicode_DecodeMBCS(const char *s,
7353 Py_ssize_t size,
7354 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007355{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007356 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7357}
7358
Victor Stinner3a50e702011-10-18 21:21:00 +02007359static DWORD
7360encode_code_page_flags(UINT code_page, const char *errors)
7361{
7362 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007363 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 }
7365 else if (code_page == CP_UTF7) {
7366 /* CP_UTF7 only supports flags=0 */
7367 return 0;
7368 }
7369 else {
7370 if (errors != NULL && strcmp(errors, "replace") == 0)
7371 return 0;
7372 else
7373 return WC_NO_BEST_FIT_CHARS;
7374 }
7375}
7376
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007377/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 * Encode a Unicode string to a Windows code page into a byte string in strict
7379 * mode.
7380 *
7381 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007382 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007383 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007384static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007385encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007386 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007388{
Victor Stinner554f3f02010-06-16 23:33:54 +00007389 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 BOOL *pusedDefaultChar = &usedDefaultChar;
7391 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007392 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007393 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 const DWORD flags = encode_code_page_flags(code_page, NULL);
7395 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007396 /* Create a substring so that we can get the UTF-16 representation
7397 of just the slice under consideration. */
7398 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007399
Martin v. Löwis3d325192011-11-04 18:23:06 +01007400 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007401
Victor Stinner3a50e702011-10-18 21:21:00 +02007402 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007403 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007404 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007405 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007406
Victor Stinner2fc507f2011-11-04 20:06:39 +01007407 substring = PyUnicode_Substring(unicode, offset, offset+len);
7408 if (substring == NULL)
7409 return -1;
7410 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7411 if (p == NULL) {
7412 Py_DECREF(substring);
7413 return -1;
7414 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007415 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007416
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007417 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007419 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 NULL, 0,
7421 NULL, pusedDefaultChar);
7422 if (outsize <= 0)
7423 goto error;
7424 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007425 if (pusedDefaultChar && *pusedDefaultChar) {
7426 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007427 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007428 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007429
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007431 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007433 if (*outbytes == NULL) {
7434 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007435 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007436 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007438 }
7439 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007440 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007441 const Py_ssize_t n = PyBytes_Size(*outbytes);
7442 if (outsize > PY_SSIZE_T_MAX - n) {
7443 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007444 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007445 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007446 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7448 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007450 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007451 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007452 }
7453
7454 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007455 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007456 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 out, outsize,
7458 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007459 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007460 if (outsize <= 0)
7461 goto error;
7462 if (pusedDefaultChar && *pusedDefaultChar)
7463 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007464 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007465
Victor Stinner3a50e702011-10-18 21:21:00 +02007466error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007467 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007468 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7469 return -2;
7470 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007471 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007472}
7473
Victor Stinner3a50e702011-10-18 21:21:00 +02007474/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007475 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007476 * error handler.
7477 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007478 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007479 * -1 on other error.
7480 */
7481static int
7482encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007483 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007484 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007485{
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007487 Py_ssize_t pos = unicode_offset;
7488 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007489 /* Ideally, we should get reason from FormatMessage. This is the Windows
7490 2000 English version of the message. */
7491 const char *reason = "invalid character";
7492 /* 4=maximum length of a UTF-8 sequence */
7493 char buffer[4];
7494 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7495 Py_ssize_t outsize;
7496 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007497 PyObject *errorHandler = NULL;
7498 PyObject *exc = NULL;
7499 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007500 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007501 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007502 PyObject *rep;
7503 int ret = -1;
7504
7505 assert(insize > 0);
7506
7507 encoding = code_page_name(code_page, &encoding_obj);
7508 if (encoding == NULL)
7509 return -1;
7510
7511 if (errors == NULL || strcmp(errors, "strict") == 0) {
7512 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7513 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007514 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007515 if (exc != NULL) {
7516 PyCodec_StrictErrors(exc);
7517 Py_DECREF(exc);
7518 }
7519 Py_XDECREF(encoding_obj);
7520 return -1;
7521 }
7522
7523 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7524 pusedDefaultChar = &usedDefaultChar;
7525 else
7526 pusedDefaultChar = NULL;
7527
7528 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7529 PyErr_NoMemory();
7530 goto error;
7531 }
7532 outsize = insize * Py_ARRAY_LENGTH(buffer);
7533
7534 if (*outbytes == NULL) {
7535 /* Create string object */
7536 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7537 if (*outbytes == NULL)
7538 goto error;
7539 out = PyBytes_AS_STRING(*outbytes);
7540 }
7541 else {
7542 /* Extend string object */
7543 Py_ssize_t n = PyBytes_Size(*outbytes);
7544 if (n > PY_SSIZE_T_MAX - outsize) {
7545 PyErr_NoMemory();
7546 goto error;
7547 }
7548 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7549 goto error;
7550 out = PyBytes_AS_STRING(*outbytes) + n;
7551 }
7552
7553 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007554 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007555 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007556 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7557 wchar_t chars[2];
7558 int charsize;
7559 if (ch < 0x10000) {
7560 chars[0] = (wchar_t)ch;
7561 charsize = 1;
7562 }
7563 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007564 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7565 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007566 charsize = 2;
7567 }
7568
Victor Stinner3a50e702011-10-18 21:21:00 +02007569 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007570 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007571 buffer, Py_ARRAY_LENGTH(buffer),
7572 NULL, pusedDefaultChar);
7573 if (outsize > 0) {
7574 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7575 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007576 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007577 memcpy(out, buffer, outsize);
7578 out += outsize;
7579 continue;
7580 }
7581 }
7582 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7583 PyErr_SetFromWindowsErr(0);
7584 goto error;
7585 }
7586
Victor Stinner3a50e702011-10-18 21:21:00 +02007587 rep = unicode_encode_call_errorhandler(
7588 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007589 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007590 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007591 if (rep == NULL)
7592 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007593 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007594
7595 if (PyBytes_Check(rep)) {
7596 outsize = PyBytes_GET_SIZE(rep);
7597 if (outsize != 1) {
7598 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7599 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7600 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7601 Py_DECREF(rep);
7602 goto error;
7603 }
7604 out = PyBytes_AS_STRING(*outbytes) + offset;
7605 }
7606 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7607 out += outsize;
7608 }
7609 else {
7610 Py_ssize_t i;
7611 enum PyUnicode_Kind kind;
7612 void *data;
7613
Benjamin Petersonbac79492012-01-14 13:34:47 -05007614 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007615 Py_DECREF(rep);
7616 goto error;
7617 }
7618
7619 outsize = PyUnicode_GET_LENGTH(rep);
7620 if (outsize != 1) {
7621 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7622 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7623 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7624 Py_DECREF(rep);
7625 goto error;
7626 }
7627 out = PyBytes_AS_STRING(*outbytes) + offset;
7628 }
7629 kind = PyUnicode_KIND(rep);
7630 data = PyUnicode_DATA(rep);
7631 for (i=0; i < outsize; i++) {
7632 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7633 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007634 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007635 encoding, unicode,
7636 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007637 "unable to encode error handler result to ASCII");
7638 Py_DECREF(rep);
7639 goto error;
7640 }
7641 *out = (unsigned char)ch;
7642 out++;
7643 }
7644 }
7645 Py_DECREF(rep);
7646 }
7647 /* write a NUL byte */
7648 *out = 0;
7649 outsize = out - PyBytes_AS_STRING(*outbytes);
7650 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7651 if (_PyBytes_Resize(outbytes, outsize) < 0)
7652 goto error;
7653 ret = 0;
7654
7655error:
7656 Py_XDECREF(encoding_obj);
7657 Py_XDECREF(errorHandler);
7658 Py_XDECREF(exc);
7659 return ret;
7660}
7661
Victor Stinner3a50e702011-10-18 21:21:00 +02007662static PyObject *
7663encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007664 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007665 const char *errors)
7666{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007667 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007668 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007669 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007670 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007671
Victor Stinner29dacf22015-01-26 16:41:32 +01007672 if (!PyUnicode_Check(unicode)) {
7673 PyErr_BadArgument();
7674 return NULL;
7675 }
7676
Benjamin Petersonbac79492012-01-14 13:34:47 -05007677 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007678 return NULL;
7679 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007680
Victor Stinner3a50e702011-10-18 21:21:00 +02007681 if (code_page < 0) {
7682 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7683 return NULL;
7684 }
7685
Martin v. Löwis3d325192011-11-04 18:23:06 +01007686 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007687 return PyBytes_FromStringAndSize(NULL, 0);
7688
Victor Stinner7581cef2011-11-03 22:32:33 +01007689 offset = 0;
7690 do
7691 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007692#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007693 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007694 chunks. */
7695 if (len > INT_MAX/2) {
7696 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007697 done = 0;
7698 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007699 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007700#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007701 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007702 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007703 done = 1;
7704 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007705
Victor Stinner76a31a62011-11-04 00:05:13 +01007706 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007707 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007708 errors);
7709 if (ret == -2)
7710 ret = encode_code_page_errors(code_page, &outbytes,
7711 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007712 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007713 if (ret < 0) {
7714 Py_XDECREF(outbytes);
7715 return NULL;
7716 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007717
Victor Stinner7581cef2011-11-03 22:32:33 +01007718 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007719 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007720 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007721
Victor Stinner3a50e702011-10-18 21:21:00 +02007722 return outbytes;
7723}
7724
7725PyObject *
7726PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7727 Py_ssize_t size,
7728 const char *errors)
7729{
Victor Stinner7581cef2011-11-03 22:32:33 +01007730 PyObject *unicode, *res;
7731 unicode = PyUnicode_FromUnicode(p, size);
7732 if (unicode == NULL)
7733 return NULL;
7734 res = encode_code_page(CP_ACP, unicode, errors);
7735 Py_DECREF(unicode);
7736 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007737}
7738
7739PyObject *
7740PyUnicode_EncodeCodePage(int code_page,
7741 PyObject *unicode,
7742 const char *errors)
7743{
Victor Stinner7581cef2011-11-03 22:32:33 +01007744 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007745}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007746
Alexander Belopolsky40018472011-02-26 01:02:56 +00007747PyObject *
7748PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007749{
Victor Stinner7581cef2011-11-03 22:32:33 +01007750 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007751}
7752
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007753#undef NEED_RETRY
7754
Steve Dowercc16be82016-09-08 10:35:16 -07007755#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007756
Guido van Rossumd57fd912000-03-10 22:53:23 +00007757/* --- Character Mapping Codec -------------------------------------------- */
7758
Victor Stinnerfb161b12013-04-18 01:44:27 +02007759static int
7760charmap_decode_string(const char *s,
7761 Py_ssize_t size,
7762 PyObject *mapping,
7763 const char *errors,
7764 _PyUnicodeWriter *writer)
7765{
7766 const char *starts = s;
7767 const char *e;
7768 Py_ssize_t startinpos, endinpos;
7769 PyObject *errorHandler = NULL, *exc = NULL;
7770 Py_ssize_t maplen;
7771 enum PyUnicode_Kind mapkind;
7772 void *mapdata;
7773 Py_UCS4 x;
7774 unsigned char ch;
7775
7776 if (PyUnicode_READY(mapping) == -1)
7777 return -1;
7778
7779 maplen = PyUnicode_GET_LENGTH(mapping);
7780 mapdata = PyUnicode_DATA(mapping);
7781 mapkind = PyUnicode_KIND(mapping);
7782
7783 e = s + size;
7784
7785 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7786 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7787 * is disabled in encoding aliases, latin1 is preferred because
7788 * its implementation is faster. */
7789 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7790 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7791 Py_UCS4 maxchar = writer->maxchar;
7792
7793 assert (writer->kind == PyUnicode_1BYTE_KIND);
7794 while (s < e) {
7795 ch = *s;
7796 x = mapdata_ucs1[ch];
7797 if (x > maxchar) {
7798 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7799 goto onError;
7800 maxchar = writer->maxchar;
7801 outdata = (Py_UCS1 *)writer->data;
7802 }
7803 outdata[writer->pos] = x;
7804 writer->pos++;
7805 ++s;
7806 }
7807 return 0;
7808 }
7809
7810 while (s < e) {
7811 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7812 enum PyUnicode_Kind outkind = writer->kind;
7813 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7814 if (outkind == PyUnicode_1BYTE_KIND) {
7815 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7816 Py_UCS4 maxchar = writer->maxchar;
7817 while (s < e) {
7818 ch = *s;
7819 x = mapdata_ucs2[ch];
7820 if (x > maxchar)
7821 goto Error;
7822 outdata[writer->pos] = x;
7823 writer->pos++;
7824 ++s;
7825 }
7826 break;
7827 }
7828 else if (outkind == PyUnicode_2BYTE_KIND) {
7829 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7830 while (s < e) {
7831 ch = *s;
7832 x = mapdata_ucs2[ch];
7833 if (x == 0xFFFE)
7834 goto Error;
7835 outdata[writer->pos] = x;
7836 writer->pos++;
7837 ++s;
7838 }
7839 break;
7840 }
7841 }
7842 ch = *s;
7843
7844 if (ch < maplen)
7845 x = PyUnicode_READ(mapkind, mapdata, ch);
7846 else
7847 x = 0xfffe; /* invalid value */
7848Error:
7849 if (x == 0xfffe)
7850 {
7851 /* undefined mapping */
7852 startinpos = s-starts;
7853 endinpos = startinpos+1;
7854 if (unicode_decode_call_errorhandler_writer(
7855 errors, &errorHandler,
7856 "charmap", "character maps to <undefined>",
7857 &starts, &e, &startinpos, &endinpos, &exc, &s,
7858 writer)) {
7859 goto onError;
7860 }
7861 continue;
7862 }
7863
7864 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7865 goto onError;
7866 ++s;
7867 }
7868 Py_XDECREF(errorHandler);
7869 Py_XDECREF(exc);
7870 return 0;
7871
7872onError:
7873 Py_XDECREF(errorHandler);
7874 Py_XDECREF(exc);
7875 return -1;
7876}
7877
7878static int
7879charmap_decode_mapping(const char *s,
7880 Py_ssize_t size,
7881 PyObject *mapping,
7882 const char *errors,
7883 _PyUnicodeWriter *writer)
7884{
7885 const char *starts = s;
7886 const char *e;
7887 Py_ssize_t startinpos, endinpos;
7888 PyObject *errorHandler = NULL, *exc = NULL;
7889 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007890 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007891
7892 e = s + size;
7893
7894 while (s < e) {
7895 ch = *s;
7896
7897 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7898 key = PyLong_FromLong((long)ch);
7899 if (key == NULL)
7900 goto onError;
7901
7902 item = PyObject_GetItem(mapping, key);
7903 Py_DECREF(key);
7904 if (item == NULL) {
7905 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7906 /* No mapping found means: mapping is undefined. */
7907 PyErr_Clear();
7908 goto Undefined;
7909 } else
7910 goto onError;
7911 }
7912
7913 /* Apply mapping */
7914 if (item == Py_None)
7915 goto Undefined;
7916 if (PyLong_Check(item)) {
7917 long value = PyLong_AS_LONG(item);
7918 if (value == 0xFFFE)
7919 goto Undefined;
7920 if (value < 0 || value > MAX_UNICODE) {
7921 PyErr_Format(PyExc_TypeError,
7922 "character mapping must be in range(0x%lx)",
7923 (unsigned long)MAX_UNICODE + 1);
7924 goto onError;
7925 }
7926
7927 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7928 goto onError;
7929 }
7930 else if (PyUnicode_Check(item)) {
7931 if (PyUnicode_READY(item) == -1)
7932 goto onError;
7933 if (PyUnicode_GET_LENGTH(item) == 1) {
7934 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7935 if (value == 0xFFFE)
7936 goto Undefined;
7937 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7938 goto onError;
7939 }
7940 else {
7941 writer->overallocate = 1;
7942 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7943 goto onError;
7944 }
7945 }
7946 else {
7947 /* wrong return value */
7948 PyErr_SetString(PyExc_TypeError,
7949 "character mapping must return integer, None or str");
7950 goto onError;
7951 }
7952 Py_CLEAR(item);
7953 ++s;
7954 continue;
7955
7956Undefined:
7957 /* undefined mapping */
7958 Py_CLEAR(item);
7959 startinpos = s-starts;
7960 endinpos = startinpos+1;
7961 if (unicode_decode_call_errorhandler_writer(
7962 errors, &errorHandler,
7963 "charmap", "character maps to <undefined>",
7964 &starts, &e, &startinpos, &endinpos, &exc, &s,
7965 writer)) {
7966 goto onError;
7967 }
7968 }
7969 Py_XDECREF(errorHandler);
7970 Py_XDECREF(exc);
7971 return 0;
7972
7973onError:
7974 Py_XDECREF(item);
7975 Py_XDECREF(errorHandler);
7976 Py_XDECREF(exc);
7977 return -1;
7978}
7979
Alexander Belopolsky40018472011-02-26 01:02:56 +00007980PyObject *
7981PyUnicode_DecodeCharmap(const char *s,
7982 Py_ssize_t size,
7983 PyObject *mapping,
7984 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007985{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007986 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007987
Guido van Rossumd57fd912000-03-10 22:53:23 +00007988 /* Default to Latin-1 */
7989 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007990 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007991
Guido van Rossumd57fd912000-03-10 22:53:23 +00007992 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007993 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007994 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007995 writer.min_length = size;
7996 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007997 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007998
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007999 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008000 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8001 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008002 }
8003 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008004 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8005 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008006 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008007 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008008
Benjamin Peterson29060642009-01-31 22:14:21 +00008009 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008010 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008011 return NULL;
8012}
8013
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008014/* Charmap encoding: the lookup table */
8015
Alexander Belopolsky40018472011-02-26 01:02:56 +00008016struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008017 PyObject_HEAD
8018 unsigned char level1[32];
8019 int count2, count3;
8020 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008021};
8022
8023static PyObject*
8024encoding_map_size(PyObject *obj, PyObject* args)
8025{
8026 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008027 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008029}
8030
8031static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008032 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 PyDoc_STR("Return the size (in bytes) of this object") },
8034 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008035};
8036
8037static void
8038encoding_map_dealloc(PyObject* o)
8039{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008040 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008041}
8042
8043static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008044 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008045 "EncodingMap", /*tp_name*/
8046 sizeof(struct encoding_map), /*tp_basicsize*/
8047 0, /*tp_itemsize*/
8048 /* methods */
8049 encoding_map_dealloc, /*tp_dealloc*/
8050 0, /*tp_print*/
8051 0, /*tp_getattr*/
8052 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008053 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008054 0, /*tp_repr*/
8055 0, /*tp_as_number*/
8056 0, /*tp_as_sequence*/
8057 0, /*tp_as_mapping*/
8058 0, /*tp_hash*/
8059 0, /*tp_call*/
8060 0, /*tp_str*/
8061 0, /*tp_getattro*/
8062 0, /*tp_setattro*/
8063 0, /*tp_as_buffer*/
8064 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8065 0, /*tp_doc*/
8066 0, /*tp_traverse*/
8067 0, /*tp_clear*/
8068 0, /*tp_richcompare*/
8069 0, /*tp_weaklistoffset*/
8070 0, /*tp_iter*/
8071 0, /*tp_iternext*/
8072 encoding_map_methods, /*tp_methods*/
8073 0, /*tp_members*/
8074 0, /*tp_getset*/
8075 0, /*tp_base*/
8076 0, /*tp_dict*/
8077 0, /*tp_descr_get*/
8078 0, /*tp_descr_set*/
8079 0, /*tp_dictoffset*/
8080 0, /*tp_init*/
8081 0, /*tp_alloc*/
8082 0, /*tp_new*/
8083 0, /*tp_free*/
8084 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008085};
8086
8087PyObject*
8088PyUnicode_BuildEncodingMap(PyObject* string)
8089{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008090 PyObject *result;
8091 struct encoding_map *mresult;
8092 int i;
8093 int need_dict = 0;
8094 unsigned char level1[32];
8095 unsigned char level2[512];
8096 unsigned char *mlevel1, *mlevel2, *mlevel3;
8097 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008098 int kind;
8099 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008100 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008101 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008102
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008103 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008104 PyErr_BadArgument();
8105 return NULL;
8106 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008107 kind = PyUnicode_KIND(string);
8108 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008109 length = PyUnicode_GET_LENGTH(string);
8110 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008111 memset(level1, 0xFF, sizeof level1);
8112 memset(level2, 0xFF, sizeof level2);
8113
8114 /* If there isn't a one-to-one mapping of NULL to \0,
8115 or if there are non-BMP characters, we need to use
8116 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008117 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008118 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008119 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008120 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008121 ch = PyUnicode_READ(kind, data, i);
8122 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 need_dict = 1;
8124 break;
8125 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008126 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008127 /* unmapped character */
8128 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008129 l1 = ch >> 11;
8130 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008131 if (level1[l1] == 0xFF)
8132 level1[l1] = count2++;
8133 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008134 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008135 }
8136
8137 if (count2 >= 0xFF || count3 >= 0xFF)
8138 need_dict = 1;
8139
8140 if (need_dict) {
8141 PyObject *result = PyDict_New();
8142 PyObject *key, *value;
8143 if (!result)
8144 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008145 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008146 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008147 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008148 if (!key || !value)
8149 goto failed1;
8150 if (PyDict_SetItem(result, key, value) == -1)
8151 goto failed1;
8152 Py_DECREF(key);
8153 Py_DECREF(value);
8154 }
8155 return result;
8156 failed1:
8157 Py_XDECREF(key);
8158 Py_XDECREF(value);
8159 Py_DECREF(result);
8160 return NULL;
8161 }
8162
8163 /* Create a three-level trie */
8164 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8165 16*count2 + 128*count3 - 1);
8166 if (!result)
8167 return PyErr_NoMemory();
8168 PyObject_Init(result, &EncodingMapType);
8169 mresult = (struct encoding_map*)result;
8170 mresult->count2 = count2;
8171 mresult->count3 = count3;
8172 mlevel1 = mresult->level1;
8173 mlevel2 = mresult->level23;
8174 mlevel3 = mresult->level23 + 16*count2;
8175 memcpy(mlevel1, level1, 32);
8176 memset(mlevel2, 0xFF, 16*count2);
8177 memset(mlevel3, 0, 128*count3);
8178 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008179 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008180 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008181 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8182 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008183 /* unmapped character */
8184 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008185 o1 = ch>>11;
8186 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008187 i2 = 16*mlevel1[o1] + o2;
8188 if (mlevel2[i2] == 0xFF)
8189 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008190 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008191 i3 = 128*mlevel2[i2] + o3;
8192 mlevel3[i3] = i;
8193 }
8194 return result;
8195}
8196
8197static int
Victor Stinner22168992011-11-20 17:09:18 +01008198encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008199{
8200 struct encoding_map *map = (struct encoding_map*)mapping;
8201 int l1 = c>>11;
8202 int l2 = (c>>7) & 0xF;
8203 int l3 = c & 0x7F;
8204 int i;
8205
Victor Stinner22168992011-11-20 17:09:18 +01008206 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008207 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008208 if (c == 0)
8209 return 0;
8210 /* level 1*/
8211 i = map->level1[l1];
8212 if (i == 0xFF) {
8213 return -1;
8214 }
8215 /* level 2*/
8216 i = map->level23[16*i+l2];
8217 if (i == 0xFF) {
8218 return -1;
8219 }
8220 /* level 3 */
8221 i = map->level23[16*map->count2 + 128*i + l3];
8222 if (i == 0) {
8223 return -1;
8224 }
8225 return i;
8226}
8227
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008228/* Lookup the character ch in the mapping. If the character
8229 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008230 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008231static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008232charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008233{
Christian Heimes217cfd12007-12-02 14:31:20 +00008234 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008235 PyObject *x;
8236
8237 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008239 x = PyObject_GetItem(mapping, w);
8240 Py_DECREF(w);
8241 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8243 /* No mapping found means: mapping is undefined. */
8244 PyErr_Clear();
8245 x = Py_None;
8246 Py_INCREF(x);
8247 return x;
8248 } else
8249 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008250 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008251 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008253 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 long value = PyLong_AS_LONG(x);
8255 if (value < 0 || value > 255) {
8256 PyErr_SetString(PyExc_TypeError,
8257 "character mapping must be in range(256)");
8258 Py_DECREF(x);
8259 return NULL;
8260 }
8261 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008262 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008263 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008265 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008266 /* wrong return value */
8267 PyErr_Format(PyExc_TypeError,
8268 "character mapping must return integer, bytes or None, not %.400s",
8269 x->ob_type->tp_name);
8270 Py_DECREF(x);
8271 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008272 }
8273}
8274
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008275static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008276charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008277{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008278 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8279 /* exponentially overallocate to minimize reallocations */
8280 if (requiredsize < 2*outsize)
8281 requiredsize = 2*outsize;
8282 if (_PyBytes_Resize(outobj, requiredsize))
8283 return -1;
8284 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008285}
8286
Benjamin Peterson14339b62009-01-31 16:36:08 +00008287typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008289} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008291 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008292 space is available. Return a new reference to the object that
8293 was put in the output buffer, or Py_None, if the mapping was undefined
8294 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008295 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008296static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008297charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008298 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008299{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008300 PyObject *rep;
8301 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008302 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008303
Christian Heimes90aa7642007-12-19 02:45:37 +00008304 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008305 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008307 if (res == -1)
8308 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 if (outsize<requiredsize)
8310 if (charmapencode_resize(outobj, outpos, requiredsize))
8311 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008312 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008313 outstart[(*outpos)++] = (char)res;
8314 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008315 }
8316
8317 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008318 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008320 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 Py_DECREF(rep);
8322 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008323 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008324 if (PyLong_Check(rep)) {
8325 Py_ssize_t requiredsize = *outpos+1;
8326 if (outsize<requiredsize)
8327 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8328 Py_DECREF(rep);
8329 return enc_EXCEPTION;
8330 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008331 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008332 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008333 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 else {
8335 const char *repchars = PyBytes_AS_STRING(rep);
8336 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8337 Py_ssize_t requiredsize = *outpos+repsize;
8338 if (outsize<requiredsize)
8339 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8340 Py_DECREF(rep);
8341 return enc_EXCEPTION;
8342 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008343 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 memcpy(outstart + *outpos, repchars, repsize);
8345 *outpos += repsize;
8346 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008347 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008348 Py_DECREF(rep);
8349 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350}
8351
8352/* handle an error in PyUnicode_EncodeCharmap
8353 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008354static int
8355charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008356 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008358 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008359 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360{
8361 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008362 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008363 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008364 enum PyUnicode_Kind kind;
8365 void *data;
8366 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008368 Py_ssize_t collstartpos = *inpos;
8369 Py_ssize_t collendpos = *inpos+1;
8370 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371 char *encoding = "charmap";
8372 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008373 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008374 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008375 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008376
Benjamin Petersonbac79492012-01-14 13:34:47 -05008377 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008378 return -1;
8379 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 /* find all unencodable characters */
8381 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008382 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008383 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008384 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008385 val = encoding_map_lookup(ch, mapping);
8386 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 break;
8388 ++collendpos;
8389 continue;
8390 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008391
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008392 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8393 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 if (rep==NULL)
8395 return -1;
8396 else if (rep!=Py_None) {
8397 Py_DECREF(rep);
8398 break;
8399 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008400 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402 }
8403 /* cache callback name lookup
8404 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008405 if (*error_handler == _Py_ERROR_UNKNOWN)
8406 *error_handler = get_error_handler(errors);
8407
8408 switch (*error_handler) {
8409 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008410 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008411 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008412
8413 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008414 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 x = charmapencode_output('?', mapping, res, respos);
8416 if (x==enc_EXCEPTION) {
8417 return -1;
8418 }
8419 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008420 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 return -1;
8422 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008423 }
8424 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008425 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008426 *inpos = collendpos;
8427 break;
Victor Stinner50149202015-09-22 00:26:54 +02008428
8429 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008430 /* generate replacement (temporarily (mis)uses p) */
8431 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 char buffer[2+29+1+1];
8433 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008434 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008435 for (cp = buffer; *cp; ++cp) {
8436 x = charmapencode_output(*cp, mapping, res, respos);
8437 if (x==enc_EXCEPTION)
8438 return -1;
8439 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008440 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 return -1;
8442 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008443 }
8444 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008445 *inpos = collendpos;
8446 break;
Victor Stinner50149202015-09-22 00:26:54 +02008447
Benjamin Peterson14339b62009-01-31 16:36:08 +00008448 default:
Victor Stinner50149202015-09-22 00:26:54 +02008449 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008450 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008452 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008454 if (PyBytes_Check(repunicode)) {
8455 /* Directly copy bytes result to output. */
8456 Py_ssize_t outsize = PyBytes_Size(*res);
8457 Py_ssize_t requiredsize;
8458 repsize = PyBytes_Size(repunicode);
8459 requiredsize = *respos + repsize;
8460 if (requiredsize > outsize)
8461 /* Make room for all additional bytes. */
8462 if (charmapencode_resize(res, respos, requiredsize)) {
8463 Py_DECREF(repunicode);
8464 return -1;
8465 }
8466 memcpy(PyBytes_AsString(*res) + *respos,
8467 PyBytes_AsString(repunicode), repsize);
8468 *respos += repsize;
8469 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008470 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008471 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008472 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008473 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008474 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008475 Py_DECREF(repunicode);
8476 return -1;
8477 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008478 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008479 data = PyUnicode_DATA(repunicode);
8480 kind = PyUnicode_KIND(repunicode);
8481 for (index = 0; index < repsize; index++) {
8482 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8483 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008485 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 return -1;
8487 }
8488 else if (x==enc_FAILED) {
8489 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008490 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 return -1;
8492 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008493 }
8494 *inpos = newpos;
8495 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 }
8497 return 0;
8498}
8499
Alexander Belopolsky40018472011-02-26 01:02:56 +00008500PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008501_PyUnicode_EncodeCharmap(PyObject *unicode,
8502 PyObject *mapping,
8503 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008504{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008505 /* output object */
8506 PyObject *res = NULL;
8507 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008508 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008509 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008510 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008511 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008512 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008513 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008514 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008515 void *data;
8516 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008517
Benjamin Petersonbac79492012-01-14 13:34:47 -05008518 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008519 return NULL;
8520 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008521 data = PyUnicode_DATA(unicode);
8522 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008523
Guido van Rossumd57fd912000-03-10 22:53:23 +00008524 /* Default to Latin-1 */
8525 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008526 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008527
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008528 /* allocate enough for a simple encoding without
8529 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008530 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008531 if (res == NULL)
8532 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008533 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008535
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008536 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008537 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008539 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 if (x==enc_EXCEPTION) /* error */
8541 goto onError;
8542 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008543 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008544 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008545 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008546 &res, &respos)) {
8547 goto onError;
8548 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008549 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 else
8551 /* done with this character => adjust input position */
8552 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008553 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008554
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008555 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008556 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008557 if (_PyBytes_Resize(&res, respos) < 0)
8558 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008559
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008560 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008561 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008562 return res;
8563
Benjamin Peterson29060642009-01-31 22:14:21 +00008564 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565 Py_XDECREF(res);
8566 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008567 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008568 return NULL;
8569}
8570
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008571/* Deprecated */
8572PyObject *
8573PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8574 Py_ssize_t size,
8575 PyObject *mapping,
8576 const char *errors)
8577{
8578 PyObject *result;
8579 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8580 if (unicode == NULL)
8581 return NULL;
8582 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8583 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008584 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008585}
8586
Alexander Belopolsky40018472011-02-26 01:02:56 +00008587PyObject *
8588PyUnicode_AsCharmapString(PyObject *unicode,
8589 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008590{
8591 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 PyErr_BadArgument();
8593 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008594 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008595 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008596}
8597
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008598/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008599static void
8600make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008601 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008602 Py_ssize_t startpos, Py_ssize_t endpos,
8603 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008604{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008605 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606 *exceptionObject = _PyUnicodeTranslateError_Create(
8607 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008608 }
8609 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008610 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8611 goto onError;
8612 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8613 goto onError;
8614 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8615 goto onError;
8616 return;
8617 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008618 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008619 }
8620}
8621
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008622/* error handling callback helper:
8623 build arguments, call the callback and check the arguments,
8624 put the result into newpos and return the replacement string, which
8625 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008626static PyObject *
8627unicode_translate_call_errorhandler(const char *errors,
8628 PyObject **errorHandler,
8629 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008630 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008631 Py_ssize_t startpos, Py_ssize_t endpos,
8632 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008633{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008634 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008635
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008636 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008637 PyObject *restuple;
8638 PyObject *resunicode;
8639
8640 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008641 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008642 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008643 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 }
8645
8646 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008647 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008648 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650
8651 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008652 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008653 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008655 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008656 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008657 Py_DECREF(restuple);
8658 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659 }
8660 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008661 &resunicode, &i_newpos)) {
8662 Py_DECREF(restuple);
8663 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008665 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008667 else
8668 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008670 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 Py_DECREF(restuple);
8672 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008673 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008674 Py_INCREF(resunicode);
8675 Py_DECREF(restuple);
8676 return resunicode;
8677}
8678
8679/* Lookup the character ch in the mapping and put the result in result,
8680 which must be decrefed by the caller.
8681 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008682static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008683charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008684{
Christian Heimes217cfd12007-12-02 14:31:20 +00008685 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008686 PyObject *x;
8687
8688 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008689 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008690 x = PyObject_GetItem(mapping, w);
8691 Py_DECREF(w);
8692 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008693 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8694 /* No mapping found means: use 1:1 mapping. */
8695 PyErr_Clear();
8696 *result = NULL;
8697 return 0;
8698 } else
8699 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008700 }
8701 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 *result = x;
8703 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008704 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008705 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008707 if (value < 0 || value > MAX_UNICODE) {
8708 PyErr_Format(PyExc_ValueError,
8709 "character mapping must be in range(0x%x)",
8710 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 Py_DECREF(x);
8712 return -1;
8713 }
8714 *result = x;
8715 return 0;
8716 }
8717 else if (PyUnicode_Check(x)) {
8718 *result = x;
8719 return 0;
8720 }
8721 else {
8722 /* wrong return value */
8723 PyErr_SetString(PyExc_TypeError,
8724 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008725 Py_DECREF(x);
8726 return -1;
8727 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008728}
Victor Stinner1194ea02014-04-04 19:37:40 +02008729
8730/* lookup the character, write the result into the writer.
8731 Return 1 if the result was written into the writer, return 0 if the mapping
8732 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008733static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008734charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8735 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008736{
Victor Stinner1194ea02014-04-04 19:37:40 +02008737 PyObject *item;
8738
8739 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008740 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008741
8742 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008743 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008744 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008746 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008747 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008748 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008749
8750 if (item == Py_None) {
8751 Py_DECREF(item);
8752 return 0;
8753 }
8754
8755 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008756 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8757 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8758 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008759 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8760 Py_DECREF(item);
8761 return -1;
8762 }
8763 Py_DECREF(item);
8764 return 1;
8765 }
8766
8767 if (!PyUnicode_Check(item)) {
8768 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008769 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008770 }
8771
8772 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8773 Py_DECREF(item);
8774 return -1;
8775 }
8776
8777 Py_DECREF(item);
8778 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008779}
8780
Victor Stinner89a76ab2014-04-05 11:44:04 +02008781static int
8782unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8783 Py_UCS1 *translate)
8784{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008785 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008786 int ret = 0;
8787
Victor Stinner89a76ab2014-04-05 11:44:04 +02008788 if (charmaptranslate_lookup(ch, mapping, &item)) {
8789 return -1;
8790 }
8791
8792 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008793 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008794 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008795 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008796 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008797 /* not found => default to 1:1 mapping */
8798 translate[ch] = ch;
8799 return 1;
8800 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008801 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008802 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008803 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8804 used it */
8805 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008806 /* invalid character or character outside ASCII:
8807 skip the fast translate */
8808 goto exit;
8809 }
8810 translate[ch] = (Py_UCS1)replace;
8811 }
8812 else if (PyUnicode_Check(item)) {
8813 Py_UCS4 replace;
8814
8815 if (PyUnicode_READY(item) == -1) {
8816 Py_DECREF(item);
8817 return -1;
8818 }
8819 if (PyUnicode_GET_LENGTH(item) != 1)
8820 goto exit;
8821
8822 replace = PyUnicode_READ_CHAR(item, 0);
8823 if (replace > 127)
8824 goto exit;
8825 translate[ch] = (Py_UCS1)replace;
8826 }
8827 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008828 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008829 goto exit;
8830 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008831 ret = 1;
8832
Benjamin Peterson1365de72014-04-07 20:15:41 -04008833 exit:
8834 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008835 return ret;
8836}
8837
8838/* Fast path for ascii => ascii translation. Return 1 if the whole string
8839 was translated into writer, return 0 if the input string was partially
8840 translated into writer, raise an exception and return -1 on error. */
8841static int
8842unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008843 _PyUnicodeWriter *writer, int ignore,
8844 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008845{
Victor Stinner872b2912014-04-05 14:27:07 +02008846 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008847 Py_ssize_t len;
8848 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008849 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008850
Victor Stinner89a76ab2014-04-05 11:44:04 +02008851 len = PyUnicode_GET_LENGTH(input);
8852
Victor Stinner872b2912014-04-05 14:27:07 +02008853 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008854
8855 in = PyUnicode_1BYTE_DATA(input);
8856 end = in + len;
8857
8858 assert(PyUnicode_IS_ASCII(writer->buffer));
8859 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8860 out = PyUnicode_1BYTE_DATA(writer->buffer);
8861
Victor Stinner872b2912014-04-05 14:27:07 +02008862 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008863 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008864 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008865 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008866 int translate = unicode_fast_translate_lookup(mapping, ch,
8867 ascii_table);
8868 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008869 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008870 if (translate == 0)
8871 goto exit;
8872 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008873 }
Victor Stinner872b2912014-04-05 14:27:07 +02008874 if (ch2 == 0xfe) {
8875 if (ignore)
8876 continue;
8877 goto exit;
8878 }
8879 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008880 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008881 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008882 }
Victor Stinner872b2912014-04-05 14:27:07 +02008883 res = 1;
8884
8885exit:
8886 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008887 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008888 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008889}
8890
Victor Stinner3222da22015-10-01 22:07:32 +02008891static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008892_PyUnicode_TranslateCharmap(PyObject *input,
8893 PyObject *mapping,
8894 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008896 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008897 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008898 Py_ssize_t size, i;
8899 int kind;
8900 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008901 _PyUnicodeWriter writer;
8902 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008903 char *reason = "character maps to <undefined>";
8904 PyObject *errorHandler = NULL;
8905 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008906 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008907 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008908
Guido van Rossumd57fd912000-03-10 22:53:23 +00008909 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008910 PyErr_BadArgument();
8911 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008912 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008913
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008914 if (PyUnicode_READY(input) == -1)
8915 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008916 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008917 kind = PyUnicode_KIND(input);
8918 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008919
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008920 if (size == 0)
8921 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008922
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008923 /* allocate enough for a simple 1:1 translation without
8924 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008925 _PyUnicodeWriter_Init(&writer);
8926 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008927 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008928
Victor Stinner872b2912014-04-05 14:27:07 +02008929 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8930
Victor Stinner33798672016-03-01 21:59:58 +01008931 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008932 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008933 if (PyUnicode_IS_ASCII(input)) {
8934 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8935 if (res < 0) {
8936 _PyUnicodeWriter_Dealloc(&writer);
8937 return NULL;
8938 }
8939 if (res == 1)
8940 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008941 }
Victor Stinner33798672016-03-01 21:59:58 +01008942 else {
8943 i = 0;
8944 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008946 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008947 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008948 int translate;
8949 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8950 Py_ssize_t newpos;
8951 /* startpos for collecting untranslatable chars */
8952 Py_ssize_t collstart;
8953 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008954 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008955
Victor Stinner1194ea02014-04-04 19:37:40 +02008956 ch = PyUnicode_READ(kind, data, i);
8957 translate = charmaptranslate_output(ch, mapping, &writer);
8958 if (translate < 0)
8959 goto onError;
8960
8961 if (translate != 0) {
8962 /* it worked => adjust input pointer */
8963 ++i;
8964 continue;
8965 }
8966
8967 /* untranslatable character */
8968 collstart = i;
8969 collend = i+1;
8970
8971 /* find all untranslatable characters */
8972 while (collend < size) {
8973 PyObject *x;
8974 ch = PyUnicode_READ(kind, data, collend);
8975 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008976 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008977 Py_XDECREF(x);
8978 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008979 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008980 ++collend;
8981 }
8982
8983 if (ignore) {
8984 i = collend;
8985 }
8986 else {
8987 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8988 reason, input, &exc,
8989 collstart, collend, &newpos);
8990 if (repunicode == NULL)
8991 goto onError;
8992 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008993 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008994 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008995 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008996 Py_DECREF(repunicode);
8997 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008998 }
8999 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009000 Py_XDECREF(exc);
9001 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009002 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009003
Benjamin Peterson29060642009-01-31 22:14:21 +00009004 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009005 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009006 Py_XDECREF(exc);
9007 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009008 return NULL;
9009}
9010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011/* Deprecated. Use PyUnicode_Translate instead. */
9012PyObject *
9013PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9014 Py_ssize_t size,
9015 PyObject *mapping,
9016 const char *errors)
9017{
Christian Heimes5f520f42012-09-11 14:03:25 +02009018 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009019 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9020 if (!unicode)
9021 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009022 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9023 Py_DECREF(unicode);
9024 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009025}
9026
Alexander Belopolsky40018472011-02-26 01:02:56 +00009027PyObject *
9028PyUnicode_Translate(PyObject *str,
9029 PyObject *mapping,
9030 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009031{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009032 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009033 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009034 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009035}
Tim Petersced69f82003-09-16 20:30:58 +00009036
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009037static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009038fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009039{
9040 /* No need to call PyUnicode_READY(self) because this function is only
9041 called as a callback from fixup() which does it already. */
9042 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9043 const int kind = PyUnicode_KIND(self);
9044 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009045 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009046 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047 Py_ssize_t i;
9048
9049 for (i = 0; i < len; ++i) {
9050 ch = PyUnicode_READ(kind, data, i);
9051 fixed = 0;
9052 if (ch > 127) {
9053 if (Py_UNICODE_ISSPACE(ch))
9054 fixed = ' ';
9055 else {
9056 const int decimal = Py_UNICODE_TODECIMAL(ch);
9057 if (decimal >= 0)
9058 fixed = '0' + decimal;
9059 }
9060 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009061 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009062 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009063 PyUnicode_WRITE(kind, data, i, fixed);
9064 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009065 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009066 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068 }
9069
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009070 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009071}
9072
9073PyObject *
9074_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9075{
9076 if (!PyUnicode_Check(unicode)) {
9077 PyErr_BadInternalCall();
9078 return NULL;
9079 }
9080 if (PyUnicode_READY(unicode) == -1)
9081 return NULL;
9082 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9083 /* If the string is already ASCII, just return the same string */
9084 Py_INCREF(unicode);
9085 return unicode;
9086 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009087 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009088}
9089
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009090PyObject *
9091PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9092 Py_ssize_t length)
9093{
Victor Stinnerf0124502011-11-21 23:12:56 +01009094 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009095 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009096 Py_UCS4 maxchar;
9097 enum PyUnicode_Kind kind;
9098 void *data;
9099
Victor Stinner99d7ad02012-02-22 13:37:39 +01009100 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009101 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009102 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009103 if (ch > 127) {
9104 int decimal = Py_UNICODE_TODECIMAL(ch);
9105 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009106 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009107 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009108 }
9109 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009110
9111 /* Copy to a new string */
9112 decimal = PyUnicode_New(length, maxchar);
9113 if (decimal == NULL)
9114 return decimal;
9115 kind = PyUnicode_KIND(decimal);
9116 data = PyUnicode_DATA(decimal);
9117 /* Iterate over code points */
9118 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009119 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009120 if (ch > 127) {
9121 int decimal = Py_UNICODE_TODECIMAL(ch);
9122 if (decimal >= 0)
9123 ch = '0' + decimal;
9124 }
9125 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009126 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009127 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009128}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009129/* --- Decimal Encoder ---------------------------------------------------- */
9130
Alexander Belopolsky40018472011-02-26 01:02:56 +00009131int
9132PyUnicode_EncodeDecimal(Py_UNICODE *s,
9133 Py_ssize_t length,
9134 char *output,
9135 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009136{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009137 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009138 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009139 enum PyUnicode_Kind kind;
9140 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009141
9142 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009143 PyErr_BadArgument();
9144 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009145 }
9146
Victor Stinner42bf7752011-11-21 22:52:58 +01009147 unicode = PyUnicode_FromUnicode(s, length);
9148 if (unicode == NULL)
9149 return -1;
9150
Benjamin Petersonbac79492012-01-14 13:34:47 -05009151 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009152 Py_DECREF(unicode);
9153 return -1;
9154 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009155 kind = PyUnicode_KIND(unicode);
9156 data = PyUnicode_DATA(unicode);
9157
Victor Stinnerb84d7232011-11-22 01:50:07 +01009158 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009159 PyObject *exc;
9160 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009161 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009162 Py_ssize_t startpos;
9163
9164 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009165
Benjamin Peterson29060642009-01-31 22:14:21 +00009166 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009167 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009168 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009169 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009170 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009171 decimal = Py_UNICODE_TODECIMAL(ch);
9172 if (decimal >= 0) {
9173 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009174 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009175 continue;
9176 }
9177 if (0 < ch && ch < 256) {
9178 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009179 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009180 continue;
9181 }
Victor Stinner6345be92011-11-25 20:09:01 +01009182
Victor Stinner42bf7752011-11-21 22:52:58 +01009183 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009184 exc = NULL;
9185 raise_encode_exception(&exc, "decimal", unicode,
9186 startpos, startpos+1,
9187 "invalid decimal Unicode string");
9188 Py_XDECREF(exc);
9189 Py_DECREF(unicode);
9190 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009191 }
9192 /* 0-terminate the output string */
9193 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009194 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009195 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009196}
9197
Guido van Rossumd57fd912000-03-10 22:53:23 +00009198/* --- Helpers ------------------------------------------------------------ */
9199
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009200/* helper macro to fixup start/end slice values */
9201#define ADJUST_INDICES(start, end, len) \
9202 if (end > len) \
9203 end = len; \
9204 else if (end < 0) { \
9205 end += len; \
9206 if (end < 0) \
9207 end = 0; \
9208 } \
9209 if (start < 0) { \
9210 start += len; \
9211 if (start < 0) \
9212 start = 0; \
9213 }
9214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009215static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009216any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009217 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009218 Py_ssize_t end,
9219 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009221 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009222 void *buf1, *buf2;
9223 Py_ssize_t len1, len2, result;
9224
9225 kind1 = PyUnicode_KIND(s1);
9226 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009227 if (kind1 < kind2)
9228 return -1;
9229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009230 len1 = PyUnicode_GET_LENGTH(s1);
9231 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009232 ADJUST_INDICES(start, end, len1);
9233 if (end - start < len2)
9234 return -1;
9235
9236 buf1 = PyUnicode_DATA(s1);
9237 buf2 = PyUnicode_DATA(s2);
9238 if (len2 == 1) {
9239 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9240 result = findchar((const char *)buf1 + kind1*start,
9241 kind1, end - start, ch, direction);
9242 if (result == -1)
9243 return -1;
9244 else
9245 return start + result;
9246 }
9247
9248 if (kind2 != kind1) {
9249 buf2 = _PyUnicode_AsKind(s2, kind1);
9250 if (!buf2)
9251 return -2;
9252 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253
Victor Stinner794d5672011-10-10 03:21:36 +02009254 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009255 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009256 case PyUnicode_1BYTE_KIND:
9257 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9258 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9259 else
9260 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9261 break;
9262 case PyUnicode_2BYTE_KIND:
9263 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9264 break;
9265 case PyUnicode_4BYTE_KIND:
9266 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9267 break;
9268 default:
9269 assert(0); result = -2;
9270 }
9271 }
9272 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009273 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009274 case PyUnicode_1BYTE_KIND:
9275 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9276 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9277 else
9278 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9279 break;
9280 case PyUnicode_2BYTE_KIND:
9281 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9282 break;
9283 case PyUnicode_4BYTE_KIND:
9284 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9285 break;
9286 default:
9287 assert(0); result = -2;
9288 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009289 }
9290
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009291 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009292 PyMem_Free(buf2);
9293
9294 return result;
9295}
9296
9297Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009298_PyUnicode_InsertThousandsGrouping(
9299 PyObject *unicode, Py_ssize_t index,
9300 Py_ssize_t n_buffer,
9301 void *digits, Py_ssize_t n_digits,
9302 Py_ssize_t min_width,
9303 const char *grouping, PyObject *thousands_sep,
9304 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305{
Victor Stinner41a863c2012-02-24 00:37:51 +01009306 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009307 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009308 Py_ssize_t thousands_sep_len;
9309 Py_ssize_t len;
9310
9311 if (unicode != NULL) {
9312 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009313 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009314 }
9315 else {
9316 kind = PyUnicode_1BYTE_KIND;
9317 data = NULL;
9318 }
9319 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9320 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9321 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9322 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009323 if (thousands_sep_kind < kind) {
9324 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9325 if (!thousands_sep_data)
9326 return -1;
9327 }
9328 else {
9329 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9330 if (!data)
9331 return -1;
9332 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009333 }
9334
Benjamin Petersonead6b532011-12-20 17:23:42 -06009335 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009337 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009338 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009339 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009340 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009341 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009342 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009343 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009344 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009345 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009346 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009347 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009349 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009350 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009351 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009352 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009353 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009354 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009355 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009356 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009357 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009358 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009359 break;
9360 default:
9361 assert(0);
9362 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009363 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009364 if (unicode != NULL && thousands_sep_kind != kind) {
9365 if (thousands_sep_kind < kind)
9366 PyMem_Free(thousands_sep_data);
9367 else
9368 PyMem_Free(data);
9369 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009370 if (unicode == NULL) {
9371 *maxchar = 127;
9372 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009373 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009374 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009375 }
9376 }
9377 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009378}
9379
9380
Alexander Belopolsky40018472011-02-26 01:02:56 +00009381Py_ssize_t
9382PyUnicode_Count(PyObject *str,
9383 PyObject *substr,
9384 Py_ssize_t start,
9385 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009387 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009388 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009389 void *buf1 = NULL, *buf2 = NULL;
9390 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009391
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009392 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009393 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009394
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009395 kind1 = PyUnicode_KIND(str);
9396 kind2 = PyUnicode_KIND(substr);
9397 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009398 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009399
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009400 len1 = PyUnicode_GET_LENGTH(str);
9401 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009402 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009403 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009404 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009405
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009406 buf1 = PyUnicode_DATA(str);
9407 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009408 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009409 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009410 if (!buf2)
9411 goto onError;
9412 }
9413
9414 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009416 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009417 result = asciilib_count(
9418 ((Py_UCS1*)buf1) + start, end - start,
9419 buf2, len2, PY_SSIZE_T_MAX
9420 );
9421 else
9422 result = ucs1lib_count(
9423 ((Py_UCS1*)buf1) + start, end - start,
9424 buf2, len2, PY_SSIZE_T_MAX
9425 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426 break;
9427 case PyUnicode_2BYTE_KIND:
9428 result = ucs2lib_count(
9429 ((Py_UCS2*)buf1) + start, end - start,
9430 buf2, len2, PY_SSIZE_T_MAX
9431 );
9432 break;
9433 case PyUnicode_4BYTE_KIND:
9434 result = ucs4lib_count(
9435 ((Py_UCS4*)buf1) + start, end - start,
9436 buf2, len2, PY_SSIZE_T_MAX
9437 );
9438 break;
9439 default:
9440 assert(0); result = 0;
9441 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009442
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009443 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444 PyMem_Free(buf2);
9445
Guido van Rossumd57fd912000-03-10 22:53:23 +00009446 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009448 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009449 PyMem_Free(buf2);
9450 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451}
9452
Alexander Belopolsky40018472011-02-26 01:02:56 +00009453Py_ssize_t
9454PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009455 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009456 Py_ssize_t start,
9457 Py_ssize_t end,
9458 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009459{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009460 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009461 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009462
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009463 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464}
9465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466Py_ssize_t
9467PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9468 Py_ssize_t start, Py_ssize_t end,
9469 int direction)
9470{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009472 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009473 if (PyUnicode_READY(str) == -1)
9474 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009475 if (start < 0 || end < 0) {
9476 PyErr_SetString(PyExc_IndexError, "string index out of range");
9477 return -2;
9478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479 if (end > PyUnicode_GET_LENGTH(str))
9480 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009481 if (start >= end)
9482 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009484 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9485 kind, end-start, ch, direction);
9486 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009488 else
9489 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009490}
9491
Alexander Belopolsky40018472011-02-26 01:02:56 +00009492static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009493tailmatch(PyObject *self,
9494 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009495 Py_ssize_t start,
9496 Py_ssize_t end,
9497 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009498{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499 int kind_self;
9500 int kind_sub;
9501 void *data_self;
9502 void *data_sub;
9503 Py_ssize_t offset;
9504 Py_ssize_t i;
9505 Py_ssize_t end_sub;
9506
9507 if (PyUnicode_READY(self) == -1 ||
9508 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009509 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009510
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009511 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9512 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009513 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009514 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009515
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009516 if (PyUnicode_GET_LENGTH(substring) == 0)
9517 return 1;
9518
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519 kind_self = PyUnicode_KIND(self);
9520 data_self = PyUnicode_DATA(self);
9521 kind_sub = PyUnicode_KIND(substring);
9522 data_sub = PyUnicode_DATA(substring);
9523 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9524
9525 if (direction > 0)
9526 offset = end;
9527 else
9528 offset = start;
9529
9530 if (PyUnicode_READ(kind_self, data_self, offset) ==
9531 PyUnicode_READ(kind_sub, data_sub, 0) &&
9532 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9533 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9534 /* If both are of the same kind, memcmp is sufficient */
9535 if (kind_self == kind_sub) {
9536 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009537 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009538 data_sub,
9539 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009540 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009541 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009542 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009543 else {
9544 /* We do not need to compare 0 and len(substring)-1 because
9545 the if statement above ensured already that they are equal
9546 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009547 for (i = 1; i < end_sub; ++i) {
9548 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9549 PyUnicode_READ(kind_sub, data_sub, i))
9550 return 0;
9551 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009552 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009553 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009554 }
9555
9556 return 0;
9557}
9558
Alexander Belopolsky40018472011-02-26 01:02:56 +00009559Py_ssize_t
9560PyUnicode_Tailmatch(PyObject *str,
9561 PyObject *substr,
9562 Py_ssize_t start,
9563 Py_ssize_t end,
9564 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009565{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009566 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009567 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009568
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009569 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009570}
9571
Guido van Rossumd57fd912000-03-10 22:53:23 +00009572/* Apply fixfct filter to the Unicode object self and return a
9573 reference to the modified object */
9574
Alexander Belopolsky40018472011-02-26 01:02:56 +00009575static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009576fixup(PyObject *self,
9577 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009579 PyObject *u;
9580 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009581 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009582
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009583 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009584 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009585 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009586 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009588 /* fix functions return the new maximum character in a string,
9589 if the kind of the resulting unicode object does not change,
9590 everything is fine. Otherwise we need to change the string kind
9591 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009592 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009593
9594 if (maxchar_new == 0) {
9595 /* no changes */;
9596 if (PyUnicode_CheckExact(self)) {
9597 Py_DECREF(u);
9598 Py_INCREF(self);
9599 return self;
9600 }
9601 else
9602 return u;
9603 }
9604
Victor Stinnere6abb482012-05-02 01:15:40 +02009605 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009606
Victor Stinnereaab6042011-12-11 22:22:39 +01009607 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009608 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009609
9610 /* In case the maximum character changed, we need to
9611 convert the string to the new category. */
9612 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9613 if (v == NULL) {
9614 Py_DECREF(u);
9615 return NULL;
9616 }
9617 if (maxchar_new > maxchar_old) {
9618 /* If the maxchar increased so that the kind changed, not all
9619 characters are representable anymore and we need to fix the
9620 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009621 _PyUnicode_FastCopyCharacters(v, 0,
9622 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009623 maxchar_old = fixfct(v);
9624 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625 }
9626 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009627 _PyUnicode_FastCopyCharacters(v, 0,
9628 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009629 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009630 Py_DECREF(u);
9631 assert(_PyUnicode_CheckConsistency(v, 1));
9632 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009633}
9634
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009635static PyObject *
9636ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009637{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009638 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9639 char *resdata, *data = PyUnicode_DATA(self);
9640 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009641
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009642 res = PyUnicode_New(len, 127);
9643 if (res == NULL)
9644 return NULL;
9645 resdata = PyUnicode_DATA(res);
9646 if (lower)
9647 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009648 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009649 _Py_bytes_upper(resdata, data, len);
9650 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009651}
9652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009654handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009655{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009656 Py_ssize_t j;
9657 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009658 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009659 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009660
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009661 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9662
9663 where ! is a negation and \p{xxx} is a character with property xxx.
9664 */
9665 for (j = i - 1; j >= 0; j--) {
9666 c = PyUnicode_READ(kind, data, j);
9667 if (!_PyUnicode_IsCaseIgnorable(c))
9668 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9671 if (final_sigma) {
9672 for (j = i + 1; j < length; j++) {
9673 c = PyUnicode_READ(kind, data, j);
9674 if (!_PyUnicode_IsCaseIgnorable(c))
9675 break;
9676 }
9677 final_sigma = j == length || !_PyUnicode_IsCased(c);
9678 }
9679 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009680}
9681
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009682static int
9683lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9684 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009685{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009686 /* Obscure special case. */
9687 if (c == 0x3A3) {
9688 mapped[0] = handle_capital_sigma(kind, data, length, i);
9689 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009691 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009692}
9693
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009694static Py_ssize_t
9695do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009696{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009697 Py_ssize_t i, k = 0;
9698 int n_res, j;
9699 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009700
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009701 c = PyUnicode_READ(kind, data, 0);
9702 n_res = _PyUnicode_ToUpperFull(c, mapped);
9703 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009704 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009705 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009706 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009707 for (i = 1; i < length; i++) {
9708 c = PyUnicode_READ(kind, data, i);
9709 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9710 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009711 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009712 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009713 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009714 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009715 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009716}
9717
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009718static Py_ssize_t
9719do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9720 Py_ssize_t i, k = 0;
9721
9722 for (i = 0; i < length; i++) {
9723 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9724 int n_res, j;
9725 if (Py_UNICODE_ISUPPER(c)) {
9726 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9727 }
9728 else if (Py_UNICODE_ISLOWER(c)) {
9729 n_res = _PyUnicode_ToUpperFull(c, mapped);
9730 }
9731 else {
9732 n_res = 1;
9733 mapped[0] = c;
9734 }
9735 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009736 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009737 res[k++] = mapped[j];
9738 }
9739 }
9740 return k;
9741}
9742
9743static Py_ssize_t
9744do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9745 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009746{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009747 Py_ssize_t i, k = 0;
9748
9749 for (i = 0; i < length; i++) {
9750 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9751 int n_res, j;
9752 if (lower)
9753 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9754 else
9755 n_res = _PyUnicode_ToUpperFull(c, mapped);
9756 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009757 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009758 res[k++] = mapped[j];
9759 }
9760 }
9761 return k;
9762}
9763
9764static Py_ssize_t
9765do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9766{
9767 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9768}
9769
9770static Py_ssize_t
9771do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9772{
9773 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9774}
9775
Benjamin Petersone51757f2012-01-12 21:10:29 -05009776static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009777do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9778{
9779 Py_ssize_t i, k = 0;
9780
9781 for (i = 0; i < length; i++) {
9782 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9783 Py_UCS4 mapped[3];
9784 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9785 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009786 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009787 res[k++] = mapped[j];
9788 }
9789 }
9790 return k;
9791}
9792
9793static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009794do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9795{
9796 Py_ssize_t i, k = 0;
9797 int previous_is_cased;
9798
9799 previous_is_cased = 0;
9800 for (i = 0; i < length; i++) {
9801 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9802 Py_UCS4 mapped[3];
9803 int n_res, j;
9804
9805 if (previous_is_cased)
9806 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9807 else
9808 n_res = _PyUnicode_ToTitleFull(c, mapped);
9809
9810 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009811 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009812 res[k++] = mapped[j];
9813 }
9814
9815 previous_is_cased = _PyUnicode_IsCased(c);
9816 }
9817 return k;
9818}
9819
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009820static PyObject *
9821case_operation(PyObject *self,
9822 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9823{
9824 PyObject *res = NULL;
9825 Py_ssize_t length, newlength = 0;
9826 int kind, outkind;
9827 void *data, *outdata;
9828 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9829
Benjamin Petersoneea48462012-01-16 14:28:50 -05009830 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009831
9832 kind = PyUnicode_KIND(self);
9833 data = PyUnicode_DATA(self);
9834 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009835 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009836 PyErr_SetString(PyExc_OverflowError, "string is too long");
9837 return NULL;
9838 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009839 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009840 if (tmp == NULL)
9841 return PyErr_NoMemory();
9842 newlength = perform(kind, data, length, tmp, &maxchar);
9843 res = PyUnicode_New(newlength, maxchar);
9844 if (res == NULL)
9845 goto leave;
9846 tmpend = tmp + newlength;
9847 outdata = PyUnicode_DATA(res);
9848 outkind = PyUnicode_KIND(res);
9849 switch (outkind) {
9850 case PyUnicode_1BYTE_KIND:
9851 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9852 break;
9853 case PyUnicode_2BYTE_KIND:
9854 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9855 break;
9856 case PyUnicode_4BYTE_KIND:
9857 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9858 break;
9859 default:
9860 assert(0);
9861 break;
9862 }
9863 leave:
9864 PyMem_FREE(tmp);
9865 return res;
9866}
9867
Tim Peters8ce9f162004-08-27 01:49:32 +00009868PyObject *
9869PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009870{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009871 PyObject *res;
9872 PyObject *fseq;
9873 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009874 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009875
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009876 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009877 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009878 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009879 }
9880
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009881 /* NOTE: the following code can't call back into Python code,
9882 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009883 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009884
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009885 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009886 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009887 res = _PyUnicode_JoinArray(separator, items, seqlen);
9888 Py_DECREF(fseq);
9889 return res;
9890}
9891
9892PyObject *
9893_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9894{
9895 PyObject *res = NULL; /* the result */
9896 PyObject *sep = NULL;
9897 Py_ssize_t seplen;
9898 PyObject *item;
9899 Py_ssize_t sz, i, res_offset;
9900 Py_UCS4 maxchar;
9901 Py_UCS4 item_maxchar;
9902 int use_memcpy;
9903 unsigned char *res_data = NULL, *sep_data = NULL;
9904 PyObject *last_obj;
9905 unsigned int kind = 0;
9906
Tim Peters05eba1f2004-08-27 21:32:02 +00009907 /* If empty sequence, return u"". */
9908 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009909 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009910 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009911
Tim Peters05eba1f2004-08-27 21:32:02 +00009912 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009913 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009914 if (seqlen == 1) {
9915 if (PyUnicode_CheckExact(items[0])) {
9916 res = items[0];
9917 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009918 return res;
9919 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009920 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009921 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009922 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009923 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009924 /* Set up sep and seplen */
9925 if (separator == NULL) {
9926 /* fall back to a blank space separator */
9927 sep = PyUnicode_FromOrdinal(' ');
9928 if (!sep)
9929 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009930 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009931 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009932 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009933 else {
9934 if (!PyUnicode_Check(separator)) {
9935 PyErr_Format(PyExc_TypeError,
9936 "separator: expected str instance,"
9937 " %.80s found",
9938 Py_TYPE(separator)->tp_name);
9939 goto onError;
9940 }
9941 if (PyUnicode_READY(separator))
9942 goto onError;
9943 sep = separator;
9944 seplen = PyUnicode_GET_LENGTH(separator);
9945 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9946 /* inc refcount to keep this code path symmetric with the
9947 above case of a blank separator */
9948 Py_INCREF(sep);
9949 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009950 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009951 }
9952
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009953 /* There are at least two things to join, or else we have a subclass
9954 * of str in the sequence.
9955 * Do a pre-pass to figure out the total amount of space we'll
9956 * need (sz), and see whether all argument are strings.
9957 */
9958 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009959#ifdef Py_DEBUG
9960 use_memcpy = 0;
9961#else
9962 use_memcpy = 1;
9963#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009964 for (i = 0; i < seqlen; i++) {
9965 const Py_ssize_t old_sz = sz;
9966 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009967 if (!PyUnicode_Check(item)) {
9968 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009969 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009970 " %.80s found",
9971 i, Py_TYPE(item)->tp_name);
9972 goto onError;
9973 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009974 if (PyUnicode_READY(item) == -1)
9975 goto onError;
9976 sz += PyUnicode_GET_LENGTH(item);
9977 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009978 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009979 if (i != 0)
9980 sz += seplen;
9981 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9982 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009983 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009984 goto onError;
9985 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009986 if (use_memcpy && last_obj != NULL) {
9987 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9988 use_memcpy = 0;
9989 }
9990 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009991 }
Tim Petersced69f82003-09-16 20:30:58 +00009992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009993 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009994 if (res == NULL)
9995 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009996
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009997 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009998#ifdef Py_DEBUG
9999 use_memcpy = 0;
10000#else
10001 if (use_memcpy) {
10002 res_data = PyUnicode_1BYTE_DATA(res);
10003 kind = PyUnicode_KIND(res);
10004 if (seplen != 0)
10005 sep_data = PyUnicode_1BYTE_DATA(sep);
10006 }
10007#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010008 if (use_memcpy) {
10009 for (i = 0; i < seqlen; ++i) {
10010 Py_ssize_t itemlen;
10011 item = items[i];
10012
10013 /* Copy item, and maybe the separator. */
10014 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010015 Py_MEMCPY(res_data,
10016 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010017 kind * seplen);
10018 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010019 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010020
10021 itemlen = PyUnicode_GET_LENGTH(item);
10022 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +020010023 Py_MEMCPY(res_data,
10024 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010025 kind * itemlen);
10026 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010027 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010028 }
10029 assert(res_data == PyUnicode_1BYTE_DATA(res)
10030 + kind * PyUnicode_GET_LENGTH(res));
10031 }
10032 else {
10033 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10034 Py_ssize_t itemlen;
10035 item = items[i];
10036
10037 /* Copy item, and maybe the separator. */
10038 if (i && seplen != 0) {
10039 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10040 res_offset += seplen;
10041 }
10042
10043 itemlen = PyUnicode_GET_LENGTH(item);
10044 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010045 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010046 res_offset += itemlen;
10047 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010048 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010049 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010050 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010053 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010055
Benjamin Peterson29060642009-01-31 22:14:21 +000010056 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010058 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010059 return NULL;
10060}
10061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062#define FILL(kind, data, value, start, length) \
10063 do { \
10064 Py_ssize_t i_ = 0; \
10065 assert(kind != PyUnicode_WCHAR_KIND); \
10066 switch ((kind)) { \
10067 case PyUnicode_1BYTE_KIND: { \
10068 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010069 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 break; \
10071 } \
10072 case PyUnicode_2BYTE_KIND: { \
10073 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10074 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10075 break; \
10076 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010077 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10079 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10080 break; \
10081 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010082 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 } \
10084 } while (0)
10085
Victor Stinnerd3f08822012-05-29 12:57:52 +020010086void
10087_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10088 Py_UCS4 fill_char)
10089{
10090 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10091 const void *data = PyUnicode_DATA(unicode);
10092 assert(PyUnicode_IS_READY(unicode));
10093 assert(unicode_modifiable(unicode));
10094 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10095 assert(start >= 0);
10096 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10097 FILL(kind, data, fill_char, start, length);
10098}
10099
Victor Stinner3fe55312012-01-04 00:33:50 +010010100Py_ssize_t
10101PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10102 Py_UCS4 fill_char)
10103{
10104 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010105
10106 if (!PyUnicode_Check(unicode)) {
10107 PyErr_BadInternalCall();
10108 return -1;
10109 }
10110 if (PyUnicode_READY(unicode) == -1)
10111 return -1;
10112 if (unicode_check_modifiable(unicode))
10113 return -1;
10114
Victor Stinnerd3f08822012-05-29 12:57:52 +020010115 if (start < 0) {
10116 PyErr_SetString(PyExc_IndexError, "string index out of range");
10117 return -1;
10118 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010119 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10120 PyErr_SetString(PyExc_ValueError,
10121 "fill character is bigger than "
10122 "the string maximum character");
10123 return -1;
10124 }
10125
10126 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10127 length = Py_MIN(maxlen, length);
10128 if (length <= 0)
10129 return 0;
10130
Victor Stinnerd3f08822012-05-29 12:57:52 +020010131 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010132 return length;
10133}
10134
Victor Stinner9310abb2011-10-05 00:59:23 +020010135static PyObject *
10136pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010137 Py_ssize_t left,
10138 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010140{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 PyObject *u;
10142 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010143 int kind;
10144 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010145
10146 if (left < 0)
10147 left = 0;
10148 if (right < 0)
10149 right = 0;
10150
Victor Stinnerc4b49542011-12-11 22:44:26 +010010151 if (left == 0 && right == 0)
10152 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010153
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10155 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010156 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10157 return NULL;
10158 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010160 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010162 if (!u)
10163 return NULL;
10164
10165 kind = PyUnicode_KIND(u);
10166 data = PyUnicode_DATA(u);
10167 if (left)
10168 FILL(kind, data, fill, 0, left);
10169 if (right)
10170 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010171 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010172 assert(_PyUnicode_CheckConsistency(u, 1));
10173 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010174}
10175
Alexander Belopolsky40018472011-02-26 01:02:56 +000010176PyObject *
10177PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010178{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010179 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010180
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010181 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010182 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010183
Benjamin Petersonead6b532011-12-20 17:23:42 -060010184 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010186 if (PyUnicode_IS_ASCII(string))
10187 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010188 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010189 PyUnicode_GET_LENGTH(string), keepends);
10190 else
10191 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010192 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010193 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 break;
10195 case PyUnicode_2BYTE_KIND:
10196 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010197 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 PyUnicode_GET_LENGTH(string), keepends);
10199 break;
10200 case PyUnicode_4BYTE_KIND:
10201 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010202 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 PyUnicode_GET_LENGTH(string), keepends);
10204 break;
10205 default:
10206 assert(0);
10207 list = 0;
10208 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010209 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010210}
10211
Alexander Belopolsky40018472011-02-26 01:02:56 +000010212static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010213split(PyObject *self,
10214 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010215 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010216{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010217 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 void *buf1, *buf2;
10219 Py_ssize_t len1, len2;
10220 PyObject* out;
10221
Guido van Rossumd57fd912000-03-10 22:53:23 +000010222 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010223 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010224
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225 if (PyUnicode_READY(self) == -1)
10226 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010229 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010231 if (PyUnicode_IS_ASCII(self))
10232 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010233 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010234 PyUnicode_GET_LENGTH(self), maxcount
10235 );
10236 else
10237 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010238 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010239 PyUnicode_GET_LENGTH(self), maxcount
10240 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 case PyUnicode_2BYTE_KIND:
10242 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010243 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 PyUnicode_GET_LENGTH(self), maxcount
10245 );
10246 case PyUnicode_4BYTE_KIND:
10247 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010248 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 PyUnicode_GET_LENGTH(self), maxcount
10250 );
10251 default:
10252 assert(0);
10253 return NULL;
10254 }
10255
10256 if (PyUnicode_READY(substring) == -1)
10257 return NULL;
10258
10259 kind1 = PyUnicode_KIND(self);
10260 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 len1 = PyUnicode_GET_LENGTH(self);
10262 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010263 if (kind1 < kind2 || len1 < len2) {
10264 out = PyList_New(1);
10265 if (out == NULL)
10266 return NULL;
10267 Py_INCREF(self);
10268 PyList_SET_ITEM(out, 0, self);
10269 return out;
10270 }
10271 buf1 = PyUnicode_DATA(self);
10272 buf2 = PyUnicode_DATA(substring);
10273 if (kind2 != kind1) {
10274 buf2 = _PyUnicode_AsKind(substring, kind1);
10275 if (!buf2)
10276 return NULL;
10277 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010279 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010281 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10282 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010283 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010284 else
10285 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010286 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 break;
10288 case PyUnicode_2BYTE_KIND:
10289 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010290 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 break;
10292 case PyUnicode_4BYTE_KIND:
10293 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010294 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 break;
10296 default:
10297 out = NULL;
10298 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010299 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 PyMem_Free(buf2);
10301 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010302}
10303
Alexander Belopolsky40018472011-02-26 01:02:56 +000010304static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010305rsplit(PyObject *self,
10306 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010307 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010308{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010309 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 void *buf1, *buf2;
10311 Py_ssize_t len1, len2;
10312 PyObject* out;
10313
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010314 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010315 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010316
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 if (PyUnicode_READY(self) == -1)
10318 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010321 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010323 if (PyUnicode_IS_ASCII(self))
10324 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010325 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010326 PyUnicode_GET_LENGTH(self), maxcount
10327 );
10328 else
10329 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010330 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010331 PyUnicode_GET_LENGTH(self), maxcount
10332 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 case PyUnicode_2BYTE_KIND:
10334 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010335 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 PyUnicode_GET_LENGTH(self), maxcount
10337 );
10338 case PyUnicode_4BYTE_KIND:
10339 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010340 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 PyUnicode_GET_LENGTH(self), maxcount
10342 );
10343 default:
10344 assert(0);
10345 return NULL;
10346 }
10347
10348 if (PyUnicode_READY(substring) == -1)
10349 return NULL;
10350
10351 kind1 = PyUnicode_KIND(self);
10352 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353 len1 = PyUnicode_GET_LENGTH(self);
10354 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010355 if (kind1 < kind2 || len1 < len2) {
10356 out = PyList_New(1);
10357 if (out == NULL)
10358 return NULL;
10359 Py_INCREF(self);
10360 PyList_SET_ITEM(out, 0, self);
10361 return out;
10362 }
10363 buf1 = PyUnicode_DATA(self);
10364 buf2 = PyUnicode_DATA(substring);
10365 if (kind2 != kind1) {
10366 buf2 = _PyUnicode_AsKind(substring, kind1);
10367 if (!buf2)
10368 return NULL;
10369 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010371 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010373 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10374 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010375 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010376 else
10377 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010378 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 break;
10380 case PyUnicode_2BYTE_KIND:
10381 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010382 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 break;
10384 case PyUnicode_4BYTE_KIND:
10385 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010386 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 break;
10388 default:
10389 out = NULL;
10390 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010391 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 PyMem_Free(buf2);
10393 return out;
10394}
10395
10396static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010397anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10398 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010400 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010402 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10403 return asciilib_find(buf1, len1, buf2, len2, offset);
10404 else
10405 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 case PyUnicode_2BYTE_KIND:
10407 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10408 case PyUnicode_4BYTE_KIND:
10409 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10410 }
10411 assert(0);
10412 return -1;
10413}
10414
10415static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010416anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10417 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010419 switch (kind) {
10420 case PyUnicode_1BYTE_KIND:
10421 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10422 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10423 else
10424 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10425 case PyUnicode_2BYTE_KIND:
10426 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10427 case PyUnicode_4BYTE_KIND:
10428 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10429 }
10430 assert(0);
10431 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010432}
10433
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010434static void
10435replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10436 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10437{
10438 int kind = PyUnicode_KIND(u);
10439 void *data = PyUnicode_DATA(u);
10440 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10441 if (kind == PyUnicode_1BYTE_KIND) {
10442 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10443 (Py_UCS1 *)data + len,
10444 u1, u2, maxcount);
10445 }
10446 else if (kind == PyUnicode_2BYTE_KIND) {
10447 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10448 (Py_UCS2 *)data + len,
10449 u1, u2, maxcount);
10450 }
10451 else {
10452 assert(kind == PyUnicode_4BYTE_KIND);
10453 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10454 (Py_UCS4 *)data + len,
10455 u1, u2, maxcount);
10456 }
10457}
10458
Alexander Belopolsky40018472011-02-26 01:02:56 +000010459static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460replace(PyObject *self, PyObject *str1,
10461 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010462{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 PyObject *u;
10464 char *sbuf = PyUnicode_DATA(self);
10465 char *buf1 = PyUnicode_DATA(str1);
10466 char *buf2 = PyUnicode_DATA(str2);
10467 int srelease = 0, release1 = 0, release2 = 0;
10468 int skind = PyUnicode_KIND(self);
10469 int kind1 = PyUnicode_KIND(str1);
10470 int kind2 = PyUnicode_KIND(str2);
10471 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10472 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10473 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010474 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010475 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010476
10477 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010478 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010480 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481
Victor Stinner59de0ee2011-10-07 10:01:28 +020010482 if (str1 == str2)
10483 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484
Victor Stinner49a0a212011-10-12 23:46:10 +020010485 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010486 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10487 if (maxchar < maxchar_str1)
10488 /* substring too wide to be present */
10489 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010490 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10491 /* Replacing str1 with str2 may cause a maxchar reduction in the
10492 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010493 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010494 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010495
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010497 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010499 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010501 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010502 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010503 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010504
Victor Stinner69ed0f42013-04-09 21:48:24 +020010505 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010506 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010507 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010508 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010509 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010510 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010511 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010512 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010513
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010514 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10515 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010516 }
10517 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010518 int rkind = skind;
10519 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010520 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010521
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010522 if (kind1 < rkind) {
10523 /* widen substring */
10524 buf1 = _PyUnicode_AsKind(str1, rkind);
10525 if (!buf1) goto error;
10526 release1 = 1;
10527 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010528 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010529 if (i < 0)
10530 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010531 if (rkind > kind2) {
10532 /* widen replacement */
10533 buf2 = _PyUnicode_AsKind(str2, rkind);
10534 if (!buf2) goto error;
10535 release2 = 1;
10536 }
10537 else if (rkind < kind2) {
10538 /* widen self and buf1 */
10539 rkind = kind2;
10540 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010541 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010542 sbuf = _PyUnicode_AsKind(self, rkind);
10543 if (!sbuf) goto error;
10544 srelease = 1;
10545 buf1 = _PyUnicode_AsKind(str1, rkind);
10546 if (!buf1) goto error;
10547 release1 = 1;
10548 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010549 u = PyUnicode_New(slen, maxchar);
10550 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010551 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010552 assert(PyUnicode_KIND(u) == rkind);
10553 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010554
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010555 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010556 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010557 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010559 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010560 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010561
10562 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010563 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010564 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010565 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010566 if (i == -1)
10567 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010568 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010570 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010572 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010573 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010574 }
10575 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010577 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 int rkind = skind;
10579 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010582 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 buf1 = _PyUnicode_AsKind(str1, rkind);
10584 if (!buf1) goto error;
10585 release1 = 1;
10586 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010587 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010588 if (n == 0)
10589 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010591 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 buf2 = _PyUnicode_AsKind(str2, rkind);
10593 if (!buf2) goto error;
10594 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010595 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010597 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 rkind = kind2;
10599 sbuf = _PyUnicode_AsKind(self, rkind);
10600 if (!sbuf) goto error;
10601 srelease = 1;
10602 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010603 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010604 buf1 = _PyUnicode_AsKind(str1, rkind);
10605 if (!buf1) goto error;
10606 release1 = 1;
10607 }
10608 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10609 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010610 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611 PyErr_SetString(PyExc_OverflowError,
10612 "replace string is too long");
10613 goto error;
10614 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010615 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010616 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010617 _Py_INCREF_UNICODE_EMPTY();
10618 if (!unicode_empty)
10619 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010620 u = unicode_empty;
10621 goto done;
10622 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010623 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 PyErr_SetString(PyExc_OverflowError,
10625 "replace string is too long");
10626 goto error;
10627 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010628 u = PyUnicode_New(new_size, maxchar);
10629 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010631 assert(PyUnicode_KIND(u) == rkind);
10632 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633 ires = i = 0;
10634 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010635 while (n-- > 0) {
10636 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010637 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010638 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010639 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010640 if (j == -1)
10641 break;
10642 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010643 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010644 memcpy(res + rkind * ires,
10645 sbuf + rkind * i,
10646 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010647 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010648 }
10649 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010650 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010651 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010653 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010654 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010655 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010657 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010659 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010660 memcpy(res + rkind * ires,
10661 sbuf + rkind * i,
10662 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010663 }
10664 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010665 /* interleave */
10666 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010667 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010668 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010669 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010670 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010671 if (--n <= 0)
10672 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010673 memcpy(res + rkind * ires,
10674 sbuf + rkind * i,
10675 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 ires++;
10677 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010678 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010679 memcpy(res + rkind * ires,
10680 sbuf + rkind * i,
10681 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010682 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010683 }
10684
10685 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010686 unicode_adjust_maxchar(&u);
10687 if (u == NULL)
10688 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010689 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010690
10691 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010692 if (srelease)
10693 PyMem_FREE(sbuf);
10694 if (release1)
10695 PyMem_FREE(buf1);
10696 if (release2)
10697 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010698 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010699 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010700
Benjamin Peterson29060642009-01-31 22:14:21 +000010701 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010702 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010703 if (srelease)
10704 PyMem_FREE(sbuf);
10705 if (release1)
10706 PyMem_FREE(buf1);
10707 if (release2)
10708 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010709 return unicode_result_unchanged(self);
10710
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010711 error:
10712 if (srelease && sbuf)
10713 PyMem_FREE(sbuf);
10714 if (release1 && buf1)
10715 PyMem_FREE(buf1);
10716 if (release2 && buf2)
10717 PyMem_FREE(buf2);
10718 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010719}
10720
10721/* --- Unicode Object Methods --------------------------------------------- */
10722
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010723PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010724 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010725\n\
10726Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010727characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010728
10729static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010730unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010731{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010732 if (PyUnicode_READY(self) == -1)
10733 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010734 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010735}
10736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010737PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010738 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010739\n\
10740Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010741have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010742
10743static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010744unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010745{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010746 if (PyUnicode_READY(self) == -1)
10747 return NULL;
10748 if (PyUnicode_GET_LENGTH(self) == 0)
10749 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010750 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010751}
10752
Benjamin Petersond5890c82012-01-14 13:23:30 -050010753PyDoc_STRVAR(casefold__doc__,
10754 "S.casefold() -> str\n\
10755\n\
10756Return a version of S suitable for caseless comparisons.");
10757
10758static PyObject *
10759unicode_casefold(PyObject *self)
10760{
10761 if (PyUnicode_READY(self) == -1)
10762 return NULL;
10763 if (PyUnicode_IS_ASCII(self))
10764 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010765 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010766}
10767
10768
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010769/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010770
10771static int
10772convert_uc(PyObject *obj, void *addr)
10773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010774 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010775
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010776 if (!PyUnicode_Check(obj)) {
10777 PyErr_Format(PyExc_TypeError,
10778 "The fill character must be a unicode character, "
10779 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010780 return 0;
10781 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010782 if (PyUnicode_READY(obj) < 0)
10783 return 0;
10784 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010785 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010786 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010787 return 0;
10788 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010789 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010790 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010791}
10792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010793PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010794 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010795\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010796Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010797done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798
10799static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010800unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010802 Py_ssize_t marg, left;
10803 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010804 Py_UCS4 fillchar = ' ';
10805
Victor Stinnere9a29352011-10-01 02:14:59 +020010806 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808
Benjamin Petersonbac79492012-01-14 13:34:47 -050010809 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810 return NULL;
10811
Victor Stinnerc4b49542011-12-11 22:44:26 +010010812 if (PyUnicode_GET_LENGTH(self) >= width)
10813 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010814
Victor Stinnerc4b49542011-12-11 22:44:26 +010010815 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816 left = marg / 2 + (marg & width & 1);
10817
Victor Stinner9310abb2011-10-05 00:59:23 +020010818 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010819}
10820
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010821/* This function assumes that str1 and str2 are readied by the caller. */
10822
Marc-André Lemburge5034372000-08-08 08:04:29 +000010823static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010824unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010825{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010826#define COMPARE(TYPE1, TYPE2) \
10827 do { \
10828 TYPE1* p1 = (TYPE1 *)data1; \
10829 TYPE2* p2 = (TYPE2 *)data2; \
10830 TYPE1* end = p1 + len; \
10831 Py_UCS4 c1, c2; \
10832 for (; p1 != end; p1++, p2++) { \
10833 c1 = *p1; \
10834 c2 = *p2; \
10835 if (c1 != c2) \
10836 return (c1 < c2) ? -1 : 1; \
10837 } \
10838 } \
10839 while (0)
10840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010841 int kind1, kind2;
10842 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010843 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010845 kind1 = PyUnicode_KIND(str1);
10846 kind2 = PyUnicode_KIND(str2);
10847 data1 = PyUnicode_DATA(str1);
10848 data2 = PyUnicode_DATA(str2);
10849 len1 = PyUnicode_GET_LENGTH(str1);
10850 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010851 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010852
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010853 switch(kind1) {
10854 case PyUnicode_1BYTE_KIND:
10855 {
10856 switch(kind2) {
10857 case PyUnicode_1BYTE_KIND:
10858 {
10859 int cmp = memcmp(data1, data2, len);
10860 /* normalize result of memcmp() into the range [-1; 1] */
10861 if (cmp < 0)
10862 return -1;
10863 if (cmp > 0)
10864 return 1;
10865 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010866 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010867 case PyUnicode_2BYTE_KIND:
10868 COMPARE(Py_UCS1, Py_UCS2);
10869 break;
10870 case PyUnicode_4BYTE_KIND:
10871 COMPARE(Py_UCS1, Py_UCS4);
10872 break;
10873 default:
10874 assert(0);
10875 }
10876 break;
10877 }
10878 case PyUnicode_2BYTE_KIND:
10879 {
10880 switch(kind2) {
10881 case PyUnicode_1BYTE_KIND:
10882 COMPARE(Py_UCS2, Py_UCS1);
10883 break;
10884 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010885 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010886 COMPARE(Py_UCS2, Py_UCS2);
10887 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010888 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010889 case PyUnicode_4BYTE_KIND:
10890 COMPARE(Py_UCS2, Py_UCS4);
10891 break;
10892 default:
10893 assert(0);
10894 }
10895 break;
10896 }
10897 case PyUnicode_4BYTE_KIND:
10898 {
10899 switch(kind2) {
10900 case PyUnicode_1BYTE_KIND:
10901 COMPARE(Py_UCS4, Py_UCS1);
10902 break;
10903 case PyUnicode_2BYTE_KIND:
10904 COMPARE(Py_UCS4, Py_UCS2);
10905 break;
10906 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010907 {
10908#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10909 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10910 /* normalize result of wmemcmp() into the range [-1; 1] */
10911 if (cmp < 0)
10912 return -1;
10913 if (cmp > 0)
10914 return 1;
10915#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010916 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010917#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010918 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010919 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010920 default:
10921 assert(0);
10922 }
10923 break;
10924 }
10925 default:
10926 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010927 }
10928
Victor Stinner770e19e2012-10-04 22:59:45 +020010929 if (len1 == len2)
10930 return 0;
10931 if (len1 < len2)
10932 return -1;
10933 else
10934 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010935
10936#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010937}
10938
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010939Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010940unicode_compare_eq(PyObject *str1, PyObject *str2)
10941{
10942 int kind;
10943 void *data1, *data2;
10944 Py_ssize_t len;
10945 int cmp;
10946
Victor Stinnere5567ad2012-10-23 02:48:49 +020010947 len = PyUnicode_GET_LENGTH(str1);
10948 if (PyUnicode_GET_LENGTH(str2) != len)
10949 return 0;
10950 kind = PyUnicode_KIND(str1);
10951 if (PyUnicode_KIND(str2) != kind)
10952 return 0;
10953 data1 = PyUnicode_DATA(str1);
10954 data2 = PyUnicode_DATA(str2);
10955
10956 cmp = memcmp(data1, data2, len * kind);
10957 return (cmp == 0);
10958}
10959
10960
Alexander Belopolsky40018472011-02-26 01:02:56 +000010961int
10962PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010963{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10965 if (PyUnicode_READY(left) == -1 ||
10966 PyUnicode_READY(right) == -1)
10967 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010968
10969 /* a string is equal to itself */
10970 if (left == right)
10971 return 0;
10972
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010973 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010974 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010975 PyErr_Format(PyExc_TypeError,
10976 "Can't compare %.100s and %.100s",
10977 left->ob_type->tp_name,
10978 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010979 return -1;
10980}
10981
Martin v. Löwis5b222132007-06-10 09:51:05 +000010982int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010983_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10984{
10985 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10986 if (right_str == NULL)
10987 return -1;
10988 return PyUnicode_Compare(left, right_str);
10989}
10990
10991int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010992PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10993{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010994 Py_ssize_t i;
10995 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 Py_UCS4 chr;
10997
Victor Stinner910337b2011-10-03 03:20:16 +020010998 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010999 if (PyUnicode_READY(uni) == -1)
11000 return -1;
11001 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011002 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011003 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011004 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011005 size_t len, len2 = strlen(str);
11006 int cmp;
11007
11008 len = Py_MIN(len1, len2);
11009 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011010 if (cmp != 0) {
11011 if (cmp < 0)
11012 return -1;
11013 else
11014 return 1;
11015 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011016 if (len1 > len2)
11017 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011018 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011019 return -1; /* str is longer */
11020 return 0;
11021 }
11022 else {
11023 void *data = PyUnicode_DATA(uni);
11024 /* Compare Unicode string and source character set string */
11025 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011026 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011027 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11028 /* This check keeps Python strings that end in '\0' from comparing equal
11029 to C strings identical up to that point. */
11030 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11031 return 1; /* uni is longer */
11032 if (str[i])
11033 return -1; /* str is longer */
11034 return 0;
11035 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011036}
11037
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011038
Benjamin Peterson29060642009-01-31 22:14:21 +000011039#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011040 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011041
Alexander Belopolsky40018472011-02-26 01:02:56 +000011042PyObject *
11043PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011044{
11045 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011046 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011047
Victor Stinnere5567ad2012-10-23 02:48:49 +020011048 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11049 Py_RETURN_NOTIMPLEMENTED;
11050
11051 if (PyUnicode_READY(left) == -1 ||
11052 PyUnicode_READY(right) == -1)
11053 return NULL;
11054
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011055 if (left == right) {
11056 switch (op) {
11057 case Py_EQ:
11058 case Py_LE:
11059 case Py_GE:
11060 /* a string is equal to itself */
11061 v = Py_True;
11062 break;
11063 case Py_NE:
11064 case Py_LT:
11065 case Py_GT:
11066 v = Py_False;
11067 break;
11068 default:
11069 PyErr_BadArgument();
11070 return NULL;
11071 }
11072 }
11073 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011074 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011075 result ^= (op == Py_NE);
11076 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011077 }
11078 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011079 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011080
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011081 /* Convert the return value to a Boolean */
11082 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011083 case Py_LE:
11084 v = TEST_COND(result <= 0);
11085 break;
11086 case Py_GE:
11087 v = TEST_COND(result >= 0);
11088 break;
11089 case Py_LT:
11090 v = TEST_COND(result == -1);
11091 break;
11092 case Py_GT:
11093 v = TEST_COND(result == 1);
11094 break;
11095 default:
11096 PyErr_BadArgument();
11097 return NULL;
11098 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011099 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011100 Py_INCREF(v);
11101 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011102}
11103
Alexander Belopolsky40018472011-02-26 01:02:56 +000011104int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011105_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11106{
11107 return unicode_eq(aa, bb);
11108}
11109
11110int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011111PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011112{
Victor Stinner77282cb2013-04-14 19:22:47 +020011113 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 void *buf1, *buf2;
11115 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011116 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011117
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011118 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011119 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011120 "'in <string>' requires string as left operand, not %.100s",
11121 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011122 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011123 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011124 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011125 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011126 if (ensure_unicode(str) < 0)
11127 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011129 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011130 kind2 = PyUnicode_KIND(substr);
11131 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011132 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011133 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011134 len2 = PyUnicode_GET_LENGTH(substr);
11135 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011136 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011137 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011138 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011139 if (len2 == 1) {
11140 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11141 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011142 return result;
11143 }
11144 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011145 buf2 = _PyUnicode_AsKind(substr, kind1);
11146 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011147 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149
Victor Stinner77282cb2013-04-14 19:22:47 +020011150 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 case PyUnicode_1BYTE_KIND:
11152 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11153 break;
11154 case PyUnicode_2BYTE_KIND:
11155 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11156 break;
11157 case PyUnicode_4BYTE_KIND:
11158 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11159 break;
11160 default:
11161 result = -1;
11162 assert(0);
11163 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011164
Victor Stinner77282cb2013-04-14 19:22:47 +020011165 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011166 PyMem_Free(buf2);
11167
Guido van Rossum403d68b2000-03-13 15:55:09 +000011168 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011169}
11170
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171/* Concat to string or Unicode object giving a new Unicode object. */
11172
Alexander Belopolsky40018472011-02-26 01:02:56 +000011173PyObject *
11174PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011176 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011177 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011178 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011180 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11181 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182
11183 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011184 if (left == unicode_empty)
11185 return PyUnicode_FromObject(right);
11186 if (right == unicode_empty)
11187 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011189 left_len = PyUnicode_GET_LENGTH(left);
11190 right_len = PyUnicode_GET_LENGTH(right);
11191 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011192 PyErr_SetString(PyExc_OverflowError,
11193 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011194 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011195 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011196 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011197
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011198 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11199 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011200 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011203 result = PyUnicode_New(new_len, maxchar);
11204 if (result == NULL)
11205 return NULL;
11206 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11207 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11208 assert(_PyUnicode_CheckConsistency(result, 1));
11209 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210}
11211
Walter Dörwald1ab83302007-05-18 17:15:44 +000011212void
Victor Stinner23e56682011-10-03 03:54:37 +020011213PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011214{
Victor Stinner23e56682011-10-03 03:54:37 +020011215 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011216 Py_UCS4 maxchar, maxchar2;
11217 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011218
11219 if (p_left == NULL) {
11220 if (!PyErr_Occurred())
11221 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011222 return;
11223 }
Victor Stinner23e56682011-10-03 03:54:37 +020011224 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011225 if (right == NULL || left == NULL
11226 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011227 if (!PyErr_Occurred())
11228 PyErr_BadInternalCall();
11229 goto error;
11230 }
11231
Benjamin Petersonbac79492012-01-14 13:34:47 -050011232 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011233 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011234 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011235 goto error;
11236
Victor Stinner488fa492011-12-12 00:01:39 +010011237 /* Shortcuts */
11238 if (left == unicode_empty) {
11239 Py_DECREF(left);
11240 Py_INCREF(right);
11241 *p_left = right;
11242 return;
11243 }
11244 if (right == unicode_empty)
11245 return;
11246
11247 left_len = PyUnicode_GET_LENGTH(left);
11248 right_len = PyUnicode_GET_LENGTH(right);
11249 if (left_len > PY_SSIZE_T_MAX - right_len) {
11250 PyErr_SetString(PyExc_OverflowError,
11251 "strings are too large to concat");
11252 goto error;
11253 }
11254 new_len = left_len + right_len;
11255
11256 if (unicode_modifiable(left)
11257 && PyUnicode_CheckExact(right)
11258 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011259 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11260 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011261 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011262 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011263 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11264 {
11265 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011266 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011267 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011268
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011269 /* copy 'right' into the newly allocated area of 'left' */
11270 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011271 }
Victor Stinner488fa492011-12-12 00:01:39 +010011272 else {
11273 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11274 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011275 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011276
Victor Stinner488fa492011-12-12 00:01:39 +010011277 /* Concat the two Unicode strings */
11278 res = PyUnicode_New(new_len, maxchar);
11279 if (res == NULL)
11280 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011281 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11282 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011283 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011284 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011285 }
11286 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011287 return;
11288
11289error:
Victor Stinner488fa492011-12-12 00:01:39 +010011290 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011291}
11292
11293void
11294PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11295{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011296 PyUnicode_Append(pleft, right);
11297 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011298}
11299
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011300/*
11301Wraps stringlib_parse_args_finds() and additionally ensures that the
11302first argument is a unicode object.
11303*/
11304
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011305static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011306parse_args_finds_unicode(const char * function_name, PyObject *args,
11307 PyObject **substring,
11308 Py_ssize_t *start, Py_ssize_t *end)
11309{
11310 if(stringlib_parse_args_finds(function_name, args, substring,
11311 start, end)) {
11312 if (ensure_unicode(*substring) < 0)
11313 return 0;
11314 return 1;
11315 }
11316 return 0;
11317}
11318
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011319PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011320 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011322Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011323string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011324interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011325
11326static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011327unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011329 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011330 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011331 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011332 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011333 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011334 void *buf1, *buf2;
11335 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011337 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011338 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340 kind1 = PyUnicode_KIND(self);
11341 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011342 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011343 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011344
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 len1 = PyUnicode_GET_LENGTH(self);
11346 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011348 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011349 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011350
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011351 buf1 = PyUnicode_DATA(self);
11352 buf2 = PyUnicode_DATA(substring);
11353 if (kind2 != kind1) {
11354 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011355 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011356 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011357 }
11358 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011359 case PyUnicode_1BYTE_KIND:
11360 iresult = ucs1lib_count(
11361 ((Py_UCS1*)buf1) + start, end - start,
11362 buf2, len2, PY_SSIZE_T_MAX
11363 );
11364 break;
11365 case PyUnicode_2BYTE_KIND:
11366 iresult = ucs2lib_count(
11367 ((Py_UCS2*)buf1) + start, end - start,
11368 buf2, len2, PY_SSIZE_T_MAX
11369 );
11370 break;
11371 case PyUnicode_4BYTE_KIND:
11372 iresult = ucs4lib_count(
11373 ((Py_UCS4*)buf1) + start, end - start,
11374 buf2, len2, PY_SSIZE_T_MAX
11375 );
11376 break;
11377 default:
11378 assert(0); iresult = 0;
11379 }
11380
11381 result = PyLong_FromSsize_t(iresult);
11382
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011383 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011384 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386 return result;
11387}
11388
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011389PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011390 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011392Encode S using the codec registered for encoding. Default encoding\n\
11393is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011394handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011395a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11396'xmlcharrefreplace' as well as any other name registered with\n\
11397codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398
11399static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011400unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011402 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403 char *encoding = NULL;
11404 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011405
Benjamin Peterson308d6372009-09-18 21:42:35 +000011406 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11407 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011409 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011410}
11411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011412PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011413 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414\n\
11415Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011416If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417
11418static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011419unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011421 Py_ssize_t i, j, line_pos, src_len, incr;
11422 Py_UCS4 ch;
11423 PyObject *u;
11424 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011425 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011427 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011428 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429
Ezio Melotti745d54d2013-11-16 19:10:57 +020011430 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11431 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011432 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433
Antoine Pitrou22425222011-10-04 19:10:51 +020011434 if (PyUnicode_READY(self) == -1)
11435 return NULL;
11436
Thomas Wouters7e474022000-07-16 12:04:32 +000011437 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011438 src_len = PyUnicode_GET_LENGTH(self);
11439 i = j = line_pos = 0;
11440 kind = PyUnicode_KIND(self);
11441 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011442 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011443 for (; i < src_len; i++) {
11444 ch = PyUnicode_READ(kind, src_data, i);
11445 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011446 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011447 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011448 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011449 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011450 goto overflow;
11451 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011452 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011453 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011454 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011456 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011457 goto overflow;
11458 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011460 if (ch == '\n' || ch == '\r')
11461 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011463 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011464 if (!found)
11465 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011466
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011468 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469 if (!u)
11470 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011471 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472
Antoine Pitroue71d5742011-10-04 15:55:09 +020011473 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474
Antoine Pitroue71d5742011-10-04 15:55:09 +020011475 for (; i < src_len; i++) {
11476 ch = PyUnicode_READ(kind, src_data, i);
11477 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011479 incr = tabsize - (line_pos % tabsize);
11480 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011481 FILL(kind, dest_data, ' ', j, incr);
11482 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011484 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 line_pos++;
11487 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011488 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011489 if (ch == '\n' || ch == '\r')
11490 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011492 }
11493 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011494 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011495
Antoine Pitroue71d5742011-10-04 15:55:09 +020011496 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011497 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11498 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499}
11500
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011501PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011502 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503\n\
11504Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011505such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506arguments start and end are interpreted as in slice notation.\n\
11507\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011508Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509
11510static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011513 /* initialize variables to prevent gcc warning */
11514 PyObject *substring = NULL;
11515 Py_ssize_t start = 0;
11516 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011517 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011519 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011522 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011523 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011524
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011525 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 if (result == -2)
11528 return NULL;
11529
Christian Heimes217cfd12007-12-02 14:31:20 +000011530 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531}
11532
11533static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011534unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011536 void *data;
11537 enum PyUnicode_Kind kind;
11538 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011539
11540 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11541 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011543 }
11544 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11545 PyErr_SetString(PyExc_IndexError, "string index out of range");
11546 return NULL;
11547 }
11548 kind = PyUnicode_KIND(self);
11549 data = PyUnicode_DATA(self);
11550 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011551 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552}
11553
Guido van Rossumc2504932007-09-18 19:42:40 +000011554/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011555 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011556static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011557unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558{
Guido van Rossumc2504932007-09-18 19:42:40 +000011559 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011560 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011561
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011562#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011563 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011564#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011565 if (_PyUnicode_HASH(self) != -1)
11566 return _PyUnicode_HASH(self);
11567 if (PyUnicode_READY(self) == -1)
11568 return -1;
11569 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011570 /*
11571 We make the hash of the empty string be 0, rather than using
11572 (prefix ^ suffix), since this slightly obfuscates the hash secret
11573 */
11574 if (len == 0) {
11575 _PyUnicode_HASH(self) = 0;
11576 return 0;
11577 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011578 x = _Py_HashBytes(PyUnicode_DATA(self),
11579 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011581 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011582}
11583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011584PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011585 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011587Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588
11589static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590unicode_index(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 */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011593 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011594 PyObject *substring = NULL;
11595 Py_ssize_t start = 0;
11596 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011598 if (!parse_args_finds_unicode("index", 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
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609 if (result < 0) {
11610 PyErr_SetString(PyExc_ValueError, "substring not found");
11611 return NULL;
11612 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011613
Christian Heimes217cfd12007-12-02 14:31:20 +000011614 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615}
11616
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011617PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011620Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011621at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622
11623static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011624unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 Py_ssize_t i, length;
11627 int kind;
11628 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011629 int cased;
11630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631 if (PyUnicode_READY(self) == -1)
11632 return NULL;
11633 length = PyUnicode_GET_LENGTH(self);
11634 kind = PyUnicode_KIND(self);
11635 data = PyUnicode_DATA(self);
11636
Guido van Rossumd57fd912000-03-10 22:53:23 +000011637 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 if (length == 1)
11639 return PyBool_FromLong(
11640 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011642 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011644 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011645
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011647 for (i = 0; i < length; i++) {
11648 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011649
Benjamin Peterson29060642009-01-31 22:14:21 +000011650 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11651 return PyBool_FromLong(0);
11652 else if (!cased && Py_UNICODE_ISLOWER(ch))
11653 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011654 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011655 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011656}
11657
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011658PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011659 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011661Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011662at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663
11664static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011665unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 Py_ssize_t i, length;
11668 int kind;
11669 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670 int cased;
11671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 if (PyUnicode_READY(self) == -1)
11673 return NULL;
11674 length = PyUnicode_GET_LENGTH(self);
11675 kind = PyUnicode_KIND(self);
11676 data = PyUnicode_DATA(self);
11677
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011679 if (length == 1)
11680 return PyBool_FromLong(
11681 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011682
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011683 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011685 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011686
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688 for (i = 0; i < length; i++) {
11689 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011690
Benjamin Peterson29060642009-01-31 22:14:21 +000011691 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11692 return PyBool_FromLong(0);
11693 else if (!cased && Py_UNICODE_ISUPPER(ch))
11694 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011696 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697}
11698
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011699PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011700 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011702Return True if S is a titlecased string and there is at least one\n\
11703character in S, i.e. upper- and titlecase characters may only\n\
11704follow uncased characters and lowercase characters only cased ones.\n\
11705Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706
11707static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011708unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 Py_ssize_t i, length;
11711 int kind;
11712 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713 int cased, previous_is_cased;
11714
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 if (PyUnicode_READY(self) == -1)
11716 return NULL;
11717 length = PyUnicode_GET_LENGTH(self);
11718 kind = PyUnicode_KIND(self);
11719 data = PyUnicode_DATA(self);
11720
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 if (length == 1) {
11723 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11724 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11725 (Py_UNICODE_ISUPPER(ch) != 0));
11726 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011728 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011730 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011731
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732 cased = 0;
11733 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011734 for (i = 0; i < length; i++) {
11735 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011736
Benjamin Peterson29060642009-01-31 22:14:21 +000011737 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11738 if (previous_is_cased)
11739 return PyBool_FromLong(0);
11740 previous_is_cased = 1;
11741 cased = 1;
11742 }
11743 else if (Py_UNICODE_ISLOWER(ch)) {
11744 if (!previous_is_cased)
11745 return PyBool_FromLong(0);
11746 previous_is_cased = 1;
11747 cased = 1;
11748 }
11749 else
11750 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011752 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011753}
11754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011755PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011756 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011758Return True if all characters in S are whitespace\n\
11759and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760
11761static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011762unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011764 Py_ssize_t i, length;
11765 int kind;
11766 void *data;
11767
11768 if (PyUnicode_READY(self) == -1)
11769 return NULL;
11770 length = PyUnicode_GET_LENGTH(self);
11771 kind = PyUnicode_KIND(self);
11772 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 if (length == 1)
11776 return PyBool_FromLong(
11777 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011779 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011781 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011783 for (i = 0; i < length; i++) {
11784 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011785 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011786 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011787 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011788 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789}
11790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011791PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011792 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011793\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011794Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011795and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011796
11797static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011798unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011799{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 Py_ssize_t i, length;
11801 int kind;
11802 void *data;
11803
11804 if (PyUnicode_READY(self) == -1)
11805 return NULL;
11806 length = PyUnicode_GET_LENGTH(self);
11807 kind = PyUnicode_KIND(self);
11808 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011809
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011810 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 if (length == 1)
11812 return PyBool_FromLong(
11813 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011814
11815 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011819 for (i = 0; i < length; i++) {
11820 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011821 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011822 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011823 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011824}
11825
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011826PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011827 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011828\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011829Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011830and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011831
11832static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011833unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011834{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 int kind;
11836 void *data;
11837 Py_ssize_t len, i;
11838
11839 if (PyUnicode_READY(self) == -1)
11840 return NULL;
11841
11842 kind = PyUnicode_KIND(self);
11843 data = PyUnicode_DATA(self);
11844 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011845
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011846 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011847 if (len == 1) {
11848 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11849 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11850 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011851
11852 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011853 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011854 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011855
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011856 for (i = 0; i < len; i++) {
11857 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011858 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011859 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011860 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011861 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011862}
11863
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011864PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011865 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011867Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011868False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869
11870static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011871unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011873 Py_ssize_t i, length;
11874 int kind;
11875 void *data;
11876
11877 if (PyUnicode_READY(self) == -1)
11878 return NULL;
11879 length = PyUnicode_GET_LENGTH(self);
11880 kind = PyUnicode_KIND(self);
11881 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011884 if (length == 1)
11885 return PyBool_FromLong(
11886 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011888 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011890 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011892 for (i = 0; i < length; i++) {
11893 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011894 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011896 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897}
11898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011899PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011900 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011901\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011902Return True if all characters in S are digits\n\
11903and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904
11905static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011906unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908 Py_ssize_t i, length;
11909 int kind;
11910 void *data;
11911
11912 if (PyUnicode_READY(self) == -1)
11913 return NULL;
11914 length = PyUnicode_GET_LENGTH(self);
11915 kind = PyUnicode_KIND(self);
11916 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917
Guido van Rossumd57fd912000-03-10 22:53:23 +000011918 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011919 if (length == 1) {
11920 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11921 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11922 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011924 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011926 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011927
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 for (i = 0; i < length; i++) {
11929 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011930 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011932 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933}
11934
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011935PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011936 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011938Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011939False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940
11941static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011942unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011944 Py_ssize_t i, length;
11945 int kind;
11946 void *data;
11947
11948 if (PyUnicode_READY(self) == -1)
11949 return NULL;
11950 length = PyUnicode_GET_LENGTH(self);
11951 kind = PyUnicode_KIND(self);
11952 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011955 if (length == 1)
11956 return PyBool_FromLong(
11957 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011959 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011961 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011962
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011963 for (i = 0; i < length; i++) {
11964 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011965 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011967 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968}
11969
Martin v. Löwis47383402007-08-15 07:32:56 +000011970int
11971PyUnicode_IsIdentifier(PyObject *self)
11972{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973 int kind;
11974 void *data;
11975 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011976 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011978 if (PyUnicode_READY(self) == -1) {
11979 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011980 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 }
11982
11983 /* Special case for empty strings */
11984 if (PyUnicode_GET_LENGTH(self) == 0)
11985 return 0;
11986 kind = PyUnicode_KIND(self);
11987 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011988
11989 /* PEP 3131 says that the first character must be in
11990 XID_Start and subsequent characters in XID_Continue,
11991 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011992 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011993 letters, digits, underscore). However, given the current
11994 definition of XID_Start and XID_Continue, it is sufficient
11995 to check just for these, except that _ must be allowed
11996 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011997 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011998 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011999 return 0;
12000
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012001 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012003 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012004 return 1;
12005}
12006
12007PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012008 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012009\n\
12010Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012011to the language definition.\n\
12012\n\
12013Use keyword.iskeyword() to test for reserved identifiers\n\
12014such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012015
12016static PyObject*
12017unicode_isidentifier(PyObject *self)
12018{
12019 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12020}
12021
Georg Brandl559e5d72008-06-11 18:37:52 +000012022PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012023 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012024\n\
12025Return True if all characters in S are considered\n\
12026printable in repr() or S is empty, False otherwise.");
12027
12028static PyObject*
12029unicode_isprintable(PyObject *self)
12030{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012031 Py_ssize_t i, length;
12032 int kind;
12033 void *data;
12034
12035 if (PyUnicode_READY(self) == -1)
12036 return NULL;
12037 length = PyUnicode_GET_LENGTH(self);
12038 kind = PyUnicode_KIND(self);
12039 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012040
12041 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012042 if (length == 1)
12043 return PyBool_FromLong(
12044 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 for (i = 0; i < length; i++) {
12047 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012048 Py_RETURN_FALSE;
12049 }
12050 }
12051 Py_RETURN_TRUE;
12052}
12053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012054PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012055 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056\n\
12057Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012058iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012059
12060static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012061unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012063 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012064}
12065
Martin v. Löwis18e16552006-02-15 17:27:45 +000012066static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012067unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012068{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 if (PyUnicode_READY(self) == -1)
12070 return -1;
12071 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012072}
12073
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012074PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012075 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012076\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012077Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012078done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079
12080static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012081unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012082{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012083 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012084 Py_UCS4 fillchar = ' ';
12085
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012086 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087 return NULL;
12088
Benjamin Petersonbac79492012-01-14 13:34:47 -050012089 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012090 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012091
Victor Stinnerc4b49542011-12-11 22:44:26 +010012092 if (PyUnicode_GET_LENGTH(self) >= width)
12093 return unicode_result_unchanged(self);
12094
12095 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096}
12097
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012098PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012099 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012100\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012101Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102
12103static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012104unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012106 if (PyUnicode_READY(self) == -1)
12107 return NULL;
12108 if (PyUnicode_IS_ASCII(self))
12109 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012110 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111}
12112
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012113#define LEFTSTRIP 0
12114#define RIGHTSTRIP 1
12115#define BOTHSTRIP 2
12116
12117/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012118static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012119
12120#define STRIPNAME(i) (stripformat[i]+3)
12121
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012122/* externally visible for str.strip(unicode) */
12123PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012124_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012125{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012126 void *data;
12127 int kind;
12128 Py_ssize_t i, j, len;
12129 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012130 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012131
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012132 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12133 return NULL;
12134
12135 kind = PyUnicode_KIND(self);
12136 data = PyUnicode_DATA(self);
12137 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012138 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012139 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12140 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012141 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012142
Benjamin Peterson14339b62009-01-31 16:36:08 +000012143 i = 0;
12144 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012145 while (i < len) {
12146 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12147 if (!BLOOM(sepmask, ch))
12148 break;
12149 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12150 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012151 i++;
12152 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012153 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012154
Benjamin Peterson14339b62009-01-31 16:36:08 +000012155 j = len;
12156 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012157 j--;
12158 while (j >= i) {
12159 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12160 if (!BLOOM(sepmask, ch))
12161 break;
12162 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12163 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012164 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012165 }
12166
Benjamin Peterson29060642009-01-31 22:14:21 +000012167 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012168 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012169
Victor Stinner7931d9a2011-11-04 00:22:48 +010012170 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012171}
12172
12173PyObject*
12174PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12175{
12176 unsigned char *data;
12177 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012178 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012179
Victor Stinnerde636f32011-10-01 03:55:54 +020012180 if (PyUnicode_READY(self) == -1)
12181 return NULL;
12182
Victor Stinner684d5fd2012-05-03 02:32:34 +020012183 length = PyUnicode_GET_LENGTH(self);
12184 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012185
Victor Stinner684d5fd2012-05-03 02:32:34 +020012186 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012187 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012188
Victor Stinnerde636f32011-10-01 03:55:54 +020012189 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012190 PyErr_SetString(PyExc_IndexError, "string index out of range");
12191 return NULL;
12192 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012193 if (start >= length || end < start)
12194 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012195
Victor Stinner684d5fd2012-05-03 02:32:34 +020012196 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012197 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012198 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012199 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012200 }
12201 else {
12202 kind = PyUnicode_KIND(self);
12203 data = PyUnicode_1BYTE_DATA(self);
12204 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012205 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012206 length);
12207 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012208}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209
12210static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012211do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 Py_ssize_t len, i, j;
12214
12215 if (PyUnicode_READY(self) == -1)
12216 return NULL;
12217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012218 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012219
Victor Stinnercc7af722013-04-09 22:39:24 +020012220 if (PyUnicode_IS_ASCII(self)) {
12221 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12222
12223 i = 0;
12224 if (striptype != RIGHTSTRIP) {
12225 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012226 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012227 if (!_Py_ascii_whitespace[ch])
12228 break;
12229 i++;
12230 }
12231 }
12232
12233 j = len;
12234 if (striptype != LEFTSTRIP) {
12235 j--;
12236 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012237 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012238 if (!_Py_ascii_whitespace[ch])
12239 break;
12240 j--;
12241 }
12242 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012243 }
12244 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012245 else {
12246 int kind = PyUnicode_KIND(self);
12247 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012248
Victor Stinnercc7af722013-04-09 22:39:24 +020012249 i = 0;
12250 if (striptype != RIGHTSTRIP) {
12251 while (i < len) {
12252 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12253 if (!Py_UNICODE_ISSPACE(ch))
12254 break;
12255 i++;
12256 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012257 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012258
12259 j = len;
12260 if (striptype != LEFTSTRIP) {
12261 j--;
12262 while (j >= i) {
12263 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12264 if (!Py_UNICODE_ISSPACE(ch))
12265 break;
12266 j--;
12267 }
12268 j++;
12269 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012270 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012271
Victor Stinner7931d9a2011-11-04 00:22:48 +010012272 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012273}
12274
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012275
12276static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012277do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012278{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012279 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012280
Serhiy Storchakac6792272013-10-19 21:03:34 +030012281 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012282 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012283
Benjamin Peterson14339b62009-01-31 16:36:08 +000012284 if (sep != NULL && sep != Py_None) {
12285 if (PyUnicode_Check(sep))
12286 return _PyUnicode_XStrip(self, striptype, sep);
12287 else {
12288 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012289 "%s arg must be None or str",
12290 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012291 return NULL;
12292 }
12293 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012294
Benjamin Peterson14339b62009-01-31 16:36:08 +000012295 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012296}
12297
12298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012299PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012300 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012301\n\
12302Return a copy of the string S with leading and trailing\n\
12303whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012304If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012305
12306static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012307unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012308{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012309 if (PyTuple_GET_SIZE(args) == 0)
12310 return do_strip(self, BOTHSTRIP); /* Common case */
12311 else
12312 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012313}
12314
12315
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012316PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012317 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012318\n\
12319Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012320If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012321
12322static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012323unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012324{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012325 if (PyTuple_GET_SIZE(args) == 0)
12326 return do_strip(self, LEFTSTRIP); /* Common case */
12327 else
12328 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012329}
12330
12331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012332PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012333 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012334\n\
12335Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012336If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012337
12338static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012339unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012340{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012341 if (PyTuple_GET_SIZE(args) == 0)
12342 return do_strip(self, RIGHTSTRIP); /* Common case */
12343 else
12344 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012345}
12346
12347
Guido van Rossumd57fd912000-03-10 22:53:23 +000012348static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012349unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012350{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012351 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012353
Serhiy Storchaka05997252013-01-26 12:14:02 +020012354 if (len < 1)
12355 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012356
Victor Stinnerc4b49542011-12-11 22:44:26 +010012357 /* no repeat, return original string */
12358 if (len == 1)
12359 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012360
Benjamin Petersonbac79492012-01-14 13:34:47 -050012361 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362 return NULL;
12363
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012364 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012365 PyErr_SetString(PyExc_OverflowError,
12366 "repeated string is too long");
12367 return NULL;
12368 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012370
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012371 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372 if (!u)
12373 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012374 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012375
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012376 if (PyUnicode_GET_LENGTH(str) == 1) {
12377 const int kind = PyUnicode_KIND(str);
12378 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012379 if (kind == PyUnicode_1BYTE_KIND) {
12380 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012381 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012382 }
12383 else if (kind == PyUnicode_2BYTE_KIND) {
12384 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012385 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012386 ucs2[n] = fill_char;
12387 } else {
12388 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12389 assert(kind == PyUnicode_4BYTE_KIND);
12390 for (n = 0; n < len; ++n)
12391 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012392 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012393 }
12394 else {
12395 /* number of characters copied this far */
12396 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012397 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012398 char *to = (char *) PyUnicode_DATA(u);
12399 Py_MEMCPY(to, PyUnicode_DATA(str),
12400 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012401 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012402 n = (done <= nchars-done) ? done : nchars-done;
12403 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012404 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012405 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012406 }
12407
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012408 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012409 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012410}
12411
Alexander Belopolsky40018472011-02-26 01:02:56 +000012412PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012413PyUnicode_Replace(PyObject *str,
12414 PyObject *substr,
12415 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012416 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012417{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012418 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12419 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012420 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012421 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012422}
12423
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012424PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012425 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012426\n\
12427Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012428old replaced by new. If the optional argument count is\n\
12429given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012430
12431static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012432unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012433{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012434 PyObject *str1;
12435 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012436 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012437
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012438 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012439 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012440 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012441 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012442 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012443}
12444
Alexander Belopolsky40018472011-02-26 01:02:56 +000012445static PyObject *
12446unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012447{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012448 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012449 Py_ssize_t isize;
12450 Py_ssize_t osize, squote, dquote, i, o;
12451 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012452 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012453 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012455 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012456 return NULL;
12457
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012458 isize = PyUnicode_GET_LENGTH(unicode);
12459 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012461 /* Compute length of output, quote characters, and
12462 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012463 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012464 max = 127;
12465 squote = dquote = 0;
12466 ikind = PyUnicode_KIND(unicode);
12467 for (i = 0; i < isize; i++) {
12468 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012469 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012470 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012471 case '\'': squote++; break;
12472 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012474 incr = 2;
12475 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476 default:
12477 /* Fast-path ASCII */
12478 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012479 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012481 ;
12482 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012483 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012484 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012485 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012487 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012488 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012489 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012490 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012491 if (osize > PY_SSIZE_T_MAX - incr) {
12492 PyErr_SetString(PyExc_OverflowError,
12493 "string is too long to generate repr");
12494 return NULL;
12495 }
12496 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497 }
12498
12499 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012500 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012501 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012502 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012503 if (dquote)
12504 /* Both squote and dquote present. Use squote,
12505 and escape them */
12506 osize += squote;
12507 else
12508 quote = '"';
12509 }
Victor Stinner55c08782013-04-14 18:45:39 +020012510 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012511
12512 repr = PyUnicode_New(osize, max);
12513 if (repr == NULL)
12514 return NULL;
12515 okind = PyUnicode_KIND(repr);
12516 odata = PyUnicode_DATA(repr);
12517
12518 PyUnicode_WRITE(okind, odata, 0, quote);
12519 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012520 if (unchanged) {
12521 _PyUnicode_FastCopyCharacters(repr, 1,
12522 unicode, 0,
12523 isize);
12524 }
12525 else {
12526 for (i = 0, o = 1; i < isize; i++) {
12527 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012528
Victor Stinner55c08782013-04-14 18:45:39 +020012529 /* Escape quotes and backslashes */
12530 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012531 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012532 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012533 continue;
12534 }
12535
12536 /* Map special whitespace to '\t', \n', '\r' */
12537 if (ch == '\t') {
12538 PyUnicode_WRITE(okind, odata, o++, '\\');
12539 PyUnicode_WRITE(okind, odata, o++, 't');
12540 }
12541 else if (ch == '\n') {
12542 PyUnicode_WRITE(okind, odata, o++, '\\');
12543 PyUnicode_WRITE(okind, odata, o++, 'n');
12544 }
12545 else if (ch == '\r') {
12546 PyUnicode_WRITE(okind, odata, o++, '\\');
12547 PyUnicode_WRITE(okind, odata, o++, 'r');
12548 }
12549
12550 /* Map non-printable US ASCII to '\xhh' */
12551 else if (ch < ' ' || ch == 0x7F) {
12552 PyUnicode_WRITE(okind, odata, o++, '\\');
12553 PyUnicode_WRITE(okind, odata, o++, 'x');
12554 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12555 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12556 }
12557
12558 /* Copy ASCII characters as-is */
12559 else if (ch < 0x7F) {
12560 PyUnicode_WRITE(okind, odata, o++, ch);
12561 }
12562
12563 /* Non-ASCII characters */
12564 else {
12565 /* Map Unicode whitespace and control characters
12566 (categories Z* and C* except ASCII space)
12567 */
12568 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12569 PyUnicode_WRITE(okind, odata, o++, '\\');
12570 /* Map 8-bit characters to '\xhh' */
12571 if (ch <= 0xff) {
12572 PyUnicode_WRITE(okind, odata, o++, 'x');
12573 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12574 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12575 }
12576 /* Map 16-bit characters to '\uxxxx' */
12577 else if (ch <= 0xffff) {
12578 PyUnicode_WRITE(okind, odata, o++, 'u');
12579 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12580 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12581 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12582 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12583 }
12584 /* Map 21-bit characters to '\U00xxxxxx' */
12585 else {
12586 PyUnicode_WRITE(okind, odata, o++, 'U');
12587 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12588 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12589 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12590 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12591 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12592 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12593 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12594 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12595 }
12596 }
12597 /* Copy characters as-is */
12598 else {
12599 PyUnicode_WRITE(okind, odata, o++, ch);
12600 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012601 }
12602 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012603 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012604 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012605 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012606 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012607}
12608
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012609PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012610 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611\n\
12612Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012613such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012614arguments start and end are interpreted as in slice notation.\n\
12615\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012616Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617
12618static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012619unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012620{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012621 /* initialize variables to prevent gcc warning */
12622 PyObject *substring = NULL;
12623 Py_ssize_t start = 0;
12624 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012625 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012627 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012628 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012630 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012631 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012632
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012633 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012635 if (result == -2)
12636 return NULL;
12637
Christian Heimes217cfd12007-12-02 14:31:20 +000012638 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012639}
12640
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012641PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012642 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012643\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012644Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012645
12646static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012647unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012649 /* initialize variables to prevent gcc warning */
12650 PyObject *substring = NULL;
12651 Py_ssize_t start = 0;
12652 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012653 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012655 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012656 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012657
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012658 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012659 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012661 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012662
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012663 if (result == -2)
12664 return NULL;
12665
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666 if (result < 0) {
12667 PyErr_SetString(PyExc_ValueError, "substring not found");
12668 return NULL;
12669 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012670
Christian Heimes217cfd12007-12-02 14:31:20 +000012671 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012672}
12673
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012674PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012675 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012677Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012678done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012679
12680static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012681unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012683 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012684 Py_UCS4 fillchar = ' ';
12685
Victor Stinnere9a29352011-10-01 02:14:59 +020012686 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012687 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012688
Benjamin Petersonbac79492012-01-14 13:34:47 -050012689 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690 return NULL;
12691
Victor Stinnerc4b49542011-12-11 22:44:26 +010012692 if (PyUnicode_GET_LENGTH(self) >= width)
12693 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694
Victor Stinnerc4b49542011-12-11 22:44:26 +010012695 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696}
12697
Alexander Belopolsky40018472011-02-26 01:02:56 +000012698PyObject *
12699PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012701 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012702 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012704 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705}
12706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012707PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012708 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709\n\
12710Return a list of the words in S, using sep as the\n\
12711delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012712splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012713whitespace string is a separator and empty strings are\n\
12714removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012715
12716static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012717unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012719 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012721 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012723 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12724 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725 return NULL;
12726
12727 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012728 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012729
12730 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012731 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012732
12733 PyErr_Format(PyExc_TypeError,
12734 "must be str or None, not %.100s",
12735 Py_TYPE(substring)->tp_name);
12736 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012737}
12738
Thomas Wouters477c8d52006-05-27 19:21:47 +000012739PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012740PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012741{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012742 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012743 int kind1, kind2;
12744 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012746
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012747 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012748 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012749
Victor Stinner14f8f022011-10-05 20:58:25 +020012750 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012751 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012752 len1 = PyUnicode_GET_LENGTH(str_obj);
12753 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012754 if (kind1 < kind2 || len1 < len2) {
12755 _Py_INCREF_UNICODE_EMPTY();
12756 if (!unicode_empty)
12757 out = NULL;
12758 else {
12759 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12760 Py_DECREF(unicode_empty);
12761 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012762 return out;
12763 }
12764 buf1 = PyUnicode_DATA(str_obj);
12765 buf2 = PyUnicode_DATA(sep_obj);
12766 if (kind2 != kind1) {
12767 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12768 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012769 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012770 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012771
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012772 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012773 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012774 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12775 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12776 else
12777 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012778 break;
12779 case PyUnicode_2BYTE_KIND:
12780 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12781 break;
12782 case PyUnicode_4BYTE_KIND:
12783 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12784 break;
12785 default:
12786 assert(0);
12787 out = 0;
12788 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012789
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012790 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012791 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012792
12793 return out;
12794}
12795
12796
12797PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012798PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012799{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012800 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012801 int kind1, kind2;
12802 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012803 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012804
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012805 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012806 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012807
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012808 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012809 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012810 len1 = PyUnicode_GET_LENGTH(str_obj);
12811 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012812 if (kind1 < kind2 || len1 < len2) {
12813 _Py_INCREF_UNICODE_EMPTY();
12814 if (!unicode_empty)
12815 out = NULL;
12816 else {
12817 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12818 Py_DECREF(unicode_empty);
12819 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012820 return out;
12821 }
12822 buf1 = PyUnicode_DATA(str_obj);
12823 buf2 = PyUnicode_DATA(sep_obj);
12824 if (kind2 != kind1) {
12825 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12826 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012827 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012828 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012829
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012830 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012831 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012832 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12833 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12834 else
12835 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012836 break;
12837 case PyUnicode_2BYTE_KIND:
12838 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12839 break;
12840 case PyUnicode_4BYTE_KIND:
12841 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12842 break;
12843 default:
12844 assert(0);
12845 out = 0;
12846 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012847
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012848 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012849 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012850
12851 return out;
12852}
12853
12854PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012855 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012856\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012857Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012858the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012859found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012860
12861static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012862unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012863{
Victor Stinner9310abb2011-10-05 00:59:23 +020012864 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012865}
12866
12867PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012868 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012869\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012870Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012871the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012872separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012873
12874static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012875unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012876{
Victor Stinner9310abb2011-10-05 00:59:23 +020012877 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012878}
12879
Alexander Belopolsky40018472011-02-26 01:02:56 +000012880PyObject *
12881PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012882{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012883 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012884 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012885
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012886 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012887}
12888
12889PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012890 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012891\n\
12892Return a list of the words in S, using sep as the\n\
12893delimiter string, starting at the end of the string and\n\
12894working to the front. If maxsplit is given, at most maxsplit\n\
12895splits are done. If sep is not specified, any whitespace string\n\
12896is a separator.");
12897
12898static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012899unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012900{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012901 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012902 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012903 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012904
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012905 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12906 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012907 return NULL;
12908
12909 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012910 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012911
12912 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012913 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012914
12915 PyErr_Format(PyExc_TypeError,
12916 "must be str or None, not %.100s",
12917 Py_TYPE(substring)->tp_name);
12918 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012919}
12920
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012921PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012922 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012923\n\
12924Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012925Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012926is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012927
12928static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012929unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012930{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012931 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012932 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012933
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012934 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12935 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012936 return NULL;
12937
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012938 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012939}
12940
12941static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012942PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012943{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012944 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012945}
12946
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012947PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012948 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012949\n\
12950Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012951and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012952
12953static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012954unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012955{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012956 if (PyUnicode_READY(self) == -1)
12957 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012958 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012959}
12960
Larry Hastings61272b72014-01-07 12:41:53 -080012961/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012962
Larry Hastings31826802013-10-19 00:09:25 -070012963@staticmethod
12964str.maketrans as unicode_maketrans
12965
12966 x: object
12967
12968 y: unicode=NULL
12969
12970 z: unicode=NULL
12971
12972 /
12973
12974Return a translation table usable for str.translate().
12975
12976If there is only one argument, it must be a dictionary mapping Unicode
12977ordinals (integers) or characters to Unicode ordinals, strings or None.
12978Character keys will be then converted to ordinals.
12979If there are two arguments, they must be strings of equal length, and
12980in the resulting dictionary, each character in x will be mapped to the
12981character at the same position in y. If there is a third argument, it
12982must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012983[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012984
Larry Hastings31826802013-10-19 00:09:25 -070012985static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012986unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012987/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012988{
Georg Brandlceee0772007-11-27 23:48:05 +000012989 PyObject *new = NULL, *key, *value;
12990 Py_ssize_t i = 0;
12991 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012992
Georg Brandlceee0772007-11-27 23:48:05 +000012993 new = PyDict_New();
12994 if (!new)
12995 return NULL;
12996 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012997 int x_kind, y_kind, z_kind;
12998 void *x_data, *y_data, *z_data;
12999
Georg Brandlceee0772007-11-27 23:48:05 +000013000 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013001 if (!PyUnicode_Check(x)) {
13002 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13003 "be a string if there is a second argument");
13004 goto err;
13005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013006 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013007 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13008 "arguments must have equal length");
13009 goto err;
13010 }
13011 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013012 x_kind = PyUnicode_KIND(x);
13013 y_kind = PyUnicode_KIND(y);
13014 x_data = PyUnicode_DATA(x);
13015 y_data = PyUnicode_DATA(y);
13016 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13017 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013018 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013019 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013020 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013021 if (!value) {
13022 Py_DECREF(key);
13023 goto err;
13024 }
Georg Brandlceee0772007-11-27 23:48:05 +000013025 res = PyDict_SetItem(new, key, value);
13026 Py_DECREF(key);
13027 Py_DECREF(value);
13028 if (res < 0)
13029 goto err;
13030 }
13031 /* create entries for deleting chars in z */
13032 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013033 z_kind = PyUnicode_KIND(z);
13034 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013035 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013036 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013037 if (!key)
13038 goto err;
13039 res = PyDict_SetItem(new, key, Py_None);
13040 Py_DECREF(key);
13041 if (res < 0)
13042 goto err;
13043 }
13044 }
13045 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013046 int kind;
13047 void *data;
13048
Georg Brandlceee0772007-11-27 23:48:05 +000013049 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013050 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013051 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13052 "to maketrans it must be a dict");
13053 goto err;
13054 }
13055 /* copy entries into the new dict, converting string keys to int keys */
13056 while (PyDict_Next(x, &i, &key, &value)) {
13057 if (PyUnicode_Check(key)) {
13058 /* convert string keys to integer keys */
13059 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013060 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013061 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13062 "table must be of length 1");
13063 goto err;
13064 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013065 kind = PyUnicode_KIND(key);
13066 data = PyUnicode_DATA(key);
13067 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013068 if (!newkey)
13069 goto err;
13070 res = PyDict_SetItem(new, newkey, value);
13071 Py_DECREF(newkey);
13072 if (res < 0)
13073 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013074 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013075 /* just keep integer keys */
13076 if (PyDict_SetItem(new, key, value) < 0)
13077 goto err;
13078 } else {
13079 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13080 "be strings or integers");
13081 goto err;
13082 }
13083 }
13084 }
13085 return new;
13086 err:
13087 Py_DECREF(new);
13088 return NULL;
13089}
13090
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013091PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013092 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013094Return a copy of the string S in which each character has been mapped\n\
13095through the given translation table. The table must implement\n\
13096lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13097mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13098this operation raises LookupError, the character is left untouched.\n\
13099Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100
13101static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013102unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013105}
13106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013107PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013108 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013110Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013111
13112static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013113unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013115 if (PyUnicode_READY(self) == -1)
13116 return NULL;
13117 if (PyUnicode_IS_ASCII(self))
13118 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013119 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120}
13121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013122PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013123 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013124\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013125Pad a numeric string S with zeros on the left, to fill a field\n\
13126of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127
13128static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013129unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013131 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013132 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013133 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013134 int kind;
13135 void *data;
13136 Py_UCS4 chr;
13137
Martin v. Löwis18e16552006-02-15 17:27:45 +000013138 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013139 return NULL;
13140
Benjamin Petersonbac79492012-01-14 13:34:47 -050013141 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013142 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013143
Victor Stinnerc4b49542011-12-11 22:44:26 +010013144 if (PyUnicode_GET_LENGTH(self) >= width)
13145 return unicode_result_unchanged(self);
13146
13147 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013148
13149 u = pad(self, fill, 0, '0');
13150
Walter Dörwald068325e2002-04-15 13:36:47 +000013151 if (u == NULL)
13152 return NULL;
13153
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013154 kind = PyUnicode_KIND(u);
13155 data = PyUnicode_DATA(u);
13156 chr = PyUnicode_READ(kind, data, fill);
13157
13158 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013159 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013160 PyUnicode_WRITE(kind, data, 0, chr);
13161 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013162 }
13163
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013164 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013165 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013167
13168#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013169static PyObject *
13170unicode__decimal2ascii(PyObject *self)
13171{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013172 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013173}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013174#endif
13175
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013176PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013177 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013178\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013179Return True if S starts with the specified prefix, False otherwise.\n\
13180With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013181With optional end, stop comparing S at that position.\n\
13182prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183
13184static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013185unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013186 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013187{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013188 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013189 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013190 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013191 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013192 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193
Jesus Ceaac451502011-04-20 17:09:23 +020013194 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013195 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013196 if (PyTuple_Check(subobj)) {
13197 Py_ssize_t i;
13198 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013199 substring = PyTuple_GET_ITEM(subobj, i);
13200 if (!PyUnicode_Check(substring)) {
13201 PyErr_Format(PyExc_TypeError,
13202 "tuple for startswith must only contain str, "
13203 "not %.100s",
13204 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013205 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013206 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013207 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013208 if (result == -1)
13209 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013210 if (result) {
13211 Py_RETURN_TRUE;
13212 }
13213 }
13214 /* nothing matched */
13215 Py_RETURN_FALSE;
13216 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013217 if (!PyUnicode_Check(subobj)) {
13218 PyErr_Format(PyExc_TypeError,
13219 "startswith first arg must be str or "
13220 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013221 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013222 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013223 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013224 if (result == -1)
13225 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013226 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227}
13228
13229
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013230PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013231 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013233Return True if S ends with the specified suffix, False otherwise.\n\
13234With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013235With optional end, stop comparing S at that position.\n\
13236suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237
13238static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013239unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013240 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013241{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013242 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013243 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013244 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013245 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013246 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013247
Jesus Ceaac451502011-04-20 17:09:23 +020013248 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013249 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013250 if (PyTuple_Check(subobj)) {
13251 Py_ssize_t i;
13252 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013253 substring = PyTuple_GET_ITEM(subobj, i);
13254 if (!PyUnicode_Check(substring)) {
13255 PyErr_Format(PyExc_TypeError,
13256 "tuple for endswith must only contain str, "
13257 "not %.100s",
13258 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013259 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013260 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013261 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013262 if (result == -1)
13263 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013264 if (result) {
13265 Py_RETURN_TRUE;
13266 }
13267 }
13268 Py_RETURN_FALSE;
13269 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013270 if (!PyUnicode_Check(subobj)) {
13271 PyErr_Format(PyExc_TypeError,
13272 "endswith first arg must be str or "
13273 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013274 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013275 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013276 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013277 if (result == -1)
13278 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013279 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013280}
13281
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013282static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013283_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013284{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013285 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13286 writer->data = PyUnicode_DATA(writer->buffer);
13287
13288 if (!writer->readonly) {
13289 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013290 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013291 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013292 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013293 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13294 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13295 writer->kind = PyUnicode_WCHAR_KIND;
13296 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13297
Victor Stinner8f674cc2013-04-17 23:02:17 +020013298 /* Copy-on-write mode: set buffer size to 0 so
13299 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13300 * next write. */
13301 writer->size = 0;
13302 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013303}
13304
Victor Stinnerd3f08822012-05-29 12:57:52 +020013305void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013306_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013307{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013308 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013309
13310 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013311 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013312
13313 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13314 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13315 writer->kind = PyUnicode_WCHAR_KIND;
13316 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013317}
13318
Victor Stinnerd3f08822012-05-29 12:57:52 +020013319int
13320_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13321 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013322{
13323 Py_ssize_t newlen;
13324 PyObject *newbuffer;
13325
Victor Stinner2740e462016-09-06 16:58:36 -070013326 assert(maxchar <= MAX_UNICODE);
13327
Victor Stinnerca9381e2015-09-22 00:58:32 +020013328 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013329 assert((maxchar > writer->maxchar && length >= 0)
13330 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013331
Victor Stinner202fdca2012-05-07 12:47:02 +020013332 if (length > PY_SSIZE_T_MAX - writer->pos) {
13333 PyErr_NoMemory();
13334 return -1;
13335 }
13336 newlen = writer->pos + length;
13337
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013338 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013339
Victor Stinnerd3f08822012-05-29 12:57:52 +020013340 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013341 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013342 if (writer->overallocate
13343 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13344 /* overallocate to limit the number of realloc() */
13345 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013346 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013347 if (newlen < writer->min_length)
13348 newlen = writer->min_length;
13349
Victor Stinnerd3f08822012-05-29 12:57:52 +020013350 writer->buffer = PyUnicode_New(newlen, maxchar);
13351 if (writer->buffer == NULL)
13352 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013353 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013354 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013355 if (writer->overallocate
13356 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13357 /* overallocate to limit the number of realloc() */
13358 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013359 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013360 if (newlen < writer->min_length)
13361 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013362
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013363 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013364 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013365 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013366 newbuffer = PyUnicode_New(newlen, maxchar);
13367 if (newbuffer == NULL)
13368 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013369 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13370 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013371 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013372 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013373 }
13374 else {
13375 newbuffer = resize_compact(writer->buffer, newlen);
13376 if (newbuffer == NULL)
13377 return -1;
13378 }
13379 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013380 }
13381 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013382 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013383 newbuffer = PyUnicode_New(writer->size, maxchar);
13384 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013385 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013386 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13387 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013388 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013389 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013390 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013391 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013392
13393#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013394}
13395
Victor Stinnerca9381e2015-09-22 00:58:32 +020013396int
13397_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13398 enum PyUnicode_Kind kind)
13399{
13400 Py_UCS4 maxchar;
13401
13402 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13403 assert(writer->kind < kind);
13404
13405 switch (kind)
13406 {
13407 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13408 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13409 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13410 default:
13411 assert(0 && "invalid kind");
13412 return -1;
13413 }
13414
13415 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13416}
13417
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013418static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013419_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013420{
Victor Stinner2740e462016-09-06 16:58:36 -070013421 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013422 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13423 return -1;
13424 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13425 writer->pos++;
13426 return 0;
13427}
13428
13429int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013430_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13431{
13432 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13433}
13434
13435int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013436_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13437{
13438 Py_UCS4 maxchar;
13439 Py_ssize_t len;
13440
13441 if (PyUnicode_READY(str) == -1)
13442 return -1;
13443 len = PyUnicode_GET_LENGTH(str);
13444 if (len == 0)
13445 return 0;
13446 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13447 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013448 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013449 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013450 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013451 Py_INCREF(str);
13452 writer->buffer = str;
13453 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013454 writer->pos += len;
13455 return 0;
13456 }
13457 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13458 return -1;
13459 }
13460 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13461 str, 0, len);
13462 writer->pos += len;
13463 return 0;
13464}
13465
Victor Stinnere215d962012-10-06 23:03:36 +020013466int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013467_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13468 Py_ssize_t start, Py_ssize_t end)
13469{
13470 Py_UCS4 maxchar;
13471 Py_ssize_t len;
13472
13473 if (PyUnicode_READY(str) == -1)
13474 return -1;
13475
13476 assert(0 <= start);
13477 assert(end <= PyUnicode_GET_LENGTH(str));
13478 assert(start <= end);
13479
13480 if (end == 0)
13481 return 0;
13482
13483 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13484 return _PyUnicodeWriter_WriteStr(writer, str);
13485
13486 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13487 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13488 else
13489 maxchar = writer->maxchar;
13490 len = end - start;
13491
13492 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13493 return -1;
13494
13495 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13496 str, start, len);
13497 writer->pos += len;
13498 return 0;
13499}
13500
13501int
Victor Stinner4a587072013-11-19 12:54:53 +010013502_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13503 const char *ascii, Py_ssize_t len)
13504{
13505 if (len == -1)
13506 len = strlen(ascii);
13507
13508 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13509
13510 if (writer->buffer == NULL && !writer->overallocate) {
13511 PyObject *str;
13512
13513 str = _PyUnicode_FromASCII(ascii, len);
13514 if (str == NULL)
13515 return -1;
13516
13517 writer->readonly = 1;
13518 writer->buffer = str;
13519 _PyUnicodeWriter_Update(writer);
13520 writer->pos += len;
13521 return 0;
13522 }
13523
13524 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13525 return -1;
13526
13527 switch (writer->kind)
13528 {
13529 case PyUnicode_1BYTE_KIND:
13530 {
13531 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13532 Py_UCS1 *data = writer->data;
13533
13534 Py_MEMCPY(data + writer->pos, str, len);
13535 break;
13536 }
13537 case PyUnicode_2BYTE_KIND:
13538 {
13539 _PyUnicode_CONVERT_BYTES(
13540 Py_UCS1, Py_UCS2,
13541 ascii, ascii + len,
13542 (Py_UCS2 *)writer->data + writer->pos);
13543 break;
13544 }
13545 case PyUnicode_4BYTE_KIND:
13546 {
13547 _PyUnicode_CONVERT_BYTES(
13548 Py_UCS1, Py_UCS4,
13549 ascii, ascii + len,
13550 (Py_UCS4 *)writer->data + writer->pos);
13551 break;
13552 }
13553 default:
13554 assert(0);
13555 }
13556
13557 writer->pos += len;
13558 return 0;
13559}
13560
13561int
13562_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13563 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013564{
13565 Py_UCS4 maxchar;
13566
13567 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13568 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13569 return -1;
13570 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13571 writer->pos += len;
13572 return 0;
13573}
13574
Victor Stinnerd3f08822012-05-29 12:57:52 +020013575PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013576_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013577{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013578 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013579 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013580 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013581 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013582 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013583 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013584 str = writer->buffer;
13585 writer->buffer = NULL;
13586 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13587 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013588 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013589 if (writer->pos == 0) {
13590 Py_CLEAR(writer->buffer);
13591
13592 /* Get the empty Unicode string singleton ('') */
13593 _Py_INCREF_UNICODE_EMPTY();
13594 str = unicode_empty;
Victor Stinner202fdca2012-05-07 12:47:02 +020013595 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013596 else {
13597 str = writer->buffer;
13598 writer->buffer = NULL;
13599
13600 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13601 PyObject *str2;
13602 str2 = resize_compact(str, writer->pos);
13603 if (str2 == NULL)
13604 return NULL;
13605 str = str2;
13606 }
13607 }
13608
Victor Stinner15a0bd32013-07-08 22:29:55 +020013609 assert(_PyUnicode_CheckConsistency(str, 1));
13610 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013611}
13612
Victor Stinnerd3f08822012-05-29 12:57:52 +020013613void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013614_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013615{
13616 Py_CLEAR(writer->buffer);
13617}
13618
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013619#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013620
13621PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013622 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013623\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013624Return a formatted version of S, using substitutions from args and kwargs.\n\
13625The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013626
Eric Smith27bbca62010-11-04 17:06:58 +000013627PyDoc_STRVAR(format_map__doc__,
13628 "S.format_map(mapping) -> str\n\
13629\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013630Return a formatted version of S, using substitutions from mapping.\n\
13631The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013632
Eric Smith4a7d76d2008-05-30 18:10:19 +000013633static PyObject *
13634unicode__format__(PyObject* self, PyObject* args)
13635{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013636 PyObject *format_spec;
13637 _PyUnicodeWriter writer;
13638 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013639
13640 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13641 return NULL;
13642
Victor Stinnerd3f08822012-05-29 12:57:52 +020013643 if (PyUnicode_READY(self) == -1)
13644 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013645 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013646 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13647 self, format_spec, 0,
13648 PyUnicode_GET_LENGTH(format_spec));
13649 if (ret == -1) {
13650 _PyUnicodeWriter_Dealloc(&writer);
13651 return NULL;
13652 }
13653 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013654}
13655
Eric Smith8c663262007-08-25 02:26:07 +000013656PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013657 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013658\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013659Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013660
13661static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013662unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013663{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013664 Py_ssize_t size;
13665
13666 /* If it's a compact object, account for base structure +
13667 character data. */
13668 if (PyUnicode_IS_COMPACT_ASCII(v))
13669 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13670 else if (PyUnicode_IS_COMPACT(v))
13671 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013672 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013673 else {
13674 /* If it is a two-block object, account for base object, and
13675 for character block if present. */
13676 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013677 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013678 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013679 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013680 }
13681 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013682 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013683 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013684 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013685 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013686 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013687
13688 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013689}
13690
13691PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013692 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013693
13694static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013695unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013696{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013697 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013698 if (!copy)
13699 return NULL;
13700 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013701}
13702
Guido van Rossumd57fd912000-03-10 22:53:23 +000013703static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013704 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013705 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013706 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13707 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013708 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13709 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013710 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013711 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13712 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13713 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013714 {"expandtabs", (PyCFunction) unicode_expandtabs,
13715 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013716 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013717 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013718 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13719 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13720 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013721 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013722 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13723 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13724 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013725 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013726 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013727 {"splitlines", (PyCFunction) unicode_splitlines,
13728 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013729 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013730 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13731 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13732 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13733 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13734 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13735 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13736 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13737 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13738 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13739 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13740 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13741 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13742 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13743 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013744 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013745 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013746 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013747 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013748 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013749 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013750 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013751 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013752#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013753 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013754 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013755#endif
13756
Benjamin Peterson14339b62009-01-31 16:36:08 +000013757 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013758 {NULL, NULL}
13759};
13760
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013761static PyObject *
13762unicode_mod(PyObject *v, PyObject *w)
13763{
Brian Curtindfc80e32011-08-10 20:28:54 -050013764 if (!PyUnicode_Check(v))
13765 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013766 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013767}
13768
13769static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013770 0, /*nb_add*/
13771 0, /*nb_subtract*/
13772 0, /*nb_multiply*/
13773 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013774};
13775
Guido van Rossumd57fd912000-03-10 22:53:23 +000013776static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013777 (lenfunc) unicode_length, /* sq_length */
13778 PyUnicode_Concat, /* sq_concat */
13779 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13780 (ssizeargfunc) unicode_getitem, /* sq_item */
13781 0, /* sq_slice */
13782 0, /* sq_ass_item */
13783 0, /* sq_ass_slice */
13784 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013785};
13786
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013787static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013788unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013789{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013790 if (PyUnicode_READY(self) == -1)
13791 return NULL;
13792
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013793 if (PyIndex_Check(item)) {
13794 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013795 if (i == -1 && PyErr_Occurred())
13796 return NULL;
13797 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013798 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013799 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013800 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013801 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013802 PyObject *result;
13803 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013804 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013805 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013807 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013808 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013809 return NULL;
13810 }
13811
13812 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013813 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013814 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013815 slicelength == PyUnicode_GET_LENGTH(self)) {
13816 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013817 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013818 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013819 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013820 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013821 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013822 src_kind = PyUnicode_KIND(self);
13823 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013824 if (!PyUnicode_IS_ASCII(self)) {
13825 kind_limit = kind_maxchar_limit(src_kind);
13826 max_char = 0;
13827 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13828 ch = PyUnicode_READ(src_kind, src_data, cur);
13829 if (ch > max_char) {
13830 max_char = ch;
13831 if (max_char >= kind_limit)
13832 break;
13833 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013834 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013835 }
Victor Stinner55c99112011-10-13 01:17:06 +020013836 else
13837 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013838 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013839 if (result == NULL)
13840 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013841 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013842 dest_data = PyUnicode_DATA(result);
13843
13844 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013845 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13846 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013847 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013848 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013849 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013850 } else {
13851 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13852 return NULL;
13853 }
13854}
13855
13856static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013857 (lenfunc)unicode_length, /* mp_length */
13858 (binaryfunc)unicode_subscript, /* mp_subscript */
13859 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013860};
13861
Guido van Rossumd57fd912000-03-10 22:53:23 +000013862
Guido van Rossumd57fd912000-03-10 22:53:23 +000013863/* Helpers for PyUnicode_Format() */
13864
Victor Stinnera47082312012-10-04 02:19:54 +020013865struct unicode_formatter_t {
13866 PyObject *args;
13867 int args_owned;
13868 Py_ssize_t arglen, argidx;
13869 PyObject *dict;
13870
13871 enum PyUnicode_Kind fmtkind;
13872 Py_ssize_t fmtcnt, fmtpos;
13873 void *fmtdata;
13874 PyObject *fmtstr;
13875
13876 _PyUnicodeWriter writer;
13877};
13878
13879struct unicode_format_arg_t {
13880 Py_UCS4 ch;
13881 int flags;
13882 Py_ssize_t width;
13883 int prec;
13884 int sign;
13885};
13886
Guido van Rossumd57fd912000-03-10 22:53:23 +000013887static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013888unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013889{
Victor Stinnera47082312012-10-04 02:19:54 +020013890 Py_ssize_t argidx = ctx->argidx;
13891
13892 if (argidx < ctx->arglen) {
13893 ctx->argidx++;
13894 if (ctx->arglen < 0)
13895 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013896 else
Victor Stinnera47082312012-10-04 02:19:54 +020013897 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013898 }
13899 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013900 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013901 return NULL;
13902}
13903
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013904/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013905
Victor Stinnera47082312012-10-04 02:19:54 +020013906/* Format a float into the writer if the writer is not NULL, or into *p_output
13907 otherwise.
13908
13909 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013910static int
Victor Stinnera47082312012-10-04 02:19:54 +020013911formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13912 PyObject **p_output,
13913 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013914{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013915 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013916 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013917 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013918 int prec;
13919 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013920
Guido van Rossumd57fd912000-03-10 22:53:23 +000013921 x = PyFloat_AsDouble(v);
13922 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013923 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013924
Victor Stinnera47082312012-10-04 02:19:54 +020013925 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013926 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013927 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013928
Victor Stinnera47082312012-10-04 02:19:54 +020013929 if (arg->flags & F_ALT)
13930 dtoa_flags = Py_DTSF_ALT;
13931 else
13932 dtoa_flags = 0;
13933 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013934 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013935 return -1;
13936 len = strlen(p);
13937 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013938 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013939 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013940 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013941 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013942 }
13943 else
13944 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013945 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013946 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013947}
13948
Victor Stinnerd0880d52012-04-27 23:40:13 +020013949/* formatlong() emulates the format codes d, u, o, x and X, and
13950 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13951 * Python's regular ints.
13952 * Return value: a new PyUnicodeObject*, or NULL if error.
13953 * The output string is of the form
13954 * "-"? ("0x" | "0X")? digit+
13955 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13956 * set in flags. The case of hex digits will be correct,
13957 * There will be at least prec digits, zero-filled on the left if
13958 * necessary to get that many.
13959 * val object to be converted
13960 * flags bitmask of format flags; only F_ALT is looked at
13961 * prec minimum number of digits; 0-fill on left if needed
13962 * type a character in [duoxX]; u acts the same as d
13963 *
13964 * CAUTION: o, x and X conversions on regular ints can never
13965 * produce a '-' sign, but can for Python's unbounded ints.
13966 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013967PyObject *
13968_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013969{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013970 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013971 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013972 Py_ssize_t i;
13973 int sign; /* 1 if '-', else 0 */
13974 int len; /* number of characters */
13975 Py_ssize_t llen;
13976 int numdigits; /* len == numnondigits + numdigits */
13977 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013978
Victor Stinnerd0880d52012-04-27 23:40:13 +020013979 /* Avoid exceeding SSIZE_T_MAX */
13980 if (prec > INT_MAX-3) {
13981 PyErr_SetString(PyExc_OverflowError,
13982 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013983 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013984 }
13985
13986 assert(PyLong_Check(val));
13987
13988 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013989 default:
13990 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013991 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013992 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013993 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013994 /* int and int subclasses should print numerically when a numeric */
13995 /* format code is used (see issue18780) */
13996 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013997 break;
13998 case 'o':
13999 numnondigits = 2;
14000 result = PyNumber_ToBase(val, 8);
14001 break;
14002 case 'x':
14003 case 'X':
14004 numnondigits = 2;
14005 result = PyNumber_ToBase(val, 16);
14006 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014007 }
14008 if (!result)
14009 return NULL;
14010
14011 assert(unicode_modifiable(result));
14012 assert(PyUnicode_IS_READY(result));
14013 assert(PyUnicode_IS_ASCII(result));
14014
14015 /* To modify the string in-place, there can only be one reference. */
14016 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014017 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014018 PyErr_BadInternalCall();
14019 return NULL;
14020 }
14021 buf = PyUnicode_DATA(result);
14022 llen = PyUnicode_GET_LENGTH(result);
14023 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014024 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014025 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014026 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014027 return NULL;
14028 }
14029 len = (int)llen;
14030 sign = buf[0] == '-';
14031 numnondigits += sign;
14032 numdigits = len - numnondigits;
14033 assert(numdigits > 0);
14034
14035 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014036 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014037 (type == 'o' || type == 'x' || type == 'X'))) {
14038 assert(buf[sign] == '0');
14039 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14040 buf[sign+1] == 'o');
14041 numnondigits -= 2;
14042 buf += 2;
14043 len -= 2;
14044 if (sign)
14045 buf[0] = '-';
14046 assert(len == numnondigits + numdigits);
14047 assert(numdigits > 0);
14048 }
14049
14050 /* Fill with leading zeroes to meet minimum width. */
14051 if (prec > numdigits) {
14052 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14053 numnondigits + prec);
14054 char *b1;
14055 if (!r1) {
14056 Py_DECREF(result);
14057 return NULL;
14058 }
14059 b1 = PyBytes_AS_STRING(r1);
14060 for (i = 0; i < numnondigits; ++i)
14061 *b1++ = *buf++;
14062 for (i = 0; i < prec - numdigits; i++)
14063 *b1++ = '0';
14064 for (i = 0; i < numdigits; i++)
14065 *b1++ = *buf++;
14066 *b1 = '\0';
14067 Py_DECREF(result);
14068 result = r1;
14069 buf = PyBytes_AS_STRING(result);
14070 len = numnondigits + prec;
14071 }
14072
14073 /* Fix up case for hex conversions. */
14074 if (type == 'X') {
14075 /* Need to convert all lower case letters to upper case.
14076 and need to convert 0x to 0X (and -0x to -0X). */
14077 for (i = 0; i < len; i++)
14078 if (buf[i] >= 'a' && buf[i] <= 'x')
14079 buf[i] -= 'a'-'A';
14080 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014081 if (!PyUnicode_Check(result)
14082 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014083 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014084 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014085 Py_DECREF(result);
14086 result = unicode;
14087 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014088 else if (len != PyUnicode_GET_LENGTH(result)) {
14089 if (PyUnicode_Resize(&result, len) < 0)
14090 Py_CLEAR(result);
14091 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014092 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014093}
14094
Ethan Furmandf3ed242014-01-05 06:50:30 -080014095/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014096 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014097 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014098 * -1 and raise an exception on error */
14099static int
Victor Stinnera47082312012-10-04 02:19:54 +020014100mainformatlong(PyObject *v,
14101 struct unicode_format_arg_t *arg,
14102 PyObject **p_output,
14103 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014104{
14105 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014106 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014107
14108 if (!PyNumber_Check(v))
14109 goto wrongtype;
14110
Ethan Furman9ab74802014-03-21 06:38:46 -070014111 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014112 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014113 if (type == 'o' || type == 'x' || type == 'X') {
14114 iobj = PyNumber_Index(v);
14115 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014116 if (PyErr_ExceptionMatches(PyExc_TypeError))
14117 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014118 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014119 }
14120 }
14121 else {
14122 iobj = PyNumber_Long(v);
14123 if (iobj == NULL ) {
14124 if (PyErr_ExceptionMatches(PyExc_TypeError))
14125 goto wrongtype;
14126 return -1;
14127 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014128 }
14129 assert(PyLong_Check(iobj));
14130 }
14131 else {
14132 iobj = v;
14133 Py_INCREF(iobj);
14134 }
14135
14136 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014137 && arg->width == -1 && arg->prec == -1
14138 && !(arg->flags & (F_SIGN | F_BLANK))
14139 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014140 {
14141 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014142 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014143 int base;
14144
Victor Stinnera47082312012-10-04 02:19:54 +020014145 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014146 {
14147 default:
14148 assert(0 && "'type' not in [diuoxX]");
14149 case 'd':
14150 case 'i':
14151 case 'u':
14152 base = 10;
14153 break;
14154 case 'o':
14155 base = 8;
14156 break;
14157 case 'x':
14158 case 'X':
14159 base = 16;
14160 break;
14161 }
14162
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014163 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14164 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014165 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014166 }
14167 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014168 return 1;
14169 }
14170
Ethan Furmanb95b5612015-01-23 20:05:18 -080014171 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014172 Py_DECREF(iobj);
14173 if (res == NULL)
14174 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014175 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014176 return 0;
14177
14178wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014179 switch(type)
14180 {
14181 case 'o':
14182 case 'x':
14183 case 'X':
14184 PyErr_Format(PyExc_TypeError,
14185 "%%%c format: an integer is required, "
14186 "not %.200s",
14187 type, Py_TYPE(v)->tp_name);
14188 break;
14189 default:
14190 PyErr_Format(PyExc_TypeError,
14191 "%%%c format: a number is required, "
14192 "not %.200s",
14193 type, Py_TYPE(v)->tp_name);
14194 break;
14195 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014196 return -1;
14197}
14198
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014199static Py_UCS4
14200formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014201{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014202 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014203 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014204 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014205 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014206 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014207 goto onError;
14208 }
14209 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014210 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014211 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014212 /* make sure number is a type of integer */
14213 if (!PyLong_Check(v)) {
14214 iobj = PyNumber_Index(v);
14215 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014216 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014217 }
14218 v = iobj;
14219 Py_DECREF(iobj);
14220 }
14221 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014222 x = PyLong_AsLong(v);
14223 if (x == -1 && PyErr_Occurred())
14224 goto onError;
14225
Victor Stinner8faf8212011-12-08 22:14:11 +010014226 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014227 PyErr_SetString(PyExc_OverflowError,
14228 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014229 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014230 }
14231
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014232 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014233 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014234
Benjamin Peterson29060642009-01-31 22:14:21 +000014235 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014236 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014237 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014238 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014239}
14240
Victor Stinnera47082312012-10-04 02:19:54 +020014241/* Parse options of an argument: flags, width, precision.
14242 Handle also "%(name)" syntax.
14243
14244 Return 0 if the argument has been formatted into arg->str.
14245 Return 1 if the argument has been written into ctx->writer,
14246 Raise an exception and return -1 on error. */
14247static int
14248unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14249 struct unicode_format_arg_t *arg)
14250{
14251#define FORMAT_READ(ctx) \
14252 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14253
14254 PyObject *v;
14255
Victor Stinnera47082312012-10-04 02:19:54 +020014256 if (arg->ch == '(') {
14257 /* Get argument value from a dictionary. Example: "%(name)s". */
14258 Py_ssize_t keystart;
14259 Py_ssize_t keylen;
14260 PyObject *key;
14261 int pcount = 1;
14262
14263 if (ctx->dict == NULL) {
14264 PyErr_SetString(PyExc_TypeError,
14265 "format requires a mapping");
14266 return -1;
14267 }
14268 ++ctx->fmtpos;
14269 --ctx->fmtcnt;
14270 keystart = ctx->fmtpos;
14271 /* Skip over balanced parentheses */
14272 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14273 arg->ch = FORMAT_READ(ctx);
14274 if (arg->ch == ')')
14275 --pcount;
14276 else if (arg->ch == '(')
14277 ++pcount;
14278 ctx->fmtpos++;
14279 }
14280 keylen = ctx->fmtpos - keystart - 1;
14281 if (ctx->fmtcnt < 0 || pcount > 0) {
14282 PyErr_SetString(PyExc_ValueError,
14283 "incomplete format key");
14284 return -1;
14285 }
14286 key = PyUnicode_Substring(ctx->fmtstr,
14287 keystart, keystart + keylen);
14288 if (key == NULL)
14289 return -1;
14290 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014291 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014292 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014293 }
14294 ctx->args = PyObject_GetItem(ctx->dict, key);
14295 Py_DECREF(key);
14296 if (ctx->args == NULL)
14297 return -1;
14298 ctx->args_owned = 1;
14299 ctx->arglen = -1;
14300 ctx->argidx = -2;
14301 }
14302
14303 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014304 while (--ctx->fmtcnt >= 0) {
14305 arg->ch = FORMAT_READ(ctx);
14306 ctx->fmtpos++;
14307 switch (arg->ch) {
14308 case '-': arg->flags |= F_LJUST; continue;
14309 case '+': arg->flags |= F_SIGN; continue;
14310 case ' ': arg->flags |= F_BLANK; continue;
14311 case '#': arg->flags |= F_ALT; continue;
14312 case '0': arg->flags |= F_ZERO; continue;
14313 }
14314 break;
14315 }
14316
14317 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014318 if (arg->ch == '*') {
14319 v = unicode_format_getnextarg(ctx);
14320 if (v == NULL)
14321 return -1;
14322 if (!PyLong_Check(v)) {
14323 PyErr_SetString(PyExc_TypeError,
14324 "* wants int");
14325 return -1;
14326 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014327 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014328 if (arg->width == -1 && PyErr_Occurred())
14329 return -1;
14330 if (arg->width < 0) {
14331 arg->flags |= F_LJUST;
14332 arg->width = -arg->width;
14333 }
14334 if (--ctx->fmtcnt >= 0) {
14335 arg->ch = FORMAT_READ(ctx);
14336 ctx->fmtpos++;
14337 }
14338 }
14339 else if (arg->ch >= '0' && arg->ch <= '9') {
14340 arg->width = arg->ch - '0';
14341 while (--ctx->fmtcnt >= 0) {
14342 arg->ch = FORMAT_READ(ctx);
14343 ctx->fmtpos++;
14344 if (arg->ch < '0' || arg->ch > '9')
14345 break;
14346 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14347 mixing signed and unsigned comparison. Since arg->ch is between
14348 '0' and '9', casting to int is safe. */
14349 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14350 PyErr_SetString(PyExc_ValueError,
14351 "width too big");
14352 return -1;
14353 }
14354 arg->width = arg->width*10 + (arg->ch - '0');
14355 }
14356 }
14357
14358 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014359 if (arg->ch == '.') {
14360 arg->prec = 0;
14361 if (--ctx->fmtcnt >= 0) {
14362 arg->ch = FORMAT_READ(ctx);
14363 ctx->fmtpos++;
14364 }
14365 if (arg->ch == '*') {
14366 v = unicode_format_getnextarg(ctx);
14367 if (v == NULL)
14368 return -1;
14369 if (!PyLong_Check(v)) {
14370 PyErr_SetString(PyExc_TypeError,
14371 "* wants int");
14372 return -1;
14373 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014374 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014375 if (arg->prec == -1 && PyErr_Occurred())
14376 return -1;
14377 if (arg->prec < 0)
14378 arg->prec = 0;
14379 if (--ctx->fmtcnt >= 0) {
14380 arg->ch = FORMAT_READ(ctx);
14381 ctx->fmtpos++;
14382 }
14383 }
14384 else if (arg->ch >= '0' && arg->ch <= '9') {
14385 arg->prec = arg->ch - '0';
14386 while (--ctx->fmtcnt >= 0) {
14387 arg->ch = FORMAT_READ(ctx);
14388 ctx->fmtpos++;
14389 if (arg->ch < '0' || arg->ch > '9')
14390 break;
14391 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14392 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014393 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014394 return -1;
14395 }
14396 arg->prec = arg->prec*10 + (arg->ch - '0');
14397 }
14398 }
14399 }
14400
14401 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14402 if (ctx->fmtcnt >= 0) {
14403 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14404 if (--ctx->fmtcnt >= 0) {
14405 arg->ch = FORMAT_READ(ctx);
14406 ctx->fmtpos++;
14407 }
14408 }
14409 }
14410 if (ctx->fmtcnt < 0) {
14411 PyErr_SetString(PyExc_ValueError,
14412 "incomplete format");
14413 return -1;
14414 }
14415 return 0;
14416
14417#undef FORMAT_READ
14418}
14419
14420/* Format one argument. Supported conversion specifiers:
14421
14422 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014423 - "i", "d", "u": int or float
14424 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014425 - "e", "E", "f", "F", "g", "G": float
14426 - "c": int or str (1 character)
14427
Victor Stinner8dbd4212012-12-04 09:30:24 +010014428 When possible, the output is written directly into the Unicode writer
14429 (ctx->writer). A string is created when padding is required.
14430
Victor Stinnera47082312012-10-04 02:19:54 +020014431 Return 0 if the argument has been formatted into *p_str,
14432 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014433 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014434static int
14435unicode_format_arg_format(struct unicode_formatter_t *ctx,
14436 struct unicode_format_arg_t *arg,
14437 PyObject **p_str)
14438{
14439 PyObject *v;
14440 _PyUnicodeWriter *writer = &ctx->writer;
14441
14442 if (ctx->fmtcnt == 0)
14443 ctx->writer.overallocate = 0;
14444
14445 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014446 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014447 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014448 return 1;
14449 }
14450
14451 v = unicode_format_getnextarg(ctx);
14452 if (v == NULL)
14453 return -1;
14454
Victor Stinnera47082312012-10-04 02:19:54 +020014455
14456 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014457 case 's':
14458 case 'r':
14459 case 'a':
14460 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14461 /* Fast path */
14462 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14463 return -1;
14464 return 1;
14465 }
14466
14467 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14468 *p_str = v;
14469 Py_INCREF(*p_str);
14470 }
14471 else {
14472 if (arg->ch == 's')
14473 *p_str = PyObject_Str(v);
14474 else if (arg->ch == 'r')
14475 *p_str = PyObject_Repr(v);
14476 else
14477 *p_str = PyObject_ASCII(v);
14478 }
14479 break;
14480
14481 case 'i':
14482 case 'd':
14483 case 'u':
14484 case 'o':
14485 case 'x':
14486 case 'X':
14487 {
14488 int ret = mainformatlong(v, arg, p_str, writer);
14489 if (ret != 0)
14490 return ret;
14491 arg->sign = 1;
14492 break;
14493 }
14494
14495 case 'e':
14496 case 'E':
14497 case 'f':
14498 case 'F':
14499 case 'g':
14500 case 'G':
14501 if (arg->width == -1 && arg->prec == -1
14502 && !(arg->flags & (F_SIGN | F_BLANK)))
14503 {
14504 /* Fast path */
14505 if (formatfloat(v, arg, NULL, writer) == -1)
14506 return -1;
14507 return 1;
14508 }
14509
14510 arg->sign = 1;
14511 if (formatfloat(v, arg, p_str, NULL) == -1)
14512 return -1;
14513 break;
14514
14515 case 'c':
14516 {
14517 Py_UCS4 ch = formatchar(v);
14518 if (ch == (Py_UCS4) -1)
14519 return -1;
14520 if (arg->width == -1 && arg->prec == -1) {
14521 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014522 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014523 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014524 return 1;
14525 }
14526 *p_str = PyUnicode_FromOrdinal(ch);
14527 break;
14528 }
14529
14530 default:
14531 PyErr_Format(PyExc_ValueError,
14532 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014533 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014534 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14535 (int)arg->ch,
14536 ctx->fmtpos - 1);
14537 return -1;
14538 }
14539 if (*p_str == NULL)
14540 return -1;
14541 assert (PyUnicode_Check(*p_str));
14542 return 0;
14543}
14544
14545static int
14546unicode_format_arg_output(struct unicode_formatter_t *ctx,
14547 struct unicode_format_arg_t *arg,
14548 PyObject *str)
14549{
14550 Py_ssize_t len;
14551 enum PyUnicode_Kind kind;
14552 void *pbuf;
14553 Py_ssize_t pindex;
14554 Py_UCS4 signchar;
14555 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014556 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014557 Py_ssize_t sublen;
14558 _PyUnicodeWriter *writer = &ctx->writer;
14559 Py_UCS4 fill;
14560
14561 fill = ' ';
14562 if (arg->sign && arg->flags & F_ZERO)
14563 fill = '0';
14564
14565 if (PyUnicode_READY(str) == -1)
14566 return -1;
14567
14568 len = PyUnicode_GET_LENGTH(str);
14569 if ((arg->width == -1 || arg->width <= len)
14570 && (arg->prec == -1 || arg->prec >= len)
14571 && !(arg->flags & (F_SIGN | F_BLANK)))
14572 {
14573 /* Fast path */
14574 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14575 return -1;
14576 return 0;
14577 }
14578
14579 /* Truncate the string for "s", "r" and "a" formats
14580 if the precision is set */
14581 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14582 if (arg->prec >= 0 && len > arg->prec)
14583 len = arg->prec;
14584 }
14585
14586 /* Adjust sign and width */
14587 kind = PyUnicode_KIND(str);
14588 pbuf = PyUnicode_DATA(str);
14589 pindex = 0;
14590 signchar = '\0';
14591 if (arg->sign) {
14592 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14593 if (ch == '-' || ch == '+') {
14594 signchar = ch;
14595 len--;
14596 pindex++;
14597 }
14598 else if (arg->flags & F_SIGN)
14599 signchar = '+';
14600 else if (arg->flags & F_BLANK)
14601 signchar = ' ';
14602 else
14603 arg->sign = 0;
14604 }
14605 if (arg->width < len)
14606 arg->width = len;
14607
14608 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014609 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014610 if (!(arg->flags & F_LJUST)) {
14611 if (arg->sign) {
14612 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014613 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014614 }
14615 else {
14616 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014617 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014618 }
14619 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014620 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14621 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014622 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014623 }
14624
Victor Stinnera47082312012-10-04 02:19:54 +020014625 buflen = arg->width;
14626 if (arg->sign && len == arg->width)
14627 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014628 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014629 return -1;
14630
14631 /* Write the sign if needed */
14632 if (arg->sign) {
14633 if (fill != ' ') {
14634 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14635 writer->pos += 1;
14636 }
14637 if (arg->width > len)
14638 arg->width--;
14639 }
14640
14641 /* Write the numeric prefix for "x", "X" and "o" formats
14642 if the alternate form is used.
14643 For example, write "0x" for the "%#x" format. */
14644 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14645 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14646 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14647 if (fill != ' ') {
14648 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14649 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14650 writer->pos += 2;
14651 pindex += 2;
14652 }
14653 arg->width -= 2;
14654 if (arg->width < 0)
14655 arg->width = 0;
14656 len -= 2;
14657 }
14658
14659 /* Pad left with the fill character if needed */
14660 if (arg->width > len && !(arg->flags & F_LJUST)) {
14661 sublen = arg->width - len;
14662 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14663 writer->pos += sublen;
14664 arg->width = len;
14665 }
14666
14667 /* If padding with spaces: write sign if needed and/or numeric prefix if
14668 the alternate form is used */
14669 if (fill == ' ') {
14670 if (arg->sign) {
14671 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14672 writer->pos += 1;
14673 }
14674 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14675 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14676 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14677 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14678 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14679 writer->pos += 2;
14680 pindex += 2;
14681 }
14682 }
14683
14684 /* Write characters */
14685 if (len) {
14686 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14687 str, pindex, len);
14688 writer->pos += len;
14689 }
14690
14691 /* Pad right with the fill character if needed */
14692 if (arg->width > len) {
14693 sublen = arg->width - len;
14694 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14695 writer->pos += sublen;
14696 }
14697 return 0;
14698}
14699
14700/* Helper of PyUnicode_Format(): format one arg.
14701 Return 0 on success, raise an exception and return -1 on error. */
14702static int
14703unicode_format_arg(struct unicode_formatter_t *ctx)
14704{
14705 struct unicode_format_arg_t arg;
14706 PyObject *str;
14707 int ret;
14708
Victor Stinner8dbd4212012-12-04 09:30:24 +010014709 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14710 arg.flags = 0;
14711 arg.width = -1;
14712 arg.prec = -1;
14713 arg.sign = 0;
14714 str = NULL;
14715
Victor Stinnera47082312012-10-04 02:19:54 +020014716 ret = unicode_format_arg_parse(ctx, &arg);
14717 if (ret == -1)
14718 return -1;
14719
14720 ret = unicode_format_arg_format(ctx, &arg, &str);
14721 if (ret == -1)
14722 return -1;
14723
14724 if (ret != 1) {
14725 ret = unicode_format_arg_output(ctx, &arg, str);
14726 Py_DECREF(str);
14727 if (ret == -1)
14728 return -1;
14729 }
14730
14731 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14732 PyErr_SetString(PyExc_TypeError,
14733 "not all arguments converted during string formatting");
14734 return -1;
14735 }
14736 return 0;
14737}
14738
Alexander Belopolsky40018472011-02-26 01:02:56 +000014739PyObject *
14740PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014741{
Victor Stinnera47082312012-10-04 02:19:54 +020014742 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014743
Guido van Rossumd57fd912000-03-10 22:53:23 +000014744 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014745 PyErr_BadInternalCall();
14746 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014747 }
Victor Stinnera47082312012-10-04 02:19:54 +020014748
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014749 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014750 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014751
14752 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014753 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14754 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14755 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14756 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014757
Victor Stinner8f674cc2013-04-17 23:02:17 +020014758 _PyUnicodeWriter_Init(&ctx.writer);
14759 ctx.writer.min_length = ctx.fmtcnt + 100;
14760 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014761
Guido van Rossumd57fd912000-03-10 22:53:23 +000014762 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014763 ctx.arglen = PyTuple_Size(args);
14764 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014765 }
14766 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014767 ctx.arglen = -1;
14768 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014769 }
Victor Stinnera47082312012-10-04 02:19:54 +020014770 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014771 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014772 ctx.dict = args;
14773 else
14774 ctx.dict = NULL;
14775 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014776
Victor Stinnera47082312012-10-04 02:19:54 +020014777 while (--ctx.fmtcnt >= 0) {
14778 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014779 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014780
14781 nonfmtpos = ctx.fmtpos++;
14782 while (ctx.fmtcnt >= 0 &&
14783 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14784 ctx.fmtpos++;
14785 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014786 }
Victor Stinnera47082312012-10-04 02:19:54 +020014787 if (ctx.fmtcnt < 0) {
14788 ctx.fmtpos--;
14789 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014790 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014791
Victor Stinnercfc4c132013-04-03 01:48:39 +020014792 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14793 nonfmtpos, ctx.fmtpos) < 0)
14794 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014795 }
14796 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014797 ctx.fmtpos++;
14798 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014799 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014800 }
14801 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014802
Victor Stinnera47082312012-10-04 02:19:54 +020014803 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014804 PyErr_SetString(PyExc_TypeError,
14805 "not all arguments converted during string formatting");
14806 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014807 }
14808
Victor Stinnera47082312012-10-04 02:19:54 +020014809 if (ctx.args_owned) {
14810 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014811 }
Victor Stinnera47082312012-10-04 02:19:54 +020014812 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014813
Benjamin Peterson29060642009-01-31 22:14:21 +000014814 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014815 _PyUnicodeWriter_Dealloc(&ctx.writer);
14816 if (ctx.args_owned) {
14817 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014818 }
14819 return NULL;
14820}
14821
Jeremy Hylton938ace62002-07-17 16:30:39 +000014822static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014823unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14824
Tim Peters6d6c1a32001-08-02 04:15:00 +000014825static PyObject *
14826unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14827{
Benjamin Peterson29060642009-01-31 22:14:21 +000014828 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014829 static char *kwlist[] = {"object", "encoding", "errors", 0};
14830 char *encoding = NULL;
14831 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014832
Benjamin Peterson14339b62009-01-31 16:36:08 +000014833 if (type != &PyUnicode_Type)
14834 return unicode_subtype_new(type, args, kwds);
14835 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014836 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014837 return NULL;
14838 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014839 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014840 if (encoding == NULL && errors == NULL)
14841 return PyObject_Str(x);
14842 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014843 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014844}
14845
Guido van Rossume023fe02001-08-30 03:12:59 +000014846static PyObject *
14847unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14848{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014849 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014850 Py_ssize_t length, char_size;
14851 int share_wstr, share_utf8;
14852 unsigned int kind;
14853 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014854
Benjamin Peterson14339b62009-01-31 16:36:08 +000014855 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014856
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014857 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014858 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014859 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014860 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014861 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014862 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014863 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014864 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014865
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014866 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014867 if (self == NULL) {
14868 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014869 return NULL;
14870 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014871 kind = PyUnicode_KIND(unicode);
14872 length = PyUnicode_GET_LENGTH(unicode);
14873
14874 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014875#ifdef Py_DEBUG
14876 _PyUnicode_HASH(self) = -1;
14877#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014878 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014879#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014880 _PyUnicode_STATE(self).interned = 0;
14881 _PyUnicode_STATE(self).kind = kind;
14882 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014883 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014884 _PyUnicode_STATE(self).ready = 1;
14885 _PyUnicode_WSTR(self) = NULL;
14886 _PyUnicode_UTF8_LENGTH(self) = 0;
14887 _PyUnicode_UTF8(self) = NULL;
14888 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014889 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014890
14891 share_utf8 = 0;
14892 share_wstr = 0;
14893 if (kind == PyUnicode_1BYTE_KIND) {
14894 char_size = 1;
14895 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14896 share_utf8 = 1;
14897 }
14898 else if (kind == PyUnicode_2BYTE_KIND) {
14899 char_size = 2;
14900 if (sizeof(wchar_t) == 2)
14901 share_wstr = 1;
14902 }
14903 else {
14904 assert(kind == PyUnicode_4BYTE_KIND);
14905 char_size = 4;
14906 if (sizeof(wchar_t) == 4)
14907 share_wstr = 1;
14908 }
14909
14910 /* Ensure we won't overflow the length. */
14911 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14912 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014913 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014914 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014915 data = PyObject_MALLOC((length + 1) * char_size);
14916 if (data == NULL) {
14917 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014918 goto onError;
14919 }
14920
Victor Stinnerc3c74152011-10-02 20:39:55 +020014921 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014922 if (share_utf8) {
14923 _PyUnicode_UTF8_LENGTH(self) = length;
14924 _PyUnicode_UTF8(self) = data;
14925 }
14926 if (share_wstr) {
14927 _PyUnicode_WSTR_LENGTH(self) = length;
14928 _PyUnicode_WSTR(self) = (wchar_t *)data;
14929 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014930
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014931 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014932 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014933 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014934#ifdef Py_DEBUG
14935 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14936#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014937 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014938 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014939
14940onError:
14941 Py_DECREF(unicode);
14942 Py_DECREF(self);
14943 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014944}
14945
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014946PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014947"str(object='') -> str\n\
14948str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014949\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014950Create a new string object from the given object. If encoding or\n\
14951errors is specified, then the object must expose a data buffer\n\
14952that will be decoded using the given encoding and error handler.\n\
14953Otherwise, returns the result of object.__str__() (if defined)\n\
14954or repr(object).\n\
14955encoding defaults to sys.getdefaultencoding().\n\
14956errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014957
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014958static PyObject *unicode_iter(PyObject *seq);
14959
Guido van Rossumd57fd912000-03-10 22:53:23 +000014960PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014961 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014962 "str", /* tp_name */
14963 sizeof(PyUnicodeObject), /* tp_size */
14964 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014965 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014966 (destructor)unicode_dealloc, /* tp_dealloc */
14967 0, /* tp_print */
14968 0, /* tp_getattr */
14969 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014970 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014971 unicode_repr, /* tp_repr */
14972 &unicode_as_number, /* tp_as_number */
14973 &unicode_as_sequence, /* tp_as_sequence */
14974 &unicode_as_mapping, /* tp_as_mapping */
14975 (hashfunc) unicode_hash, /* tp_hash*/
14976 0, /* tp_call*/
14977 (reprfunc) unicode_str, /* tp_str */
14978 PyObject_GenericGetAttr, /* tp_getattro */
14979 0, /* tp_setattro */
14980 0, /* tp_as_buffer */
14981 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014982 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014983 unicode_doc, /* tp_doc */
14984 0, /* tp_traverse */
14985 0, /* tp_clear */
14986 PyUnicode_RichCompare, /* tp_richcompare */
14987 0, /* tp_weaklistoffset */
14988 unicode_iter, /* tp_iter */
14989 0, /* tp_iternext */
14990 unicode_methods, /* tp_methods */
14991 0, /* tp_members */
14992 0, /* tp_getset */
14993 &PyBaseObject_Type, /* tp_base */
14994 0, /* tp_dict */
14995 0, /* tp_descr_get */
14996 0, /* tp_descr_set */
14997 0, /* tp_dictoffset */
14998 0, /* tp_init */
14999 0, /* tp_alloc */
15000 unicode_new, /* tp_new */
15001 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015002};
15003
15004/* Initialize the Unicode implementation */
15005
Victor Stinner3a50e702011-10-18 21:21:00 +020015006int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015007{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015008 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015009 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015010 0x000A, /* LINE FEED */
15011 0x000D, /* CARRIAGE RETURN */
15012 0x001C, /* FILE SEPARATOR */
15013 0x001D, /* GROUP SEPARATOR */
15014 0x001E, /* RECORD SEPARATOR */
15015 0x0085, /* NEXT LINE */
15016 0x2028, /* LINE SEPARATOR */
15017 0x2029, /* PARAGRAPH SEPARATOR */
15018 };
15019
Fred Drakee4315f52000-05-09 19:53:39 +000015020 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015021 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015022 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015023 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015024 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015025
Guido van Rossumcacfc072002-05-24 19:01:59 +000015026 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015027 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015028
15029 /* initialize the linebreak bloom filter */
15030 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015031 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015032 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015033
Christian Heimes26532f72013-07-20 14:57:16 +020015034 if (PyType_Ready(&EncodingMapType) < 0)
15035 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015036
Benjamin Petersonc4311282012-10-30 23:21:10 -040015037 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15038 Py_FatalError("Can't initialize field name iterator type");
15039
15040 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15041 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015042
Victor Stinner3a50e702011-10-18 21:21:00 +020015043 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015044}
15045
15046/* Finalize the Unicode implementation */
15047
Christian Heimesa156e092008-02-16 07:38:31 +000015048int
15049PyUnicode_ClearFreeList(void)
15050{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015051 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015052}
15053
Guido van Rossumd57fd912000-03-10 22:53:23 +000015054void
Thomas Wouters78890102000-07-22 19:25:51 +000015055_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015056{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015057 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015058
Serhiy Storchaka05997252013-01-26 12:14:02 +020015059 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015060
Serhiy Storchaka05997252013-01-26 12:14:02 +020015061 for (i = 0; i < 256; i++)
15062 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015063 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015064 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015065}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015066
Walter Dörwald16807132007-05-25 13:52:07 +000015067void
15068PyUnicode_InternInPlace(PyObject **p)
15069{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015070 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015071 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015072#ifdef Py_DEBUG
15073 assert(s != NULL);
15074 assert(_PyUnicode_CHECK(s));
15075#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015076 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015077 return;
15078#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015079 /* If it's a subclass, we don't really know what putting
15080 it in the interned dict might do. */
15081 if (!PyUnicode_CheckExact(s))
15082 return;
15083 if (PyUnicode_CHECK_INTERNED(s))
15084 return;
15085 if (interned == NULL) {
15086 interned = PyDict_New();
15087 if (interned == NULL) {
15088 PyErr_Clear(); /* Don't leave an exception */
15089 return;
15090 }
15091 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015092 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015093 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015094 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015095 if (t == NULL) {
15096 PyErr_Clear();
15097 return;
15098 }
15099 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015100 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015101 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015102 return;
15103 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015104 /* The two references in interned are not counted by refcnt.
15105 The deallocator will take care of this */
15106 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015107 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015108}
15109
15110void
15111PyUnicode_InternImmortal(PyObject **p)
15112{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015113 PyUnicode_InternInPlace(p);
15114 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015115 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015116 Py_INCREF(*p);
15117 }
Walter Dörwald16807132007-05-25 13:52:07 +000015118}
15119
15120PyObject *
15121PyUnicode_InternFromString(const char *cp)
15122{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015123 PyObject *s = PyUnicode_FromString(cp);
15124 if (s == NULL)
15125 return NULL;
15126 PyUnicode_InternInPlace(&s);
15127 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015128}
15129
Alexander Belopolsky40018472011-02-26 01:02:56 +000015130void
15131_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015132{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015133 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015134 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015135 Py_ssize_t i, n;
15136 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015137
Benjamin Peterson14339b62009-01-31 16:36:08 +000015138 if (interned == NULL || !PyDict_Check(interned))
15139 return;
15140 keys = PyDict_Keys(interned);
15141 if (keys == NULL || !PyList_Check(keys)) {
15142 PyErr_Clear();
15143 return;
15144 }
Walter Dörwald16807132007-05-25 13:52:07 +000015145
Benjamin Peterson14339b62009-01-31 16:36:08 +000015146 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15147 detector, interned unicode strings are not forcibly deallocated;
15148 rather, we give them their stolen references back, and then clear
15149 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015150
Benjamin Peterson14339b62009-01-31 16:36:08 +000015151 n = PyList_GET_SIZE(keys);
15152 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015153 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015154 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015155 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015156 if (PyUnicode_READY(s) == -1) {
15157 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015158 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015159 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015160 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015161 case SSTATE_NOT_INTERNED:
15162 /* XXX Shouldn't happen */
15163 break;
15164 case SSTATE_INTERNED_IMMORTAL:
15165 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015166 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015167 break;
15168 case SSTATE_INTERNED_MORTAL:
15169 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015170 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015171 break;
15172 default:
15173 Py_FatalError("Inconsistent interned string state.");
15174 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015175 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015176 }
15177 fprintf(stderr, "total size of all interned strings: "
15178 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15179 "mortal/immortal\n", mortal_size, immortal_size);
15180 Py_DECREF(keys);
15181 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015182 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015183}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015184
15185
15186/********************* Unicode Iterator **************************/
15187
15188typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015189 PyObject_HEAD
15190 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015191 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015192} unicodeiterobject;
15193
15194static void
15195unicodeiter_dealloc(unicodeiterobject *it)
15196{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015197 _PyObject_GC_UNTRACK(it);
15198 Py_XDECREF(it->it_seq);
15199 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015200}
15201
15202static int
15203unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15204{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015205 Py_VISIT(it->it_seq);
15206 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015207}
15208
15209static PyObject *
15210unicodeiter_next(unicodeiterobject *it)
15211{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015212 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015213
Benjamin Peterson14339b62009-01-31 16:36:08 +000015214 assert(it != NULL);
15215 seq = it->it_seq;
15216 if (seq == NULL)
15217 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015218 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015219
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015220 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15221 int kind = PyUnicode_KIND(seq);
15222 void *data = PyUnicode_DATA(seq);
15223 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15224 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015225 if (item != NULL)
15226 ++it->it_index;
15227 return item;
15228 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015229
Benjamin Peterson14339b62009-01-31 16:36:08 +000015230 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015231 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015232 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015233}
15234
15235static PyObject *
15236unicodeiter_len(unicodeiterobject *it)
15237{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015238 Py_ssize_t len = 0;
15239 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015240 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015241 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015242}
15243
15244PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15245
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015246static PyObject *
15247unicodeiter_reduce(unicodeiterobject *it)
15248{
15249 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015250 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015251 it->it_seq, it->it_index);
15252 } else {
15253 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15254 if (u == NULL)
15255 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015256 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015257 }
15258}
15259
15260PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15261
15262static PyObject *
15263unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15264{
15265 Py_ssize_t index = PyLong_AsSsize_t(state);
15266 if (index == -1 && PyErr_Occurred())
15267 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015268 if (it->it_seq != NULL) {
15269 if (index < 0)
15270 index = 0;
15271 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15272 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15273 it->it_index = index;
15274 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015275 Py_RETURN_NONE;
15276}
15277
15278PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15279
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015280static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015281 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015282 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015283 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15284 reduce_doc},
15285 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15286 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015287 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015288};
15289
15290PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015291 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15292 "str_iterator", /* tp_name */
15293 sizeof(unicodeiterobject), /* tp_basicsize */
15294 0, /* tp_itemsize */
15295 /* methods */
15296 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15297 0, /* tp_print */
15298 0, /* tp_getattr */
15299 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015300 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015301 0, /* tp_repr */
15302 0, /* tp_as_number */
15303 0, /* tp_as_sequence */
15304 0, /* tp_as_mapping */
15305 0, /* tp_hash */
15306 0, /* tp_call */
15307 0, /* tp_str */
15308 PyObject_GenericGetAttr, /* tp_getattro */
15309 0, /* tp_setattro */
15310 0, /* tp_as_buffer */
15311 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15312 0, /* tp_doc */
15313 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15314 0, /* tp_clear */
15315 0, /* tp_richcompare */
15316 0, /* tp_weaklistoffset */
15317 PyObject_SelfIter, /* tp_iter */
15318 (iternextfunc)unicodeiter_next, /* tp_iternext */
15319 unicodeiter_methods, /* tp_methods */
15320 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015321};
15322
15323static PyObject *
15324unicode_iter(PyObject *seq)
15325{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015326 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015327
Benjamin Peterson14339b62009-01-31 16:36:08 +000015328 if (!PyUnicode_Check(seq)) {
15329 PyErr_BadInternalCall();
15330 return NULL;
15331 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015332 if (PyUnicode_READY(seq) == -1)
15333 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015334 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15335 if (it == NULL)
15336 return NULL;
15337 it->it_index = 0;
15338 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015339 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015340 _PyObject_GC_TRACK(it);
15341 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015342}
15343
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015344
15345size_t
15346Py_UNICODE_strlen(const Py_UNICODE *u)
15347{
15348 int res = 0;
15349 while(*u++)
15350 res++;
15351 return res;
15352}
15353
15354Py_UNICODE*
15355Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15356{
15357 Py_UNICODE *u = s1;
15358 while ((*u++ = *s2++));
15359 return s1;
15360}
15361
15362Py_UNICODE*
15363Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15364{
15365 Py_UNICODE *u = s1;
15366 while ((*u++ = *s2++))
15367 if (n-- == 0)
15368 break;
15369 return s1;
15370}
15371
15372Py_UNICODE*
15373Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15374{
15375 Py_UNICODE *u1 = s1;
15376 u1 += Py_UNICODE_strlen(u1);
15377 Py_UNICODE_strcpy(u1, s2);
15378 return s1;
15379}
15380
15381int
15382Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15383{
15384 while (*s1 && *s2 && *s1 == *s2)
15385 s1++, s2++;
15386 if (*s1 && *s2)
15387 return (*s1 < *s2) ? -1 : +1;
15388 if (*s1)
15389 return 1;
15390 if (*s2)
15391 return -1;
15392 return 0;
15393}
15394
15395int
15396Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15397{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015398 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015399 for (; n != 0; n--) {
15400 u1 = *s1;
15401 u2 = *s2;
15402 if (u1 != u2)
15403 return (u1 < u2) ? -1 : +1;
15404 if (u1 == '\0')
15405 return 0;
15406 s1++;
15407 s2++;
15408 }
15409 return 0;
15410}
15411
15412Py_UNICODE*
15413Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15414{
15415 const Py_UNICODE *p;
15416 for (p = s; *p; p++)
15417 if (*p == c)
15418 return (Py_UNICODE*)p;
15419 return NULL;
15420}
15421
15422Py_UNICODE*
15423Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15424{
15425 const Py_UNICODE *p;
15426 p = s + Py_UNICODE_strlen(s);
15427 while (p != s) {
15428 p--;
15429 if (*p == c)
15430 return (Py_UNICODE*)p;
15431 }
15432 return NULL;
15433}
Victor Stinner331ea922010-08-10 16:37:20 +000015434
Victor Stinner71133ff2010-09-01 23:43:53 +000015435Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015436PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015437{
Victor Stinner577db2c2011-10-11 22:12:48 +020015438 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015439 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015440
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015441 if (!PyUnicode_Check(unicode)) {
15442 PyErr_BadArgument();
15443 return NULL;
15444 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015445 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015446 if (u == NULL)
15447 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015448 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015449 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015450 PyErr_NoMemory();
15451 return NULL;
15452 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015453 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015454 size *= sizeof(Py_UNICODE);
15455 copy = PyMem_Malloc(size);
15456 if (copy == NULL) {
15457 PyErr_NoMemory();
15458 return NULL;
15459 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015460 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015461 return copy;
15462}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015463
Georg Brandl66c221e2010-10-14 07:04:07 +000015464/* A _string module, to export formatter_parser and formatter_field_name_split
15465 to the string.Formatter class implemented in Python. */
15466
15467static PyMethodDef _string_methods[] = {
15468 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15469 METH_O, PyDoc_STR("split the argument as a field name")},
15470 {"formatter_parser", (PyCFunction) formatter_parser,
15471 METH_O, PyDoc_STR("parse the argument as a format string")},
15472 {NULL, NULL}
15473};
15474
15475static struct PyModuleDef _string_module = {
15476 PyModuleDef_HEAD_INIT,
15477 "_string",
15478 PyDoc_STR("string helper module"),
15479 0,
15480 _string_methods,
15481 NULL,
15482 NULL,
15483 NULL,
15484 NULL
15485};
15486
15487PyMODINIT_FUNC
15488PyInit__string(void)
15489{
15490 return PyModule_Create(&_string_module);
15491}
15492
15493
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015494#ifdef __cplusplus
15495}
15496#endif