blob: aa0402adc0b1553ba17949464df97580407b3218 [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 */
207Py_LOCAL_INLINE(int)
208_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
Alexander Belopolsky40018472011-02-26 01:02:56 +0000723Py_LOCAL_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
Serhiy Storchakad9d769f2015-03-24 21:55:47 +0200829Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200830 Py_ssize_t size, Py_UCS4 ch,
831 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200832{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200833 switch (kind) {
834 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200835 if ((Py_UCS1) ch != ch)
836 return -1;
837 if (direction > 0)
838 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
839 else
840 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200841 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200842 if ((Py_UCS2) ch != ch)
843 return -1;
844 if (direction > 0)
845 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
846 else
847 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200848 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200849 if (direction > 0)
850 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
851 else
852 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200853 default:
854 assert(0);
855 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200857}
858
Victor Stinnerafffce42012-10-03 23:03:17 +0200859#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000860/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200861 earlier.
862
863 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
864 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
865 invalid character in Unicode 6.0. */
866static void
867unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
868{
869 int kind = PyUnicode_KIND(unicode);
870 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
871 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
872 if (length <= old_length)
873 return;
874 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
875}
876#endif
877
Victor Stinnerfe226c02011-10-03 03:52:20 +0200878static PyObject*
879resize_compact(PyObject *unicode, Py_ssize_t length)
880{
881 Py_ssize_t char_size;
882 Py_ssize_t struct_size;
883 Py_ssize_t new_size;
884 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100885 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200886#ifdef Py_DEBUG
887 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
888#endif
889
Victor Stinner79891572012-05-03 13:43:07 +0200890 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200891 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100892 assert(PyUnicode_IS_COMPACT(unicode));
893
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200894 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100895 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200896 struct_size = sizeof(PyASCIIObject);
897 else
898 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200899 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200900
Victor Stinnerfe226c02011-10-03 03:52:20 +0200901 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
902 PyErr_NoMemory();
903 return NULL;
904 }
905 new_size = (struct_size + (length + 1) * char_size);
906
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200907 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
908 PyObject_DEL(_PyUnicode_UTF8(unicode));
909 _PyUnicode_UTF8(unicode) = NULL;
910 _PyUnicode_UTF8_LENGTH(unicode) = 0;
911 }
Victor Stinner84def372011-12-11 20:04:56 +0100912 _Py_DEC_REFTOTAL;
913 _Py_ForgetReference(unicode);
914
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300915 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100916 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100917 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200918 PyErr_NoMemory();
919 return NULL;
920 }
Victor Stinner84def372011-12-11 20:04:56 +0100921 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200922 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100923
Victor Stinnerfe226c02011-10-03 03:52:20 +0200924 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200925 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200926 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100927 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200928 _PyUnicode_WSTR_LENGTH(unicode) = length;
929 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100930 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
931 PyObject_DEL(_PyUnicode_WSTR(unicode));
932 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100933 if (!PyUnicode_IS_ASCII(unicode))
934 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100935 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200936#ifdef Py_DEBUG
937 unicode_fill_invalid(unicode, old_length);
938#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200939 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
940 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200941 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200942 return unicode;
943}
944
Alexander Belopolsky40018472011-02-26 01:02:56 +0000945static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200946resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000947{
Victor Stinner95663112011-10-04 01:03:50 +0200948 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100949 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200950 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200951 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000952
Victor Stinnerfe226c02011-10-03 03:52:20 +0200953 if (PyUnicode_IS_READY(unicode)) {
954 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200955 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200956 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200957#ifdef Py_DEBUG
958 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
959#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200960
961 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200962 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200963 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
964 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200965
966 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
967 PyErr_NoMemory();
968 return -1;
969 }
970 new_size = (length + 1) * char_size;
971
Victor Stinner7a9105a2011-12-12 00:13:42 +0100972 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
973 {
974 PyObject_DEL(_PyUnicode_UTF8(unicode));
975 _PyUnicode_UTF8(unicode) = NULL;
976 _PyUnicode_UTF8_LENGTH(unicode) = 0;
977 }
978
Victor Stinnerfe226c02011-10-03 03:52:20 +0200979 data = (PyObject *)PyObject_REALLOC(data, new_size);
980 if (data == NULL) {
981 PyErr_NoMemory();
982 return -1;
983 }
984 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200985 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200986 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200987 _PyUnicode_WSTR_LENGTH(unicode) = length;
988 }
989 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200990 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200991 _PyUnicode_UTF8_LENGTH(unicode) = length;
992 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200993 _PyUnicode_LENGTH(unicode) = length;
994 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200995#ifdef Py_DEBUG
996 unicode_fill_invalid(unicode, old_length);
997#endif
Victor Stinner95663112011-10-04 01:03:50 +0200998 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200999 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001000 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001001 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001002 }
Victor Stinner95663112011-10-04 01:03:50 +02001003 assert(_PyUnicode_WSTR(unicode) != NULL);
1004
1005 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001006 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001007 PyErr_NoMemory();
1008 return -1;
1009 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001010 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001011 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001012 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001013 if (!wstr) {
1014 PyErr_NoMemory();
1015 return -1;
1016 }
1017 _PyUnicode_WSTR(unicode) = wstr;
1018 _PyUnicode_WSTR(unicode)[length] = 0;
1019 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001020 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001021 return 0;
1022}
1023
Victor Stinnerfe226c02011-10-03 03:52:20 +02001024static PyObject*
1025resize_copy(PyObject *unicode, Py_ssize_t length)
1026{
1027 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001028 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001029 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001030
Benjamin Petersonbac79492012-01-14 13:34:47 -05001031 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +01001032 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001033
1034 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1035 if (copy == NULL)
1036 return NULL;
1037
1038 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001039 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001040 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001041 }
1042 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001043 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001044
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001045 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046 if (w == NULL)
1047 return NULL;
1048 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1049 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001050 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
1051 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001052 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001053 }
1054}
1055
Guido van Rossumd57fd912000-03-10 22:53:23 +00001056/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001057 Ux0000 terminated; some code (e.g. new_identifier)
1058 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001059
1060 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001061 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001062
1063*/
1064
Alexander Belopolsky40018472011-02-26 01:02:56 +00001065static PyUnicodeObject *
1066_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001067{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001068 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001069 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001070
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001072 if (length == 0 && unicode_empty != NULL) {
1073 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001074 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001075 }
1076
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001077 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001078 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001079 return (PyUnicodeObject *)PyErr_NoMemory();
1080 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081 if (length < 0) {
1082 PyErr_SetString(PyExc_SystemError,
1083 "Negative size passed to _PyUnicode_New");
1084 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001085 }
1086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1088 if (unicode == NULL)
1089 return NULL;
1090 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001091
1092 _PyUnicode_WSTR_LENGTH(unicode) = length;
1093 _PyUnicode_HASH(unicode) = -1;
1094 _PyUnicode_STATE(unicode).interned = 0;
1095 _PyUnicode_STATE(unicode).kind = 0;
1096 _PyUnicode_STATE(unicode).compact = 0;
1097 _PyUnicode_STATE(unicode).ready = 0;
1098 _PyUnicode_STATE(unicode).ascii = 0;
1099 _PyUnicode_DATA_ANY(unicode) = NULL;
1100 _PyUnicode_LENGTH(unicode) = 0;
1101 _PyUnicode_UTF8(unicode) = NULL;
1102 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001104 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1105 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001106 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001107 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001108 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001109 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110
Jeremy Hyltond8082792003-09-16 19:41:39 +00001111 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001112 * the caller fails before initializing str -- unicode_resize()
1113 * reads str[0], and the Keep-Alive optimization can keep memory
1114 * allocated for str alive across a call to unicode_dealloc(unicode).
1115 * We don't want unicode_resize to read uninitialized memory in
1116 * that case.
1117 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001118 _PyUnicode_WSTR(unicode)[0] = 0;
1119 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001120
Victor Stinner7931d9a2011-11-04 00:22:48 +01001121 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001122 return unicode;
1123}
1124
Victor Stinnerf42dc442011-10-02 23:33:16 +02001125static const char*
1126unicode_kind_name(PyObject *unicode)
1127{
Victor Stinner42dfd712011-10-03 14:41:45 +02001128 /* don't check consistency: unicode_kind_name() is called from
1129 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001130 if (!PyUnicode_IS_COMPACT(unicode))
1131 {
1132 if (!PyUnicode_IS_READY(unicode))
1133 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001134 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001135 {
1136 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001137 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001138 return "legacy ascii";
1139 else
1140 return "legacy latin1";
1141 case PyUnicode_2BYTE_KIND:
1142 return "legacy UCS2";
1143 case PyUnicode_4BYTE_KIND:
1144 return "legacy UCS4";
1145 default:
1146 return "<legacy invalid kind>";
1147 }
1148 }
1149 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001150 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001152 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001153 return "ascii";
1154 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001155 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001156 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001157 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001158 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001159 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001160 default:
1161 return "<invalid compact kind>";
1162 }
1163}
1164
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001165#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166/* Functions wrapping macros for use in debugger */
1167char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001168 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001169}
1170
1171void *_PyUnicode_compact_data(void *unicode) {
1172 return _PyUnicode_COMPACT_DATA(unicode);
1173}
1174void *_PyUnicode_data(void *unicode){
1175 printf("obj %p\n", unicode);
1176 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1177 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1178 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1179 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1180 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1181 return PyUnicode_DATA(unicode);
1182}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001183
1184void
1185_PyUnicode_Dump(PyObject *op)
1186{
1187 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001188 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1189 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1190 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001191
Victor Stinnera849a4b2011-10-03 12:12:11 +02001192 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001193 {
1194 if (ascii->state.ascii)
1195 data = (ascii + 1);
1196 else
1197 data = (compact + 1);
1198 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001199 else
1200 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001201 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1202 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001203
Victor Stinnera849a4b2011-10-03 12:12:11 +02001204 if (ascii->wstr == data)
1205 printf("shared ");
1206 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001207
Victor Stinnera3b334d2011-10-03 13:53:37 +02001208 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001209 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001210 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1211 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001212 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1213 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001214 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001215 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001216}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001217#endif
1218
1219PyObject *
1220PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1221{
1222 PyObject *obj;
1223 PyCompactUnicodeObject *unicode;
1224 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001225 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001226 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001227 Py_ssize_t char_size;
1228 Py_ssize_t struct_size;
1229
1230 /* Optimization for empty strings */
1231 if (size == 0 && unicode_empty != NULL) {
1232 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001233 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001234 }
1235
Victor Stinner9e9d6892011-10-04 01:02:02 +02001236 is_ascii = 0;
1237 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001238 struct_size = sizeof(PyCompactUnicodeObject);
1239 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001240 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001241 char_size = 1;
1242 is_ascii = 1;
1243 struct_size = sizeof(PyASCIIObject);
1244 }
1245 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001246 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001247 char_size = 1;
1248 }
1249 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001250 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 char_size = 2;
1252 if (sizeof(wchar_t) == 2)
1253 is_sharing = 1;
1254 }
1255 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001256 if (maxchar > MAX_UNICODE) {
1257 PyErr_SetString(PyExc_SystemError,
1258 "invalid maximum character passed to PyUnicode_New");
1259 return NULL;
1260 }
Victor Stinner8f825062012-04-27 13:55:39 +02001261 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001262 char_size = 4;
1263 if (sizeof(wchar_t) == 4)
1264 is_sharing = 1;
1265 }
1266
1267 /* Ensure we won't overflow the size. */
1268 if (size < 0) {
1269 PyErr_SetString(PyExc_SystemError,
1270 "Negative size passed to PyUnicode_New");
1271 return NULL;
1272 }
1273 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1274 return PyErr_NoMemory();
1275
1276 /* Duplicated allocation code from _PyObject_New() instead of a call to
1277 * PyObject_New() so we are able to allocate space for the object and
1278 * it's data buffer.
1279 */
1280 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1281 if (obj == NULL)
1282 return PyErr_NoMemory();
1283 obj = PyObject_INIT(obj, &PyUnicode_Type);
1284 if (obj == NULL)
1285 return NULL;
1286
1287 unicode = (PyCompactUnicodeObject *)obj;
1288 if (is_ascii)
1289 data = ((PyASCIIObject*)obj) + 1;
1290 else
1291 data = unicode + 1;
1292 _PyUnicode_LENGTH(unicode) = size;
1293 _PyUnicode_HASH(unicode) = -1;
1294 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001295 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001296 _PyUnicode_STATE(unicode).compact = 1;
1297 _PyUnicode_STATE(unicode).ready = 1;
1298 _PyUnicode_STATE(unicode).ascii = is_ascii;
1299 if (is_ascii) {
1300 ((char*)data)[size] = 0;
1301 _PyUnicode_WSTR(unicode) = NULL;
1302 }
Victor Stinner8f825062012-04-27 13:55:39 +02001303 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 ((char*)data)[size] = 0;
1305 _PyUnicode_WSTR(unicode) = NULL;
1306 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001308 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310 else {
1311 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001312 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001313 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001315 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 ((Py_UCS4*)data)[size] = 0;
1317 if (is_sharing) {
1318 _PyUnicode_WSTR_LENGTH(unicode) = size;
1319 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1320 }
1321 else {
1322 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1323 _PyUnicode_WSTR(unicode) = NULL;
1324 }
1325 }
Victor Stinner8f825062012-04-27 13:55:39 +02001326#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001327 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001328#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001329 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330 return obj;
1331}
1332
1333#if SIZEOF_WCHAR_T == 2
1334/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1335 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001336 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337
1338 This function assumes that unicode can hold one more code point than wstr
1339 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001340static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001341unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001342 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343{
1344 const wchar_t *iter;
1345 Py_UCS4 *ucs4_out;
1346
Victor Stinner910337b2011-10-03 03:20:16 +02001347 assert(unicode != NULL);
1348 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1350 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1351
1352 for (iter = begin; iter < end; ) {
1353 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1354 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001355 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1356 && (iter+1) < end
1357 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001358 {
Victor Stinner551ac952011-11-29 22:58:13 +01001359 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001360 iter += 2;
1361 }
1362 else {
1363 *ucs4_out++ = *iter;
1364 iter++;
1365 }
1366 }
1367 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1368 _PyUnicode_GET_LENGTH(unicode)));
1369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001370}
1371#endif
1372
Victor Stinnercd9950f2011-10-02 00:34:53 +02001373static int
Victor Stinner488fa492011-12-12 00:01:39 +01001374unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001375{
Victor Stinner488fa492011-12-12 00:01:39 +01001376 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001377 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001378 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001379 return -1;
1380 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001381 return 0;
1382}
1383
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001384static int
1385_copy_characters(PyObject *to, Py_ssize_t to_start,
1386 PyObject *from, Py_ssize_t from_start,
1387 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001388{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001389 unsigned int from_kind, to_kind;
1390 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001391
Victor Stinneree4544c2012-05-09 22:24:08 +02001392 assert(0 <= how_many);
1393 assert(0 <= from_start);
1394 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001395 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001396 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001397 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001398
Victor Stinnerd3f08822012-05-29 12:57:52 +02001399 assert(PyUnicode_Check(to));
1400 assert(PyUnicode_IS_READY(to));
1401 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1402
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001403 if (how_many == 0)
1404 return 0;
1405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001407 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001409 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410
Victor Stinnerf1852262012-06-16 16:38:26 +02001411#ifdef Py_DEBUG
1412 if (!check_maxchar
1413 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1414 {
1415 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1416 Py_UCS4 ch;
1417 Py_ssize_t i;
1418 for (i=0; i < how_many; i++) {
1419 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1420 assert(ch <= to_maxchar);
1421 }
1422 }
1423#endif
1424
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001425 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001426 if (check_maxchar
1427 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1428 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001429 /* Writing Latin-1 characters into an ASCII string requires to
1430 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001431 Py_UCS4 max_char;
1432 max_char = ucs1lib_find_max_char(from_data,
1433 (Py_UCS1*)from_data + how_many);
1434 if (max_char >= 128)
1435 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001436 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001437 Py_MEMCPY((char*)to_data + to_kind * to_start,
1438 (char*)from_data + from_kind * from_start,
1439 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001441 else if (from_kind == PyUnicode_1BYTE_KIND
1442 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001443 {
1444 _PyUnicode_CONVERT_BYTES(
1445 Py_UCS1, Py_UCS2,
1446 PyUnicode_1BYTE_DATA(from) + from_start,
1447 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1448 PyUnicode_2BYTE_DATA(to) + to_start
1449 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001450 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001451 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001452 && to_kind == PyUnicode_4BYTE_KIND)
1453 {
1454 _PyUnicode_CONVERT_BYTES(
1455 Py_UCS1, Py_UCS4,
1456 PyUnicode_1BYTE_DATA(from) + from_start,
1457 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1458 PyUnicode_4BYTE_DATA(to) + to_start
1459 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001460 }
1461 else if (from_kind == PyUnicode_2BYTE_KIND
1462 && to_kind == PyUnicode_4BYTE_KIND)
1463 {
1464 _PyUnicode_CONVERT_BYTES(
1465 Py_UCS2, Py_UCS4,
1466 PyUnicode_2BYTE_DATA(from) + from_start,
1467 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1468 PyUnicode_4BYTE_DATA(to) + to_start
1469 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001470 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001471 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001472 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1473
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001474 if (!check_maxchar) {
1475 if (from_kind == PyUnicode_2BYTE_KIND
1476 && to_kind == PyUnicode_1BYTE_KIND)
1477 {
1478 _PyUnicode_CONVERT_BYTES(
1479 Py_UCS2, Py_UCS1,
1480 PyUnicode_2BYTE_DATA(from) + from_start,
1481 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1482 PyUnicode_1BYTE_DATA(to) + to_start
1483 );
1484 }
1485 else if (from_kind == PyUnicode_4BYTE_KIND
1486 && to_kind == PyUnicode_1BYTE_KIND)
1487 {
1488 _PyUnicode_CONVERT_BYTES(
1489 Py_UCS4, Py_UCS1,
1490 PyUnicode_4BYTE_DATA(from) + from_start,
1491 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1492 PyUnicode_1BYTE_DATA(to) + to_start
1493 );
1494 }
1495 else if (from_kind == PyUnicode_4BYTE_KIND
1496 && to_kind == PyUnicode_2BYTE_KIND)
1497 {
1498 _PyUnicode_CONVERT_BYTES(
1499 Py_UCS4, Py_UCS2,
1500 PyUnicode_4BYTE_DATA(from) + from_start,
1501 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1502 PyUnicode_2BYTE_DATA(to) + to_start
1503 );
1504 }
1505 else {
1506 assert(0);
1507 return -1;
1508 }
1509 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001510 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001511 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001512 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001513 Py_ssize_t i;
1514
Victor Stinnera0702ab2011-09-29 14:14:38 +02001515 for (i=0; i < how_many; i++) {
1516 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001517 if (ch > to_maxchar)
1518 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001519 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1520 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001521 }
1522 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001523 return 0;
1524}
1525
Victor Stinnerd3f08822012-05-29 12:57:52 +02001526void
1527_PyUnicode_FastCopyCharacters(
1528 PyObject *to, Py_ssize_t to_start,
1529 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001530{
1531 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1532}
1533
1534Py_ssize_t
1535PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1536 PyObject *from, Py_ssize_t from_start,
1537 Py_ssize_t how_many)
1538{
1539 int err;
1540
1541 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1542 PyErr_BadInternalCall();
1543 return -1;
1544 }
1545
Benjamin Petersonbac79492012-01-14 13:34:47 -05001546 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001547 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001548 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001549 return -1;
1550
Victor Stinnerd3f08822012-05-29 12:57:52 +02001551 if (from_start < 0) {
1552 PyErr_SetString(PyExc_IndexError, "string index out of range");
1553 return -1;
1554 }
1555 if (to_start < 0) {
1556 PyErr_SetString(PyExc_IndexError, "string index out of range");
1557 return -1;
1558 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001559 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1560 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1561 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001562 "Cannot write %zi characters at %zi "
1563 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001564 how_many, to_start, PyUnicode_GET_LENGTH(to));
1565 return -1;
1566 }
1567
1568 if (how_many == 0)
1569 return 0;
1570
Victor Stinner488fa492011-12-12 00:01:39 +01001571 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001572 return -1;
1573
1574 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1575 if (err) {
1576 PyErr_Format(PyExc_SystemError,
1577 "Cannot copy %s characters "
1578 "into a string of %s characters",
1579 unicode_kind_name(from),
1580 unicode_kind_name(to));
1581 return -1;
1582 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001583 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001584}
1585
Victor Stinner17222162011-09-28 22:15:37 +02001586/* Find the maximum code point and count the number of surrogate pairs so a
1587 correct string length can be computed before converting a string to UCS4.
1588 This function counts single surrogates as a character and not as a pair.
1589
1590 Return 0 on success, or -1 on error. */
1591static int
1592find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1593 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594{
1595 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001596 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597
Victor Stinnerc53be962011-10-02 21:33:54 +02001598 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001599 *num_surrogates = 0;
1600 *maxchar = 0;
1601
1602 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001603#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001604 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1605 && (iter+1) < end
1606 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1607 {
1608 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1609 ++(*num_surrogates);
1610 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001611 }
1612 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001613#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001614 {
1615 ch = *iter;
1616 iter++;
1617 }
1618 if (ch > *maxchar) {
1619 *maxchar = ch;
1620 if (*maxchar > MAX_UNICODE) {
1621 PyErr_Format(PyExc_ValueError,
1622 "character U+%x is not in range [U+0000; U+10ffff]",
1623 ch);
1624 return -1;
1625 }
1626 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001627 }
1628 return 0;
1629}
1630
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001631int
1632_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001633{
1634 wchar_t *end;
1635 Py_UCS4 maxchar = 0;
1636 Py_ssize_t num_surrogates;
1637#if SIZEOF_WCHAR_T == 2
1638 Py_ssize_t length_wo_surrogates;
1639#endif
1640
Georg Brandl7597add2011-10-05 16:36:47 +02001641 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001642 strings were created using _PyObject_New() and where no canonical
1643 representation (the str field) has been set yet aka strings
1644 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001645 assert(_PyUnicode_CHECK(unicode));
1646 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001647 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001648 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001649 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001650 /* Actually, it should neither be interned nor be anything else: */
1651 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001653 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001654 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001655 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001656 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657
1658 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001659 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1660 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661 PyErr_NoMemory();
1662 return -1;
1663 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001664 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001665 _PyUnicode_WSTR(unicode), end,
1666 PyUnicode_1BYTE_DATA(unicode));
1667 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1668 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1669 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1670 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001671 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001672 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001673 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001674 }
1675 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001676 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001677 _PyUnicode_UTF8(unicode) = NULL;
1678 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001679 }
1680 PyObject_FREE(_PyUnicode_WSTR(unicode));
1681 _PyUnicode_WSTR(unicode) = NULL;
1682 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1683 }
1684 /* In this case we might have to convert down from 4-byte native
1685 wchar_t to 2-byte unicode. */
1686 else if (maxchar < 65536) {
1687 assert(num_surrogates == 0 &&
1688 "FindMaxCharAndNumSurrogatePairs() messed up");
1689
Victor Stinner506f5922011-09-28 22:34:18 +02001690#if SIZEOF_WCHAR_T == 2
1691 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001692 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001693 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1694 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1695 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001696 _PyUnicode_UTF8(unicode) = NULL;
1697 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001698#else
1699 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001700 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001701 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001702 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001703 PyErr_NoMemory();
1704 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001705 }
Victor Stinner506f5922011-09-28 22:34:18 +02001706 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1707 _PyUnicode_WSTR(unicode), end,
1708 PyUnicode_2BYTE_DATA(unicode));
1709 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1710 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1711 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001712 _PyUnicode_UTF8(unicode) = NULL;
1713 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001714 PyObject_FREE(_PyUnicode_WSTR(unicode));
1715 _PyUnicode_WSTR(unicode) = NULL;
1716 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1717#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001718 }
1719 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1720 else {
1721#if SIZEOF_WCHAR_T == 2
1722 /* in case the native representation is 2-bytes, we need to allocate a
1723 new normalized 4-byte version. */
1724 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001725 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1726 PyErr_NoMemory();
1727 return -1;
1728 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001729 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1730 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001731 PyErr_NoMemory();
1732 return -1;
1733 }
1734 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1735 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001736 _PyUnicode_UTF8(unicode) = NULL;
1737 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001738 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1739 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001740 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001741 PyObject_FREE(_PyUnicode_WSTR(unicode));
1742 _PyUnicode_WSTR(unicode) = NULL;
1743 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1744#else
1745 assert(num_surrogates == 0);
1746
Victor Stinnerc3c74152011-10-02 20:39:55 +02001747 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001749 _PyUnicode_UTF8(unicode) = NULL;
1750 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001751 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1752#endif
1753 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1754 }
1755 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001756 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 return 0;
1758}
1759
Alexander Belopolsky40018472011-02-26 01:02:56 +00001760static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001761unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001762{
Walter Dörwald16807132007-05-25 13:52:07 +00001763 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001764 case SSTATE_NOT_INTERNED:
1765 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001766
Benjamin Peterson29060642009-01-31 22:14:21 +00001767 case SSTATE_INTERNED_MORTAL:
1768 /* revive dead object temporarily for DelItem */
1769 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001770 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001771 Py_FatalError(
1772 "deletion of interned string failed");
1773 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001774
Benjamin Peterson29060642009-01-31 22:14:21 +00001775 case SSTATE_INTERNED_IMMORTAL:
1776 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001777
Benjamin Peterson29060642009-01-31 22:14:21 +00001778 default:
1779 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001780 }
1781
Victor Stinner03490912011-10-03 23:45:12 +02001782 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001783 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001784 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001785 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001786 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1787 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001788
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001789 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001790}
1791
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001792#ifdef Py_DEBUG
1793static int
1794unicode_is_singleton(PyObject *unicode)
1795{
1796 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1797 if (unicode == unicode_empty)
1798 return 1;
1799 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1800 {
1801 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1802 if (ch < 256 && unicode_latin1[ch] == unicode)
1803 return 1;
1804 }
1805 return 0;
1806}
1807#endif
1808
Alexander Belopolsky40018472011-02-26 01:02:56 +00001809static int
Victor Stinner488fa492011-12-12 00:01:39 +01001810unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001811{
Victor Stinner488fa492011-12-12 00:01:39 +01001812 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001813 if (Py_REFCNT(unicode) != 1)
1814 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001815 if (_PyUnicode_HASH(unicode) != -1)
1816 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001817 if (PyUnicode_CHECK_INTERNED(unicode))
1818 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001819 if (!PyUnicode_CheckExact(unicode))
1820 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001821#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001822 /* singleton refcount is greater than 1 */
1823 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001824#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001825 return 1;
1826}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001827
Victor Stinnerfe226c02011-10-03 03:52:20 +02001828static int
1829unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1830{
1831 PyObject *unicode;
1832 Py_ssize_t old_length;
1833
1834 assert(p_unicode != NULL);
1835 unicode = *p_unicode;
1836
1837 assert(unicode != NULL);
1838 assert(PyUnicode_Check(unicode));
1839 assert(0 <= length);
1840
Victor Stinner910337b2011-10-03 03:20:16 +02001841 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001842 old_length = PyUnicode_WSTR_LENGTH(unicode);
1843 else
1844 old_length = PyUnicode_GET_LENGTH(unicode);
1845 if (old_length == length)
1846 return 0;
1847
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001848 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001849 _Py_INCREF_UNICODE_EMPTY();
1850 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001851 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001852 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001853 return 0;
1854 }
1855
Victor Stinner488fa492011-12-12 00:01:39 +01001856 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001857 PyObject *copy = resize_copy(unicode, length);
1858 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001859 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001860 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001861 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001862 }
1863
Victor Stinnerfe226c02011-10-03 03:52:20 +02001864 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001865 PyObject *new_unicode = resize_compact(unicode, length);
1866 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001867 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001868 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001869 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001870 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001871 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001872}
1873
Alexander Belopolsky40018472011-02-26 01:02:56 +00001874int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001875PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001876{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001877 PyObject *unicode;
1878 if (p_unicode == NULL) {
1879 PyErr_BadInternalCall();
1880 return -1;
1881 }
1882 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001883 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001884 {
1885 PyErr_BadInternalCall();
1886 return -1;
1887 }
1888 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001889}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001890
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001891/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001892
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001893 WARNING: The function doesn't copy the terminating null character and
1894 doesn't check the maximum character (may write a latin1 character in an
1895 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001896static void
1897unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1898 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001899{
1900 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1901 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001902 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001903
1904 switch (kind) {
1905 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001906 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001907#ifdef Py_DEBUG
1908 if (PyUnicode_IS_ASCII(unicode)) {
1909 Py_UCS4 maxchar = ucs1lib_find_max_char(
1910 (const Py_UCS1*)str,
1911 (const Py_UCS1*)str + len);
1912 assert(maxchar < 128);
1913 }
1914#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001915 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001916 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001917 }
1918 case PyUnicode_2BYTE_KIND: {
1919 Py_UCS2 *start = (Py_UCS2 *)data + index;
1920 Py_UCS2 *ucs2 = start;
1921 assert(index <= PyUnicode_GET_LENGTH(unicode));
1922
Victor Stinner184252a2012-06-16 02:57:41 +02001923 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001924 *ucs2 = (Py_UCS2)*str;
1925
1926 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001927 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001928 }
1929 default: {
1930 Py_UCS4 *start = (Py_UCS4 *)data + index;
1931 Py_UCS4 *ucs4 = start;
1932 assert(kind == PyUnicode_4BYTE_KIND);
1933 assert(index <= PyUnicode_GET_LENGTH(unicode));
1934
Victor Stinner184252a2012-06-16 02:57:41 +02001935 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001936 *ucs4 = (Py_UCS4)*str;
1937
1938 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001939 }
1940 }
1941}
1942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943static PyObject*
1944get_latin1_char(unsigned char ch)
1945{
Victor Stinnera464fc12011-10-02 20:39:30 +02001946 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001947 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001948 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001949 if (!unicode)
1950 return NULL;
1951 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001952 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 unicode_latin1[ch] = unicode;
1954 }
1955 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001956 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001957}
1958
Victor Stinner985a82a2014-01-03 12:53:47 +01001959static PyObject*
1960unicode_char(Py_UCS4 ch)
1961{
1962 PyObject *unicode;
1963
1964 assert(ch <= MAX_UNICODE);
1965
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001966 if (ch < 256)
1967 return get_latin1_char(ch);
1968
Victor Stinner985a82a2014-01-03 12:53:47 +01001969 unicode = PyUnicode_New(1, ch);
1970 if (unicode == NULL)
1971 return NULL;
1972 switch (PyUnicode_KIND(unicode)) {
1973 case PyUnicode_1BYTE_KIND:
1974 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1975 break;
1976 case PyUnicode_2BYTE_KIND:
1977 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1978 break;
1979 default:
1980 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1981 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1982 }
1983 assert(_PyUnicode_CheckConsistency(unicode, 1));
1984 return unicode;
1985}
1986
Alexander Belopolsky40018472011-02-26 01:02:56 +00001987PyObject *
1988PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001989{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001990 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001991 Py_UCS4 maxchar = 0;
1992 Py_ssize_t num_surrogates;
1993
1994 if (u == NULL)
1995 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001996
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001997 /* If the Unicode data is known at construction time, we can apply
1998 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002001 if (size == 0)
2002 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002003
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002004 /* Single character Unicode objects in the Latin-1 range are
2005 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002006 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002007 return get_latin1_char((unsigned char)*u);
2008
2009 /* If not empty and not single character, copy the Unicode data
2010 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002011 if (find_maxchar_surrogates(u, u + size,
2012 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002013 return NULL;
2014
Victor Stinner8faf8212011-12-08 22:14:11 +01002015 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002016 if (!unicode)
2017 return NULL;
2018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002019 switch (PyUnicode_KIND(unicode)) {
2020 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002021 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002022 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2023 break;
2024 case PyUnicode_2BYTE_KIND:
2025#if Py_UNICODE_SIZE == 2
2026 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
2027#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002028 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002029 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2030#endif
2031 break;
2032 case PyUnicode_4BYTE_KIND:
2033#if SIZEOF_WCHAR_T == 2
2034 /* This is the only case which has to process surrogates, thus
2035 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002036 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037#else
2038 assert(num_surrogates == 0);
2039 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
2040#endif
2041 break;
2042 default:
2043 assert(0 && "Impossible state");
2044 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002045
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002046 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002047}
2048
Alexander Belopolsky40018472011-02-26 01:02:56 +00002049PyObject *
2050PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002051{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002052 if (size < 0) {
2053 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002054 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002055 return NULL;
2056 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002057 if (u != NULL)
2058 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2059 else
2060 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002061}
2062
Alexander Belopolsky40018472011-02-26 01:02:56 +00002063PyObject *
2064PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002065{
2066 size_t size = strlen(u);
2067 if (size > PY_SSIZE_T_MAX) {
2068 PyErr_SetString(PyExc_OverflowError, "input too long");
2069 return NULL;
2070 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002071 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002072}
2073
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002074PyObject *
2075_PyUnicode_FromId(_Py_Identifier *id)
2076{
2077 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002078 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2079 strlen(id->string),
2080 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002081 if (!id->object)
2082 return NULL;
2083 PyUnicode_InternInPlace(&id->object);
2084 assert(!id->next);
2085 id->next = static_strings;
2086 static_strings = id;
2087 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002088 return id->object;
2089}
2090
2091void
2092_PyUnicode_ClearStaticStrings()
2093{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002094 _Py_Identifier *tmp, *s = static_strings;
2095 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002096 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002097 tmp = s->next;
2098 s->next = NULL;
2099 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002100 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002101 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002102}
2103
Benjamin Peterson0df54292012-03-26 14:50:32 -04002104/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002105
Victor Stinnerd3f08822012-05-29 12:57:52 +02002106PyObject*
2107_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002108{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002109 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002110 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002111 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002112#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002113 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002114#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002115 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002116 }
Victor Stinner785938e2011-12-11 20:09:03 +01002117 unicode = PyUnicode_New(size, 127);
2118 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002119 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002120 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2121 assert(_PyUnicode_CheckConsistency(unicode, 1));
2122 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002123}
2124
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002125static Py_UCS4
2126kind_maxchar_limit(unsigned int kind)
2127{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002128 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002129 case PyUnicode_1BYTE_KIND:
2130 return 0x80;
2131 case PyUnicode_2BYTE_KIND:
2132 return 0x100;
2133 case PyUnicode_4BYTE_KIND:
2134 return 0x10000;
2135 default:
2136 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002137 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002138 }
2139}
2140
Victor Stinnere6abb482012-05-02 01:15:40 +02002141Py_LOCAL_INLINE(Py_UCS4)
2142align_maxchar(Py_UCS4 maxchar)
2143{
2144 if (maxchar <= 127)
2145 return 127;
2146 else if (maxchar <= 255)
2147 return 255;
2148 else if (maxchar <= 65535)
2149 return 65535;
2150 else
2151 return MAX_UNICODE;
2152}
2153
Victor Stinner702c7342011-10-05 13:50:52 +02002154static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002155_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002156{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002157 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002158 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002159
Serhiy Storchaka678db842013-01-26 12:16:36 +02002160 if (size == 0)
2161 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002162 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002163 if (size == 1)
2164 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002165
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002166 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002167 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002168 if (!res)
2169 return NULL;
2170 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002171 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002172 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002173}
2174
Victor Stinnere57b1c02011-09-28 22:20:48 +02002175static PyObject*
2176_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177{
2178 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002179 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002180
Serhiy Storchaka678db842013-01-26 12:16:36 +02002181 if (size == 0)
2182 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002183 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002184 if (size == 1)
2185 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002186
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002187 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002188 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002189 if (!res)
2190 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002191 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002192 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002193 else {
2194 _PyUnicode_CONVERT_BYTES(
2195 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2196 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002197 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198 return res;
2199}
2200
Victor Stinnere57b1c02011-09-28 22:20:48 +02002201static PyObject*
2202_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002203{
2204 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002205 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002206
Serhiy Storchaka678db842013-01-26 12:16:36 +02002207 if (size == 0)
2208 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002209 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002210 if (size == 1)
2211 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002212
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002213 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002214 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002215 if (!res)
2216 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002217 if (max_char < 256)
2218 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2219 PyUnicode_1BYTE_DATA(res));
2220 else if (max_char < 0x10000)
2221 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2222 PyUnicode_2BYTE_DATA(res));
2223 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002224 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002225 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002226 return res;
2227}
2228
2229PyObject*
2230PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2231{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002232 if (size < 0) {
2233 PyErr_SetString(PyExc_ValueError, "size must be positive");
2234 return NULL;
2235 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002236 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002237 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002238 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002239 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002240 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002241 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002242 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002243 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002244 PyErr_SetString(PyExc_SystemError, "invalid kind");
2245 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247}
2248
Victor Stinnerece58de2012-04-23 23:36:38 +02002249Py_UCS4
2250_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2251{
2252 enum PyUnicode_Kind kind;
2253 void *startptr, *endptr;
2254
2255 assert(PyUnicode_IS_READY(unicode));
2256 assert(0 <= start);
2257 assert(end <= PyUnicode_GET_LENGTH(unicode));
2258 assert(start <= end);
2259
2260 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2261 return PyUnicode_MAX_CHAR_VALUE(unicode);
2262
2263 if (start == end)
2264 return 127;
2265
Victor Stinner94d558b2012-04-27 22:26:58 +02002266 if (PyUnicode_IS_ASCII(unicode))
2267 return 127;
2268
Victor Stinnerece58de2012-04-23 23:36:38 +02002269 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002270 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002271 endptr = (char *)startptr + end * kind;
2272 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002273 switch(kind) {
2274 case PyUnicode_1BYTE_KIND:
2275 return ucs1lib_find_max_char(startptr, endptr);
2276 case PyUnicode_2BYTE_KIND:
2277 return ucs2lib_find_max_char(startptr, endptr);
2278 case PyUnicode_4BYTE_KIND:
2279 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002280 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002281 assert(0);
2282 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002283 }
2284}
2285
Victor Stinner25a4b292011-10-06 12:31:55 +02002286/* Ensure that a string uses the most efficient storage, if it is not the
2287 case: create a new string with of the right kind. Write NULL into *p_unicode
2288 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002289static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002290unicode_adjust_maxchar(PyObject **p_unicode)
2291{
2292 PyObject *unicode, *copy;
2293 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002294 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002295 unsigned int kind;
2296
2297 assert(p_unicode != NULL);
2298 unicode = *p_unicode;
2299 assert(PyUnicode_IS_READY(unicode));
2300 if (PyUnicode_IS_ASCII(unicode))
2301 return;
2302
2303 len = PyUnicode_GET_LENGTH(unicode);
2304 kind = PyUnicode_KIND(unicode);
2305 if (kind == PyUnicode_1BYTE_KIND) {
2306 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002307 max_char = ucs1lib_find_max_char(u, u + len);
2308 if (max_char >= 128)
2309 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002310 }
2311 else if (kind == PyUnicode_2BYTE_KIND) {
2312 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002313 max_char = ucs2lib_find_max_char(u, u + len);
2314 if (max_char >= 256)
2315 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002316 }
2317 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002318 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002319 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002320 max_char = ucs4lib_find_max_char(u, u + len);
2321 if (max_char >= 0x10000)
2322 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002323 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002324 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002325 if (copy != NULL)
2326 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002327 Py_DECREF(unicode);
2328 *p_unicode = copy;
2329}
2330
Victor Stinner034f6cf2011-09-30 02:26:44 +02002331PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002332_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002333{
Victor Stinner87af4f22011-11-21 23:03:47 +01002334 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002335 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002336
Victor Stinner034f6cf2011-09-30 02:26:44 +02002337 if (!PyUnicode_Check(unicode)) {
2338 PyErr_BadInternalCall();
2339 return NULL;
2340 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002341 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002342 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002343
Victor Stinner87af4f22011-11-21 23:03:47 +01002344 length = PyUnicode_GET_LENGTH(unicode);
2345 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002346 if (!copy)
2347 return NULL;
2348 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2349
Victor Stinner87af4f22011-11-21 23:03:47 +01002350 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2351 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002352 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002353 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002354}
2355
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002356
Victor Stinnerbc603d12011-10-02 01:00:40 +02002357/* Widen Unicode objects to larger buffers. Don't write terminating null
2358 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002359
2360void*
2361_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2362{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002363 Py_ssize_t len;
2364 void *result;
2365 unsigned int skind;
2366
Benjamin Petersonbac79492012-01-14 13:34:47 -05002367 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002368 return NULL;
2369
2370 len = PyUnicode_GET_LENGTH(s);
2371 skind = PyUnicode_KIND(s);
2372 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002373 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002374 return NULL;
2375 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002376 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002377 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002378 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002379 if (!result)
2380 return PyErr_NoMemory();
2381 assert(skind == PyUnicode_1BYTE_KIND);
2382 _PyUnicode_CONVERT_BYTES(
2383 Py_UCS1, Py_UCS2,
2384 PyUnicode_1BYTE_DATA(s),
2385 PyUnicode_1BYTE_DATA(s) + len,
2386 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002387 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002388 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002389 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002390 if (!result)
2391 return PyErr_NoMemory();
2392 if (skind == PyUnicode_2BYTE_KIND) {
2393 _PyUnicode_CONVERT_BYTES(
2394 Py_UCS2, Py_UCS4,
2395 PyUnicode_2BYTE_DATA(s),
2396 PyUnicode_2BYTE_DATA(s) + len,
2397 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002398 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002399 else {
2400 assert(skind == PyUnicode_1BYTE_KIND);
2401 _PyUnicode_CONVERT_BYTES(
2402 Py_UCS1, Py_UCS4,
2403 PyUnicode_1BYTE_DATA(s),
2404 PyUnicode_1BYTE_DATA(s) + len,
2405 result);
2406 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002407 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002408 default:
2409 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002410 }
Victor Stinner01698042011-10-04 00:04:26 +02002411 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 return NULL;
2413}
2414
2415static Py_UCS4*
2416as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2417 int copy_null)
2418{
2419 int kind;
2420 void *data;
2421 Py_ssize_t len, targetlen;
2422 if (PyUnicode_READY(string) == -1)
2423 return NULL;
2424 kind = PyUnicode_KIND(string);
2425 data = PyUnicode_DATA(string);
2426 len = PyUnicode_GET_LENGTH(string);
2427 targetlen = len;
2428 if (copy_null)
2429 targetlen++;
2430 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002431 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002432 if (!target) {
2433 PyErr_NoMemory();
2434 return NULL;
2435 }
2436 }
2437 else {
2438 if (targetsize < targetlen) {
2439 PyErr_Format(PyExc_SystemError,
2440 "string is longer than the buffer");
2441 if (copy_null && 0 < targetsize)
2442 target[0] = 0;
2443 return NULL;
2444 }
2445 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002446 if (kind == PyUnicode_1BYTE_KIND) {
2447 Py_UCS1 *start = (Py_UCS1 *) data;
2448 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002449 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002450 else if (kind == PyUnicode_2BYTE_KIND) {
2451 Py_UCS2 *start = (Py_UCS2 *) data;
2452 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2453 }
2454 else {
2455 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002456 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002457 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002458 if (copy_null)
2459 target[len] = 0;
2460 return target;
2461}
2462
2463Py_UCS4*
2464PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2465 int copy_null)
2466{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002467 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002468 PyErr_BadInternalCall();
2469 return NULL;
2470 }
2471 return as_ucs4(string, target, targetsize, copy_null);
2472}
2473
2474Py_UCS4*
2475PyUnicode_AsUCS4Copy(PyObject *string)
2476{
2477 return as_ucs4(string, NULL, 0, 1);
2478}
2479
2480#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002481
Alexander Belopolsky40018472011-02-26 01:02:56 +00002482PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002483PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002484{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002485 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002486 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002487 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002488 PyErr_BadInternalCall();
2489 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002490 }
2491
Martin v. Löwis790465f2008-04-05 20:41:37 +00002492 if (size == -1) {
2493 size = wcslen(w);
2494 }
2495
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002496 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002497}
2498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002499#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002500
Victor Stinner15a11362012-10-06 23:48:20 +02002501/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002502 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2503 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2504#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002505
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002506static int
2507unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2508 Py_ssize_t width, Py_ssize_t precision)
2509{
2510 Py_ssize_t length, fill, arglen;
2511 Py_UCS4 maxchar;
2512
2513 if (PyUnicode_READY(str) == -1)
2514 return -1;
2515
2516 length = PyUnicode_GET_LENGTH(str);
2517 if ((precision == -1 || precision >= length)
2518 && width <= length)
2519 return _PyUnicodeWriter_WriteStr(writer, str);
2520
2521 if (precision != -1)
2522 length = Py_MIN(precision, length);
2523
2524 arglen = Py_MAX(length, width);
2525 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2526 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2527 else
2528 maxchar = writer->maxchar;
2529
2530 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2531 return -1;
2532
2533 if (width > length) {
2534 fill = width - length;
2535 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2536 return -1;
2537 writer->pos += fill;
2538 }
2539
2540 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2541 str, 0, length);
2542 writer->pos += length;
2543 return 0;
2544}
2545
2546static int
2547unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2548 Py_ssize_t width, Py_ssize_t precision)
2549{
2550 /* UTF-8 */
2551 Py_ssize_t length;
2552 PyObject *unicode;
2553 int res;
2554
2555 length = strlen(str);
2556 if (precision != -1)
2557 length = Py_MIN(length, precision);
2558 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2559 if (unicode == NULL)
2560 return -1;
2561
2562 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2563 Py_DECREF(unicode);
2564 return res;
2565}
2566
Victor Stinner96865452011-03-01 23:44:09 +00002567static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002568unicode_fromformat_arg(_PyUnicodeWriter *writer,
2569 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002570{
Victor Stinnere215d962012-10-06 23:03:36 +02002571 const char *p;
2572 Py_ssize_t len;
2573 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002574 Py_ssize_t width;
2575 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002576 int longflag;
2577 int longlongflag;
2578 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002579 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002580
2581 p = f;
2582 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002583 zeropad = 0;
2584 if (*f == '0') {
2585 zeropad = 1;
2586 f++;
2587 }
Victor Stinner96865452011-03-01 23:44:09 +00002588
2589 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002590 width = -1;
2591 if (Py_ISDIGIT((unsigned)*f)) {
2592 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002593 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002594 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002596 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002597 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002598 return NULL;
2599 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002600 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002601 f++;
2602 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002603 }
2604 precision = -1;
2605 if (*f == '.') {
2606 f++;
2607 if (Py_ISDIGIT((unsigned)*f)) {
2608 precision = (*f - '0');
2609 f++;
2610 while (Py_ISDIGIT((unsigned)*f)) {
2611 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2612 PyErr_SetString(PyExc_ValueError,
2613 "precision too big");
2614 return NULL;
2615 }
2616 precision = (precision * 10) + (*f - '0');
2617 f++;
2618 }
2619 }
Victor Stinner96865452011-03-01 23:44:09 +00002620 if (*f == '%') {
2621 /* "%.3%s" => f points to "3" */
2622 f--;
2623 }
2624 }
2625 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002626 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002627 f--;
2628 }
Victor Stinner96865452011-03-01 23:44:09 +00002629
2630 /* Handle %ld, %lu, %lld and %llu. */
2631 longflag = 0;
2632 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002633 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002634 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002635 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002636 longflag = 1;
2637 ++f;
2638 }
Victor Stinner96865452011-03-01 23:44:09 +00002639 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002640 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002641 longlongflag = 1;
2642 f += 2;
2643 }
Victor Stinner96865452011-03-01 23:44:09 +00002644 }
2645 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002646 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002647 size_tflag = 1;
2648 ++f;
2649 }
Victor Stinnere215d962012-10-06 23:03:36 +02002650
2651 if (f[1] == '\0')
2652 writer->overallocate = 0;
2653
2654 switch (*f) {
2655 case 'c':
2656 {
2657 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002658 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002659 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002660 "character argument not in range(0x110000)");
2661 return NULL;
2662 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002663 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002664 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002665 break;
2666 }
2667
2668 case 'i':
2669 case 'd':
2670 case 'u':
2671 case 'x':
2672 {
2673 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002674 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002675 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002676
2677 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002678 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002679 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002680 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002681 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002682 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002683 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002684 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002685 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002686 va_arg(*vargs, size_t));
2687 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002688 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002689 va_arg(*vargs, unsigned int));
2690 }
2691 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002692 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002693 }
2694 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002695 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002696 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002697 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002698 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002699 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002700 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002701 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002702 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002703 va_arg(*vargs, Py_ssize_t));
2704 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002705 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002706 va_arg(*vargs, int));
2707 }
2708 assert(len >= 0);
2709
Victor Stinnere215d962012-10-06 23:03:36 +02002710 if (precision < len)
2711 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002712
2713 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002714 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2715 return NULL;
2716
Victor Stinnere215d962012-10-06 23:03:36 +02002717 if (width > precision) {
2718 Py_UCS4 fillchar;
2719 fill = width - precision;
2720 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002721 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2722 return NULL;
2723 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002724 }
Victor Stinner15a11362012-10-06 23:48:20 +02002725 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002726 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002727 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2728 return NULL;
2729 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002730 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002731
Victor Stinner4a587072013-11-19 12:54:53 +01002732 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2733 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002734 break;
2735 }
2736
2737 case 'p':
2738 {
2739 char number[MAX_LONG_LONG_CHARS];
2740
2741 len = sprintf(number, "%p", va_arg(*vargs, void*));
2742 assert(len >= 0);
2743
2744 /* %p is ill-defined: ensure leading 0x. */
2745 if (number[1] == 'X')
2746 number[1] = 'x';
2747 else if (number[1] != 'x') {
2748 memmove(number + 2, number,
2749 strlen(number) + 1);
2750 number[0] = '0';
2751 number[1] = 'x';
2752 len += 2;
2753 }
2754
Victor Stinner4a587072013-11-19 12:54:53 +01002755 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002756 return NULL;
2757 break;
2758 }
2759
2760 case 's':
2761 {
2762 /* UTF-8 */
2763 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002764 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002765 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002766 break;
2767 }
2768
2769 case 'U':
2770 {
2771 PyObject *obj = va_arg(*vargs, PyObject *);
2772 assert(obj && _PyUnicode_CHECK(obj));
2773
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002774 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002775 return NULL;
2776 break;
2777 }
2778
2779 case 'V':
2780 {
2781 PyObject *obj = va_arg(*vargs, PyObject *);
2782 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002783 if (obj) {
2784 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002785 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002786 return NULL;
2787 }
2788 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002789 assert(str != NULL);
2790 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002791 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002792 }
2793 break;
2794 }
2795
2796 case 'S':
2797 {
2798 PyObject *obj = va_arg(*vargs, PyObject *);
2799 PyObject *str;
2800 assert(obj);
2801 str = PyObject_Str(obj);
2802 if (!str)
2803 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002804 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002805 Py_DECREF(str);
2806 return NULL;
2807 }
2808 Py_DECREF(str);
2809 break;
2810 }
2811
2812 case 'R':
2813 {
2814 PyObject *obj = va_arg(*vargs, PyObject *);
2815 PyObject *repr;
2816 assert(obj);
2817 repr = PyObject_Repr(obj);
2818 if (!repr)
2819 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002820 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002821 Py_DECREF(repr);
2822 return NULL;
2823 }
2824 Py_DECREF(repr);
2825 break;
2826 }
2827
2828 case 'A':
2829 {
2830 PyObject *obj = va_arg(*vargs, PyObject *);
2831 PyObject *ascii;
2832 assert(obj);
2833 ascii = PyObject_ASCII(obj);
2834 if (!ascii)
2835 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002836 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002837 Py_DECREF(ascii);
2838 return NULL;
2839 }
2840 Py_DECREF(ascii);
2841 break;
2842 }
2843
2844 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002845 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002846 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002847 break;
2848
2849 default:
2850 /* if we stumble upon an unknown formatting code, copy the rest
2851 of the format string to the output string. (we cannot just
2852 skip the code, since there's no way to know what's in the
2853 argument list) */
2854 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002855 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002856 return NULL;
2857 f = p+len;
2858 return f;
2859 }
2860
2861 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002862 return f;
2863}
2864
Walter Dörwaldd2034312007-05-18 16:29:38 +00002865PyObject *
2866PyUnicode_FromFormatV(const char *format, va_list vargs)
2867{
Victor Stinnere215d962012-10-06 23:03:36 +02002868 va_list vargs2;
2869 const char *f;
2870 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002871
Victor Stinner8f674cc2013-04-17 23:02:17 +02002872 _PyUnicodeWriter_Init(&writer);
2873 writer.min_length = strlen(format) + 100;
2874 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002875
2876 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2877 Copy it to be able to pass a reference to a subfunction. */
2878 Py_VA_COPY(vargs2, vargs);
2879
2880 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002881 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002882 f = unicode_fromformat_arg(&writer, f, &vargs2);
2883 if (f == NULL)
2884 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002886 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002887 const char *p;
2888 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002889
Victor Stinnere215d962012-10-06 23:03:36 +02002890 p = f;
2891 do
2892 {
2893 if ((unsigned char)*p > 127) {
2894 PyErr_Format(PyExc_ValueError,
2895 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2896 "string, got a non-ASCII byte: 0x%02x",
2897 (unsigned char)*p);
2898 return NULL;
2899 }
2900 p++;
2901 }
2902 while (*p != '\0' && *p != '%');
2903 len = p - f;
2904
2905 if (*p == '\0')
2906 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002907
2908 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002909 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002910
2911 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002912 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002913 }
Victor Stinnere215d962012-10-06 23:03:36 +02002914 return _PyUnicodeWriter_Finish(&writer);
2915
2916 fail:
2917 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002918 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002919}
2920
Walter Dörwaldd2034312007-05-18 16:29:38 +00002921PyObject *
2922PyUnicode_FromFormat(const char *format, ...)
2923{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002924 PyObject* ret;
2925 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002926
2927#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002928 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002929#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002930 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002931#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002932 ret = PyUnicode_FromFormatV(format, vargs);
2933 va_end(vargs);
2934 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002935}
2936
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002937#ifdef HAVE_WCHAR_H
2938
Victor Stinner5593d8a2010-10-02 11:11:27 +00002939/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2940 convert a Unicode object to a wide character string.
2941
Victor Stinnerd88d9832011-09-06 02:00:05 +02002942 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002943 character) required to convert the unicode object. Ignore size argument.
2944
Victor Stinnerd88d9832011-09-06 02:00:05 +02002945 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002946 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002947 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002948static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002949unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002950 wchar_t *w,
2951 Py_ssize_t size)
2952{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002953 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002954 const wchar_t *wstr;
2955
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002956 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002957 if (wstr == NULL)
2958 return -1;
2959
Victor Stinner5593d8a2010-10-02 11:11:27 +00002960 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002961 if (size > res)
2962 size = res + 1;
2963 else
2964 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002965 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002966 return res;
2967 }
2968 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002969 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002970}
2971
2972Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002973PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002974 wchar_t *w,
2975 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002976{
2977 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002978 PyErr_BadInternalCall();
2979 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002980 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002981 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002982}
2983
Victor Stinner137c34c2010-09-29 10:25:54 +00002984wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002985PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002986 Py_ssize_t *size)
2987{
2988 wchar_t* buffer;
2989 Py_ssize_t buflen;
2990
2991 if (unicode == NULL) {
2992 PyErr_BadInternalCall();
2993 return NULL;
2994 }
2995
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002996 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002997 if (buflen == -1)
2998 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002999 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00003000 if (buffer == NULL) {
3001 PyErr_NoMemory();
3002 return NULL;
3003 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003004 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02003005 if (buflen == -1) {
3006 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003007 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02003008 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00003009 if (size != NULL)
3010 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003011 return buffer;
3012}
3013
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003014#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003015
Alexander Belopolsky40018472011-02-26 01:02:56 +00003016PyObject *
3017PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003018{
Victor Stinner8faf8212011-12-08 22:14:11 +01003019 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003020 PyErr_SetString(PyExc_ValueError,
3021 "chr() arg not in range(0x110000)");
3022 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003023 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003024
Victor Stinner985a82a2014-01-03 12:53:47 +01003025 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003026}
3027
Alexander Belopolsky40018472011-02-26 01:02:56 +00003028PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003029PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003030{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003031 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003032 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003033 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003034 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003035 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003036 Py_INCREF(obj);
3037 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003038 }
3039 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003040 /* For a Unicode subtype that's not a Unicode object,
3041 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003042 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003043 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003044 PyErr_Format(PyExc_TypeError,
3045 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003046 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003047 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003048}
3049
Alexander Belopolsky40018472011-02-26 01:02:56 +00003050PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003051PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003052 const char *encoding,
3053 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003054{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003055 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003056 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003057
Guido van Rossumd57fd912000-03-10 22:53:23 +00003058 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003059 PyErr_BadInternalCall();
3060 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003061 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003062
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003063 /* Decoding bytes objects is the most common case and should be fast */
3064 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003065 if (PyBytes_GET_SIZE(obj) == 0)
3066 _Py_RETURN_UNICODE_EMPTY();
3067 v = PyUnicode_Decode(
3068 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3069 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003070 return v;
3071 }
3072
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003073 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003074 PyErr_SetString(PyExc_TypeError,
3075 "decoding str is not supported");
3076 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003077 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003078
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003079 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3080 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3081 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003082 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003083 Py_TYPE(obj)->tp_name);
3084 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003085 }
Tim Petersced69f82003-09-16 20:30:58 +00003086
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003087 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003088 PyBuffer_Release(&buffer);
3089 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003090 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003091
Serhiy Storchaka05997252013-01-26 12:14:02 +02003092 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003093 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003094 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003095}
3096
Victor Stinner942889a2016-09-05 15:40:10 -07003097/* Normalize an encoding name: C implementation of
3098 encodings.normalize_encoding(). Return 1 on success, or 0 on error (encoding
3099 is longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003100int
3101_Py_normalize_encoding(const char *encoding,
3102 char *lower,
3103 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003104{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003105 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003106 char *l;
3107 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003108 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003109
Victor Stinner942889a2016-09-05 15:40:10 -07003110 assert(encoding != NULL);
3111
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003112 e = encoding;
3113 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003114 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003115 punct = 0;
3116 while (1) {
3117 char c = *e;
3118 if (c == 0) {
3119 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003120 }
Victor Stinner942889a2016-09-05 15:40:10 -07003121
3122 if (Py_ISALNUM(c) || c == '.') {
3123 if (punct && l != lower) {
3124 if (l == l_end) {
3125 return 0;
3126 }
3127 *l++ = '_';
3128 }
3129 punct = 0;
3130
3131 if (l == l_end) {
3132 return 0;
3133 }
3134 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003135 }
3136 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003137 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003138 }
Victor Stinner942889a2016-09-05 15:40:10 -07003139
3140 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003141 }
3142 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003143 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003144}
3145
Alexander Belopolsky40018472011-02-26 01:02:56 +00003146PyObject *
3147PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003148 Py_ssize_t size,
3149 const char *encoding,
3150 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003151{
3152 PyObject *buffer = NULL, *unicode;
3153 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003154 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3155
3156 if (encoding == NULL) {
3157 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3158 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003159
Fred Drakee4315f52000-05-09 19:53:39 +00003160 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003161 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3162 char *lower = buflower;
3163
3164 /* Fast paths */
3165 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3166 lower += 3;
3167 if (*lower == '_') {
3168 /* Match "utf8" and "utf_8" */
3169 lower++;
3170 }
3171
3172 if (lower[0] == '8' && lower[1] == 0) {
3173 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3174 }
3175 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3176 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3177 }
3178 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3179 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3180 }
3181 }
3182 else {
3183 if (strcmp(lower, "ascii") == 0
3184 || strcmp(lower, "us_ascii") == 0) {
3185 return PyUnicode_DecodeASCII(s, size, errors);
3186 }
3187 #ifdef HAVE_MBCS
3188 else if (strcmp(lower, "mbcs") == 0) {
3189 return PyUnicode_DecodeMBCS(s, size, errors);
3190 }
3191 #endif
3192 else if (strcmp(lower, "latin1") == 0
3193 || strcmp(lower, "latin_1") == 0
3194 || strcmp(lower, "iso_8859_1") == 0
3195 || strcmp(lower, "iso8859_1") == 0) {
3196 return PyUnicode_DecodeLatin1(s, size, errors);
3197 }
3198 }
Victor Stinner37296e82010-06-10 13:36:23 +00003199 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003200
3201 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003202 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003203 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003204 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003205 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003206 if (buffer == NULL)
3207 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003208 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003209 if (unicode == NULL)
3210 goto onError;
3211 if (!PyUnicode_Check(unicode)) {
3212 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003213 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3214 "use codecs.decode() to decode to arbitrary types",
3215 encoding,
3216 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003217 Py_DECREF(unicode);
3218 goto onError;
3219 }
3220 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003221 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003222
Benjamin Peterson29060642009-01-31 22:14:21 +00003223 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003224 Py_XDECREF(buffer);
3225 return NULL;
3226}
3227
Alexander Belopolsky40018472011-02-26 01:02:56 +00003228PyObject *
3229PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003230 const char *encoding,
3231 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003232{
3233 PyObject *v;
3234
3235 if (!PyUnicode_Check(unicode)) {
3236 PyErr_BadArgument();
3237 goto onError;
3238 }
3239
3240 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003241 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003242
3243 /* Decode via the codec registry */
3244 v = PyCodec_Decode(unicode, encoding, errors);
3245 if (v == NULL)
3246 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003247 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003248
Benjamin Peterson29060642009-01-31 22:14:21 +00003249 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003250 return NULL;
3251}
3252
Alexander Belopolsky40018472011-02-26 01:02:56 +00003253PyObject *
3254PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003255 const char *encoding,
3256 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003257{
3258 PyObject *v;
3259
3260 if (!PyUnicode_Check(unicode)) {
3261 PyErr_BadArgument();
3262 goto onError;
3263 }
3264
3265 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003266 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003267
3268 /* Decode via the codec registry */
3269 v = PyCodec_Decode(unicode, encoding, errors);
3270 if (v == NULL)
3271 goto onError;
3272 if (!PyUnicode_Check(v)) {
3273 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003274 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3275 "use codecs.decode() to decode to arbitrary types",
3276 encoding,
3277 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003278 Py_DECREF(v);
3279 goto onError;
3280 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003281 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003282
Benjamin Peterson29060642009-01-31 22:14:21 +00003283 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003284 return NULL;
3285}
3286
Alexander Belopolsky40018472011-02-26 01:02:56 +00003287PyObject *
3288PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003289 Py_ssize_t size,
3290 const char *encoding,
3291 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292{
3293 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003294
Guido van Rossumd57fd912000-03-10 22:53:23 +00003295 unicode = PyUnicode_FromUnicode(s, size);
3296 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003297 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003298 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3299 Py_DECREF(unicode);
3300 return v;
3301}
3302
Alexander Belopolsky40018472011-02-26 01:02:56 +00003303PyObject *
3304PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003305 const char *encoding,
3306 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003307{
3308 PyObject *v;
3309
3310 if (!PyUnicode_Check(unicode)) {
3311 PyErr_BadArgument();
3312 goto onError;
3313 }
3314
3315 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003316 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003317
3318 /* Encode via the codec registry */
3319 v = PyCodec_Encode(unicode, encoding, errors);
3320 if (v == NULL)
3321 goto onError;
3322 return v;
3323
Benjamin Peterson29060642009-01-31 22:14:21 +00003324 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003325 return NULL;
3326}
3327
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003328static size_t
3329wcstombs_errorpos(const wchar_t *wstr)
3330{
3331 size_t len;
3332#if SIZEOF_WCHAR_T == 2
3333 wchar_t buf[3];
3334#else
3335 wchar_t buf[2];
3336#endif
3337 char outbuf[MB_LEN_MAX];
3338 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003339
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003340#if SIZEOF_WCHAR_T == 2
3341 buf[2] = 0;
3342#else
3343 buf[1] = 0;
3344#endif
3345 start = wstr;
3346 while (*wstr != L'\0')
3347 {
3348 previous = wstr;
3349#if SIZEOF_WCHAR_T == 2
3350 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3351 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3352 {
3353 buf[0] = wstr[0];
3354 buf[1] = wstr[1];
3355 wstr += 2;
3356 }
3357 else {
3358 buf[0] = *wstr;
3359 buf[1] = 0;
3360 wstr++;
3361 }
3362#else
3363 buf[0] = *wstr;
3364 wstr++;
3365#endif
3366 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003367 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003368 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003369 }
3370
3371 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003372 return 0;
3373}
3374
Victor Stinner1b579672011-12-17 05:47:23 +01003375static int
3376locale_error_handler(const char *errors, int *surrogateescape)
3377{
Victor Stinner50149202015-09-22 00:26:54 +02003378 _Py_error_handler error_handler = get_error_handler(errors);
3379 switch (error_handler)
3380 {
3381 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003382 *surrogateescape = 0;
3383 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003384 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003385 *surrogateescape = 1;
3386 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003387 default:
3388 PyErr_Format(PyExc_ValueError,
3389 "only 'strict' and 'surrogateescape' error handlers "
3390 "are supported, not '%s'",
3391 errors);
3392 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003393 }
Victor Stinner1b579672011-12-17 05:47:23 +01003394}
3395
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003396PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003397PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398{
3399 Py_ssize_t wlen, wlen2;
3400 wchar_t *wstr;
3401 PyObject *bytes = NULL;
3402 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003403 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003404 PyObject *exc;
3405 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003406 int surrogateescape;
3407
3408 if (locale_error_handler(errors, &surrogateescape) < 0)
3409 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003410
3411 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3412 if (wstr == NULL)
3413 return NULL;
3414
3415 wlen2 = wcslen(wstr);
3416 if (wlen2 != wlen) {
3417 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003418 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003419 return NULL;
3420 }
3421
3422 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003423 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003424 char *str;
3425
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003426 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003427 if (str == NULL) {
3428 if (error_pos == (size_t)-1) {
3429 PyErr_NoMemory();
3430 PyMem_Free(wstr);
3431 return NULL;
3432 }
3433 else {
3434 goto encode_error;
3435 }
3436 }
3437 PyMem_Free(wstr);
3438
3439 bytes = PyBytes_FromString(str);
3440 PyMem_Free(str);
3441 }
3442 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003443 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003444 size_t len, len2;
3445
3446 len = wcstombs(NULL, wstr, 0);
3447 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003448 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003449 goto encode_error;
3450 }
3451
3452 bytes = PyBytes_FromStringAndSize(NULL, len);
3453 if (bytes == NULL) {
3454 PyMem_Free(wstr);
3455 return NULL;
3456 }
3457
3458 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3459 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003460 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003461 goto encode_error;
3462 }
3463 PyMem_Free(wstr);
3464 }
3465 return bytes;
3466
3467encode_error:
3468 errmsg = strerror(errno);
3469 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003470
3471 if (error_pos == (size_t)-1)
3472 error_pos = wcstombs_errorpos(wstr);
3473
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003474 PyMem_Free(wstr);
3475 Py_XDECREF(bytes);
3476
Victor Stinner2f197072011-12-17 07:08:30 +01003477 if (errmsg != NULL) {
3478 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003479 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003480 if (wstr != NULL) {
3481 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003482 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003483 } else
3484 errmsg = NULL;
3485 }
3486 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003487 reason = PyUnicode_FromString(
3488 "wcstombs() encountered an unencodable "
3489 "wide character");
3490 if (reason == NULL)
3491 return NULL;
3492
3493 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3494 "locale", unicode,
3495 (Py_ssize_t)error_pos,
3496 (Py_ssize_t)(error_pos+1),
3497 reason);
3498 Py_DECREF(reason);
3499 if (exc != NULL) {
3500 PyCodec_StrictErrors(exc);
3501 Py_XDECREF(exc);
3502 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003503 return NULL;
3504}
3505
Victor Stinnerad158722010-10-27 00:25:46 +00003506PyObject *
3507PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003508{
Victor Stinner99b95382011-07-04 14:23:54 +02003509#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003510 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003511#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003512 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003513#else
Victor Stinner793b5312011-04-27 00:24:21 +02003514 PyInterpreterState *interp = PyThreadState_GET()->interp;
3515 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3516 cannot use it to encode and decode filenames before it is loaded. Load
3517 the Python codec requires to encode at least its own filename. Use the C
3518 version of the locale codec until the codec registry is initialized and
3519 the Python codec is loaded.
3520
3521 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3522 cannot only rely on it: check also interp->fscodec_initialized for
3523 subinterpreters. */
3524 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003525 return PyUnicode_AsEncodedString(unicode,
3526 Py_FileSystemDefaultEncoding,
3527 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003528 }
3529 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003530 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003531 }
Victor Stinnerad158722010-10-27 00:25:46 +00003532#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003533}
3534
Alexander Belopolsky40018472011-02-26 01:02:56 +00003535PyObject *
3536PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003537 const char *encoding,
3538 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003539{
3540 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003541 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003542
Guido van Rossumd57fd912000-03-10 22:53:23 +00003543 if (!PyUnicode_Check(unicode)) {
3544 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003545 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003546 }
Fred Drakee4315f52000-05-09 19:53:39 +00003547
Victor Stinner942889a2016-09-05 15:40:10 -07003548 if (encoding == NULL) {
3549 return _PyUnicode_AsUTF8String(unicode, errors);
3550 }
3551
Fred Drakee4315f52000-05-09 19:53:39 +00003552 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003553 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3554 char *lower = buflower;
3555
3556 /* Fast paths */
3557 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3558 lower += 3;
3559 if (*lower == '_') {
3560 /* Match "utf8" and "utf_8" */
3561 lower++;
3562 }
3563
3564 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003565 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003566 }
3567 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3568 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3569 }
3570 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3571 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3572 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003573 }
Victor Stinner942889a2016-09-05 15:40:10 -07003574 else {
3575 if (strcmp(lower, "ascii") == 0
3576 || strcmp(lower, "us_ascii") == 0) {
3577 return _PyUnicode_AsASCIIString(unicode, errors);
3578 }
Victor Stinner99b95382011-07-04 14:23:54 +02003579#ifdef HAVE_MBCS
Victor Stinner942889a2016-09-05 15:40:10 -07003580 else if (strcmp(lower, "mbcs") == 0) {
3581 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3582 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003583#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003584 else if (strcmp(lower, "latin1") == 0 ||
3585 strcmp(lower, "latin_1") == 0 ||
3586 strcmp(lower, "iso_8859_1") == 0 ||
3587 strcmp(lower, "iso8859_1") == 0) {
3588 return _PyUnicode_AsLatin1String(unicode, errors);
3589 }
3590 }
Victor Stinner37296e82010-06-10 13:36:23 +00003591 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003592
3593 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003594 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003595 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003596 return NULL;
3597
3598 /* The normal path */
3599 if (PyBytes_Check(v))
3600 return v;
3601
3602 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003603 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003604 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003605 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003606
3607 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003608 "encoder %s returned bytearray instead of bytes; "
3609 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003610 encoding);
3611 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003612 Py_DECREF(v);
3613 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003614 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003615
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003616 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3617 Py_DECREF(v);
3618 return b;
3619 }
3620
3621 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003622 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3623 "use codecs.encode() to encode to arbitrary types",
3624 encoding,
3625 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003626 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003627 return NULL;
3628}
3629
Alexander Belopolsky40018472011-02-26 01:02:56 +00003630PyObject *
3631PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003632 const char *encoding,
3633 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003634{
3635 PyObject *v;
3636
3637 if (!PyUnicode_Check(unicode)) {
3638 PyErr_BadArgument();
3639 goto onError;
3640 }
3641
3642 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003643 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003644
3645 /* Encode via the codec registry */
3646 v = PyCodec_Encode(unicode, encoding, errors);
3647 if (v == NULL)
3648 goto onError;
3649 if (!PyUnicode_Check(v)) {
3650 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003651 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3652 "use codecs.encode() to encode to arbitrary types",
3653 encoding,
3654 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003655 Py_DECREF(v);
3656 goto onError;
3657 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003658 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003659
Benjamin Peterson29060642009-01-31 22:14:21 +00003660 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003661 return NULL;
3662}
3663
Victor Stinner2f197072011-12-17 07:08:30 +01003664static size_t
3665mbstowcs_errorpos(const char *str, size_t len)
3666{
3667#ifdef HAVE_MBRTOWC
3668 const char *start = str;
3669 mbstate_t mbs;
3670 size_t converted;
3671 wchar_t ch;
3672
3673 memset(&mbs, 0, sizeof mbs);
3674 while (len)
3675 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003676 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003677 if (converted == 0)
3678 /* Reached end of string */
3679 break;
3680 if (converted == (size_t)-1 || converted == (size_t)-2) {
3681 /* Conversion error or incomplete character */
3682 return str - start;
3683 }
3684 else {
3685 str += converted;
3686 len -= converted;
3687 }
3688 }
3689 /* failed to find the undecodable byte sequence */
3690 return 0;
3691#endif
3692 return 0;
3693}
3694
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003695PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003696PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003697 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003698{
3699 wchar_t smallbuf[256];
3700 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3701 wchar_t *wstr;
3702 size_t wlen, wlen2;
3703 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003704 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003705 size_t error_pos;
3706 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003707 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3708 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003709
3710 if (locale_error_handler(errors, &surrogateescape) < 0)
3711 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003712
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003713 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3714 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003715 return NULL;
3716 }
3717
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003718 if (surrogateescape) {
3719 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003720 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003721 if (wstr == NULL) {
3722 if (wlen == (size_t)-1)
3723 PyErr_NoMemory();
3724 else
3725 PyErr_SetFromErrno(PyExc_OSError);
3726 return NULL;
3727 }
3728
3729 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003730 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003731 }
3732 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003733 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003734#ifndef HAVE_BROKEN_MBSTOWCS
3735 wlen = mbstowcs(NULL, str, 0);
3736#else
3737 wlen = len;
3738#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003739 if (wlen == (size_t)-1)
3740 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003741 if (wlen+1 <= smallbuf_len) {
3742 wstr = smallbuf;
3743 }
3744 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003745 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003746 if (!wstr)
3747 return PyErr_NoMemory();
3748 }
3749
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003750 wlen2 = mbstowcs(wstr, str, wlen+1);
3751 if (wlen2 == (size_t)-1) {
3752 if (wstr != smallbuf)
3753 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003754 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003755 }
3756#ifdef HAVE_BROKEN_MBSTOWCS
3757 assert(wlen2 == wlen);
3758#endif
3759 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3760 if (wstr != smallbuf)
3761 PyMem_Free(wstr);
3762 }
3763 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003764
3765decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003766 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003767 errmsg = strerror(errno);
3768 assert(errmsg != NULL);
3769
3770 error_pos = mbstowcs_errorpos(str, len);
3771 if (errmsg != NULL) {
3772 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003773 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003774 if (wstr != NULL) {
3775 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003776 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003777 }
Victor Stinner2f197072011-12-17 07:08:30 +01003778 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003779 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003780 reason = PyUnicode_FromString(
3781 "mbstowcs() encountered an invalid multibyte sequence");
3782 if (reason == NULL)
3783 return NULL;
3784
3785 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3786 "locale", str, len,
3787 (Py_ssize_t)error_pos,
3788 (Py_ssize_t)(error_pos+1),
3789 reason);
3790 Py_DECREF(reason);
3791 if (exc != NULL) {
3792 PyCodec_StrictErrors(exc);
3793 Py_XDECREF(exc);
3794 }
3795 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003796}
3797
3798PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003799PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003800{
3801 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003802 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003803}
3804
3805
3806PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003807PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003808 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003809 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3810}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003811
Christian Heimes5894ba72007-11-04 11:43:14 +00003812PyObject*
3813PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3814{
Victor Stinner99b95382011-07-04 14:23:54 +02003815#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003816 return PyUnicode_DecodeMBCS(s, size, NULL);
3817#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003818 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003819#else
Victor Stinner793b5312011-04-27 00:24:21 +02003820 PyInterpreterState *interp = PyThreadState_GET()->interp;
3821 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3822 cannot use it to encode and decode filenames before it is loaded. Load
3823 the Python codec requires to encode at least its own filename. Use the C
3824 version of the locale codec until the codec registry is initialized and
3825 the Python codec is loaded.
3826
3827 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3828 cannot only rely on it: check also interp->fscodec_initialized for
3829 subinterpreters. */
3830 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003831 return PyUnicode_Decode(s, size,
3832 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003833 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003834 }
3835 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003836 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003837 }
Victor Stinnerad158722010-10-27 00:25:46 +00003838#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003839}
3840
Martin v. Löwis011e8422009-05-05 04:43:17 +00003841
3842int
3843PyUnicode_FSConverter(PyObject* arg, void* addr)
3844{
Brett Cannonec6ce872016-09-06 15:50:29 -07003845 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003846 PyObject *output = NULL;
3847 Py_ssize_t size;
3848 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003849 if (arg == NULL) {
3850 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003851 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003852 return 1;
3853 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003854 path = PyOS_FSPath(arg);
3855 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003856 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003857 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003858 if (PyBytes_Check(path)) {
3859 output = path;
3860 }
3861 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3862 output = PyUnicode_EncodeFSDefault(path);
3863 Py_DECREF(path);
3864 if (!output) {
3865 return 0;
3866 }
3867 assert(PyBytes_Check(output));
3868 }
3869
Victor Stinner0ea2a462010-04-30 00:22:08 +00003870 size = PyBytes_GET_SIZE(output);
3871 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003872 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003873 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003874 Py_DECREF(output);
3875 return 0;
3876 }
3877 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003878 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003879}
3880
3881
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003882int
3883PyUnicode_FSDecoder(PyObject* arg, void* addr)
3884{
3885 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003886 if (arg == NULL) {
3887 Py_DECREF(*(PyObject**)addr);
3888 return 1;
3889 }
3890 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003891 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003892 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003893 output = arg;
3894 Py_INCREF(output);
3895 }
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003896 else if (PyBytes_Check(arg) || PyObject_CheckBuffer(arg)) {
3897 if (!PyBytes_Check(arg) &&
3898 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3899 "path should be string or bytes, not %.200s",
3900 Py_TYPE(arg)->tp_name)) {
3901 return 0;
3902 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003903 arg = PyBytes_FromObject(arg);
3904 if (!arg)
3905 return 0;
3906 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3907 PyBytes_GET_SIZE(arg));
3908 Py_DECREF(arg);
3909 if (!output)
3910 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003911 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003912 else {
3913 PyErr_Format(PyExc_TypeError,
3914 "path should be string or bytes, not %.200s",
3915 Py_TYPE(arg)->tp_name);
3916 return 0;
3917 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003918 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003919 Py_DECREF(output);
3920 return 0;
3921 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003922 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003923 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003924 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003925 Py_DECREF(output);
3926 return 0;
3927 }
3928 *(PyObject**)addr = output;
3929 return Py_CLEANUP_SUPPORTED;
3930}
3931
3932
Martin v. Löwis5b222132007-06-10 09:51:05 +00003933char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003934PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003935{
Christian Heimesf3863112007-11-22 07:46:41 +00003936 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003937
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003938 if (!PyUnicode_Check(unicode)) {
3939 PyErr_BadArgument();
3940 return NULL;
3941 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003942 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003943 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003944
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003945 if (PyUnicode_UTF8(unicode) == NULL) {
3946 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003947 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003948 if (bytes == NULL)
3949 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003950 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3951 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003952 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003953 Py_DECREF(bytes);
3954 return NULL;
3955 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003956 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3957 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3958 PyBytes_AS_STRING(bytes),
3959 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003960 Py_DECREF(bytes);
3961 }
3962
3963 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003964 *psize = PyUnicode_UTF8_LENGTH(unicode);
3965 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003966}
3967
3968char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003969PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003970{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003971 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3972}
3973
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974Py_UNICODE *
3975PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3976{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003977 const unsigned char *one_byte;
3978#if SIZEOF_WCHAR_T == 4
3979 const Py_UCS2 *two_bytes;
3980#else
3981 const Py_UCS4 *four_bytes;
3982 const Py_UCS4 *ucs4_end;
3983 Py_ssize_t num_surrogates;
3984#endif
3985 wchar_t *w;
3986 wchar_t *wchar_end;
3987
3988 if (!PyUnicode_Check(unicode)) {
3989 PyErr_BadArgument();
3990 return NULL;
3991 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003992 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003993 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003994 assert(_PyUnicode_KIND(unicode) != 0);
3995 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003996
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003997 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003998#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003999 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4000 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004001 num_surrogates = 0;
4002
4003 for (; four_bytes < ucs4_end; ++four_bytes) {
4004 if (*four_bytes > 0xFFFF)
4005 ++num_surrogates;
4006 }
4007
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004008 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4009 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4010 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004011 PyErr_NoMemory();
4012 return NULL;
4013 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004014 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004015
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004016 w = _PyUnicode_WSTR(unicode);
4017 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4018 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004019 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4020 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004021 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004022 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004023 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4024 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004025 }
4026 else
4027 *w = *four_bytes;
4028
4029 if (w > wchar_end) {
4030 assert(0 && "Miscalculated string end");
4031 }
4032 }
4033 *w = 0;
4034#else
4035 /* sizeof(wchar_t) == 4 */
4036 Py_FatalError("Impossible unicode object state, wstr and str "
4037 "should share memory already.");
4038 return NULL;
4039#endif
4040 }
4041 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004042 if ((size_t)_PyUnicode_LENGTH(unicode) >
4043 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4044 PyErr_NoMemory();
4045 return NULL;
4046 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004047 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4048 (_PyUnicode_LENGTH(unicode) + 1));
4049 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004050 PyErr_NoMemory();
4051 return NULL;
4052 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004053 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4054 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4055 w = _PyUnicode_WSTR(unicode);
4056 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004057
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004058 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4059 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004060 for (; w < wchar_end; ++one_byte, ++w)
4061 *w = *one_byte;
4062 /* null-terminate the wstr */
4063 *w = 0;
4064 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004065 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004066#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004067 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004068 for (; w < wchar_end; ++two_bytes, ++w)
4069 *w = *two_bytes;
4070 /* null-terminate the wstr */
4071 *w = 0;
4072#else
4073 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004074 PyObject_FREE(_PyUnicode_WSTR(unicode));
4075 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004076 Py_FatalError("Impossible unicode object state, wstr "
4077 "and str should share memory already.");
4078 return NULL;
4079#endif
4080 }
4081 else {
4082 assert(0 && "This should never happen.");
4083 }
4084 }
4085 }
4086 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004087 *size = PyUnicode_WSTR_LENGTH(unicode);
4088 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004089}
4090
Alexander Belopolsky40018472011-02-26 01:02:56 +00004091Py_UNICODE *
4092PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004093{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004094 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004095}
4096
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004097
Alexander Belopolsky40018472011-02-26 01:02:56 +00004098Py_ssize_t
4099PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004100{
4101 if (!PyUnicode_Check(unicode)) {
4102 PyErr_BadArgument();
4103 goto onError;
4104 }
4105 return PyUnicode_GET_SIZE(unicode);
4106
Benjamin Peterson29060642009-01-31 22:14:21 +00004107 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004108 return -1;
4109}
4110
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004111Py_ssize_t
4112PyUnicode_GetLength(PyObject *unicode)
4113{
Victor Stinner07621332012-06-16 04:53:46 +02004114 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004115 PyErr_BadArgument();
4116 return -1;
4117 }
Victor Stinner07621332012-06-16 04:53:46 +02004118 if (PyUnicode_READY(unicode) == -1)
4119 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004120 return PyUnicode_GET_LENGTH(unicode);
4121}
4122
4123Py_UCS4
4124PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4125{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004126 void *data;
4127 int kind;
4128
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004129 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4130 PyErr_BadArgument();
4131 return (Py_UCS4)-1;
4132 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004133 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004134 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004135 return (Py_UCS4)-1;
4136 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004137 data = PyUnicode_DATA(unicode);
4138 kind = PyUnicode_KIND(unicode);
4139 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004140}
4141
4142int
4143PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4144{
4145 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004146 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004147 return -1;
4148 }
Victor Stinner488fa492011-12-12 00:01:39 +01004149 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004150 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004151 PyErr_SetString(PyExc_IndexError, "string index out of range");
4152 return -1;
4153 }
Victor Stinner488fa492011-12-12 00:01:39 +01004154 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004155 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004156 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4157 PyErr_SetString(PyExc_ValueError, "character out of range");
4158 return -1;
4159 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004160 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4161 index, ch);
4162 return 0;
4163}
4164
Alexander Belopolsky40018472011-02-26 01:02:56 +00004165const char *
4166PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004167{
Victor Stinner42cb4622010-09-01 19:39:01 +00004168 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004169}
4170
Victor Stinner554f3f02010-06-16 23:33:54 +00004171/* create or adjust a UnicodeDecodeError */
4172static void
4173make_decode_exception(PyObject **exceptionObject,
4174 const char *encoding,
4175 const char *input, Py_ssize_t length,
4176 Py_ssize_t startpos, Py_ssize_t endpos,
4177 const char *reason)
4178{
4179 if (*exceptionObject == NULL) {
4180 *exceptionObject = PyUnicodeDecodeError_Create(
4181 encoding, input, length, startpos, endpos, reason);
4182 }
4183 else {
4184 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4185 goto onError;
4186 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4187 goto onError;
4188 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4189 goto onError;
4190 }
4191 return;
4192
4193onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004194 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004195}
4196
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004197#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004198/* error handling callback helper:
4199 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004200 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004201 and adjust various state variables.
4202 return 0 on success, -1 on error
4203*/
4204
Alexander Belopolsky40018472011-02-26 01:02:56 +00004205static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004206unicode_decode_call_errorhandler_wchar(
4207 const char *errors, PyObject **errorHandler,
4208 const char *encoding, const char *reason,
4209 const char **input, const char **inend, Py_ssize_t *startinpos,
4210 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4211 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004212{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004213 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004214
4215 PyObject *restuple = NULL;
4216 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004217 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004218 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004219 Py_ssize_t requiredsize;
4220 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004221 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004222 wchar_t *repwstr;
4223 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004224
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004225 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4226 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004227
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004228 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004229 *errorHandler = PyCodec_LookupError(errors);
4230 if (*errorHandler == NULL)
4231 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004232 }
4233
Victor Stinner554f3f02010-06-16 23:33:54 +00004234 make_decode_exception(exceptionObject,
4235 encoding,
4236 *input, *inend - *input,
4237 *startinpos, *endinpos,
4238 reason);
4239 if (*exceptionObject == NULL)
4240 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004241
4242 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4243 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004244 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004245 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004246 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004247 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004248 }
4249 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004250 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004251
4252 /* Copy back the bytes variables, which might have been modified by the
4253 callback */
4254 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4255 if (!inputobj)
4256 goto onError;
4257 if (!PyBytes_Check(inputobj)) {
4258 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4259 }
4260 *input = PyBytes_AS_STRING(inputobj);
4261 insize = PyBytes_GET_SIZE(inputobj);
4262 *inend = *input + insize;
4263 /* we can DECREF safely, as the exception has another reference,
4264 so the object won't go away. */
4265 Py_DECREF(inputobj);
4266
4267 if (newpos<0)
4268 newpos = insize+newpos;
4269 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004270 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004271 goto onError;
4272 }
4273
4274 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4275 if (repwstr == NULL)
4276 goto onError;
4277 /* need more space? (at least enough for what we
4278 have+the replacement+the rest of the string (starting
4279 at the new input position), so we won't have to check space
4280 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004281 requiredsize = *outpos;
4282 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4283 goto overflow;
4284 requiredsize += repwlen;
4285 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4286 goto overflow;
4287 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004288 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004289 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004290 requiredsize = 2*outsize;
4291 if (unicode_resize(output, requiredsize) < 0)
4292 goto onError;
4293 }
4294 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4295 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004296 *endinpos = newpos;
4297 *inptr = *input + newpos;
4298
4299 /* we made it! */
4300 Py_XDECREF(restuple);
4301 return 0;
4302
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004303 overflow:
4304 PyErr_SetString(PyExc_OverflowError,
4305 "decoded result is too long for a Python string");
4306
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004307 onError:
4308 Py_XDECREF(restuple);
4309 return -1;
4310}
4311#endif /* HAVE_MBCS */
4312
4313static int
4314unicode_decode_call_errorhandler_writer(
4315 const char *errors, PyObject **errorHandler,
4316 const char *encoding, const char *reason,
4317 const char **input, const char **inend, Py_ssize_t *startinpos,
4318 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4319 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4320{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004321 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004322
4323 PyObject *restuple = NULL;
4324 PyObject *repunicode = NULL;
4325 Py_ssize_t insize;
4326 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004327 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004328 PyObject *inputobj = NULL;
4329
4330 if (*errorHandler == NULL) {
4331 *errorHandler = PyCodec_LookupError(errors);
4332 if (*errorHandler == NULL)
4333 goto onError;
4334 }
4335
4336 make_decode_exception(exceptionObject,
4337 encoding,
4338 *input, *inend - *input,
4339 *startinpos, *endinpos,
4340 reason);
4341 if (*exceptionObject == NULL)
4342 goto onError;
4343
4344 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4345 if (restuple == NULL)
4346 goto onError;
4347 if (!PyTuple_Check(restuple)) {
4348 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4349 goto onError;
4350 }
4351 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004352 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004353
4354 /* Copy back the bytes variables, which might have been modified by the
4355 callback */
4356 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4357 if (!inputobj)
4358 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004359 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004360 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004361 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004362 *input = PyBytes_AS_STRING(inputobj);
4363 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004364 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004365 /* we can DECREF safely, as the exception has another reference,
4366 so the object won't go away. */
4367 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004368
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004369 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004370 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004371 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004372 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004373 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004374 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004375
Victor Stinner8f674cc2013-04-17 23:02:17 +02004376 if (PyUnicode_READY(repunicode) < 0)
4377 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004378 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004379 if (replen > 1) {
4380 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004381 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004382 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4383 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4384 goto onError;
4385 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004386 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004387 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004388
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004389 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004390 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004391
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004392 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004393 Py_XDECREF(restuple);
4394 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004395
Benjamin Peterson29060642009-01-31 22:14:21 +00004396 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004397 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004398 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004399}
4400
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401/* --- UTF-7 Codec -------------------------------------------------------- */
4402
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403/* See RFC2152 for details. We encode conservatively and decode liberally. */
4404
4405/* Three simple macros defining base-64. */
4406
4407/* Is c a base-64 character? */
4408
4409#define IS_BASE64(c) \
4410 (((c) >= 'A' && (c) <= 'Z') || \
4411 ((c) >= 'a' && (c) <= 'z') || \
4412 ((c) >= '0' && (c) <= '9') || \
4413 (c) == '+' || (c) == '/')
4414
4415/* given that c is a base-64 character, what is its base-64 value? */
4416
4417#define FROM_BASE64(c) \
4418 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4419 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4420 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4421 (c) == '+' ? 62 : 63)
4422
4423/* What is the base-64 character of the bottom 6 bits of n? */
4424
4425#define TO_BASE64(n) \
4426 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4427
4428/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4429 * decoded as itself. We are permissive on decoding; the only ASCII
4430 * byte not decoding to itself is the + which begins a base64
4431 * string. */
4432
4433#define DECODE_DIRECT(c) \
4434 ((c) <= 127 && (c) != '+')
4435
4436/* The UTF-7 encoder treats ASCII characters differently according to
4437 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4438 * the above). See RFC2152. This array identifies these different
4439 * sets:
4440 * 0 : "Set D"
4441 * alphanumeric and '(),-./:?
4442 * 1 : "Set O"
4443 * !"#$%&*;<=>@[]^_`{|}
4444 * 2 : "whitespace"
4445 * ht nl cr sp
4446 * 3 : special (must be base64 encoded)
4447 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4448 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004449
Tim Petersced69f82003-09-16 20:30:58 +00004450static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004451char utf7_category[128] = {
4452/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4453 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4454/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4455 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4456/* sp ! " # $ % & ' ( ) * + , - . / */
4457 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4458/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4459 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4460/* @ A B C D E F G H I J K L M N O */
4461 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4462/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4463 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4464/* ` a b c d e f g h i j k l m n o */
4465 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4466/* p q r s t u v w x y z { | } ~ del */
4467 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004468};
4469
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470/* ENCODE_DIRECT: this character should be encoded as itself. The
4471 * answer depends on whether we are encoding set O as itself, and also
4472 * on whether we are encoding whitespace as itself. RFC2152 makes it
4473 * clear that the answers to these questions vary between
4474 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004475
Antoine Pitrou244651a2009-05-04 18:56:13 +00004476#define ENCODE_DIRECT(c, directO, directWS) \
4477 ((c) < 128 && (c) > 0 && \
4478 ((utf7_category[(c)] == 0) || \
4479 (directWS && (utf7_category[(c)] == 2)) || \
4480 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004481
Alexander Belopolsky40018472011-02-26 01:02:56 +00004482PyObject *
4483PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004484 Py_ssize_t size,
4485 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004486{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004487 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4488}
4489
Antoine Pitrou244651a2009-05-04 18:56:13 +00004490/* The decoder. The only state we preserve is our read position,
4491 * i.e. how many characters we have consumed. So if we end in the
4492 * middle of a shift sequence we have to back off the read position
4493 * and the output to the beginning of the sequence, otherwise we lose
4494 * all the shift state (seen bits, number of bits seen, high
4495 * surrogate). */
4496
Alexander Belopolsky40018472011-02-26 01:02:56 +00004497PyObject *
4498PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004499 Py_ssize_t size,
4500 const char *errors,
4501 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004502{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004503 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004504 Py_ssize_t startinpos;
4505 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004506 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004507 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004508 const char *errmsg = "";
4509 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004510 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004511 unsigned int base64bits = 0;
4512 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004513 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004514 PyObject *errorHandler = NULL;
4515 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004516
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004517 if (size == 0) {
4518 if (consumed)
4519 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004520 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004521 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004522
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004523 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004524 _PyUnicodeWriter_Init(&writer);
4525 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004526
4527 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004528 e = s + size;
4529
4530 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004531 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004532 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004533 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004534
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535 if (inShift) { /* in a base-64 section */
4536 if (IS_BASE64(ch)) { /* consume a base-64 character */
4537 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4538 base64bits += 6;
4539 s++;
4540 if (base64bits >= 16) {
4541 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004542 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004543 base64bits -= 16;
4544 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004545 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004546 if (surrogate) {
4547 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004548 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4549 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004550 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004551 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004552 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004553 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554 }
4555 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004556 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004557 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004558 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004559 }
4560 }
Victor Stinner551ac952011-11-29 22:58:13 +01004561 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004562 /* first surrogate */
4563 surrogate = outCh;
4564 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004565 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004566 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004567 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004568 }
4569 }
4570 }
4571 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004572 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 if (base64bits > 0) { /* left-over bits */
4574 if (base64bits >= 6) {
4575 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004576 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 errmsg = "partial character in shift sequence";
4578 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004579 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 else {
4581 /* Some bits remain; they should be zero */
4582 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004583 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 errmsg = "non-zero padding bits in shift sequence";
4585 goto utf7Error;
4586 }
4587 }
4588 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004589 if (surrogate && DECODE_DIRECT(ch)) {
4590 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4591 goto onError;
4592 }
4593 surrogate = 0;
4594 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004595 /* '-' is absorbed; other terminating
4596 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004597 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004598 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004599 }
4600 }
4601 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004602 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004603 s++; /* consume '+' */
4604 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004605 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004606 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004607 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004608 }
4609 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004610 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004611 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004612 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004613 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004614 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004615 }
4616 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004617 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004618 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004619 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004620 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004621 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004622 else {
4623 startinpos = s-starts;
4624 s++;
4625 errmsg = "unexpected special character";
4626 goto utf7Error;
4627 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004628 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004629utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004630 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004631 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004632 errors, &errorHandler,
4633 "utf7", errmsg,
4634 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004635 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004636 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004637 }
4638
Antoine Pitrou244651a2009-05-04 18:56:13 +00004639 /* end of string */
4640
4641 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4642 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004643 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004644 if (surrogate ||
4645 (base64bits >= 6) ||
4646 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004647 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004648 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004649 errors, &errorHandler,
4650 "utf7", "unterminated shift sequence",
4651 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004652 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004653 goto onError;
4654 if (s < e)
4655 goto restart;
4656 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004657 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004658
4659 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004660 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004661 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004662 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004663 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004664 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004665 writer.kind, writer.data, shiftOutStart);
4666 Py_XDECREF(errorHandler);
4667 Py_XDECREF(exc);
4668 _PyUnicodeWriter_Dealloc(&writer);
4669 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004670 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004671 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004672 }
4673 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004674 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004675 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004676 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004677
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004678 Py_XDECREF(errorHandler);
4679 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004680 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004681
Benjamin Peterson29060642009-01-31 22:14:21 +00004682 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004683 Py_XDECREF(errorHandler);
4684 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004685 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004686 return NULL;
4687}
4688
4689
Alexander Belopolsky40018472011-02-26 01:02:56 +00004690PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004691_PyUnicode_EncodeUTF7(PyObject *str,
4692 int base64SetO,
4693 int base64WhiteSpace,
4694 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004695{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004696 int kind;
4697 void *data;
4698 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004699 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004700 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004701 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004702 unsigned int base64bits = 0;
4703 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004704 char * out;
4705 char * start;
4706
Benjamin Petersonbac79492012-01-14 13:34:47 -05004707 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004708 return NULL;
4709 kind = PyUnicode_KIND(str);
4710 data = PyUnicode_DATA(str);
4711 len = PyUnicode_GET_LENGTH(str);
4712
4713 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004714 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004715
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004716 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004717 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004718 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004719 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004720 if (v == NULL)
4721 return NULL;
4722
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004723 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004724 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004725 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004726
Antoine Pitrou244651a2009-05-04 18:56:13 +00004727 if (inShift) {
4728 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4729 /* shifting out */
4730 if (base64bits) { /* output remaining bits */
4731 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4732 base64buffer = 0;
4733 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004734 }
4735 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004736 /* Characters not in the BASE64 set implicitly unshift the sequence
4737 so no '-' is required, except if the character is itself a '-' */
4738 if (IS_BASE64(ch) || ch == '-') {
4739 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004740 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004741 *out++ = (char) ch;
4742 }
4743 else {
4744 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004745 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004746 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004747 else { /* not in a shift sequence */
4748 if (ch == '+') {
4749 *out++ = '+';
4750 *out++ = '-';
4751 }
4752 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4753 *out++ = (char) ch;
4754 }
4755 else {
4756 *out++ = '+';
4757 inShift = 1;
4758 goto encode_char;
4759 }
4760 }
4761 continue;
4762encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004763 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004764 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004765
Antoine Pitrou244651a2009-05-04 18:56:13 +00004766 /* code first surrogate */
4767 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004768 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004769 while (base64bits >= 6) {
4770 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4771 base64bits -= 6;
4772 }
4773 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004774 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004775 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004776 base64bits += 16;
4777 base64buffer = (base64buffer << 16) | ch;
4778 while (base64bits >= 6) {
4779 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4780 base64bits -= 6;
4781 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004782 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004783 if (base64bits)
4784 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4785 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004786 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004787 if (_PyBytes_Resize(&v, out - start) < 0)
4788 return NULL;
4789 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004790}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004791PyObject *
4792PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4793 Py_ssize_t size,
4794 int base64SetO,
4795 int base64WhiteSpace,
4796 const char *errors)
4797{
4798 PyObject *result;
4799 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4800 if (tmp == NULL)
4801 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004802 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004803 base64WhiteSpace, errors);
4804 Py_DECREF(tmp);
4805 return result;
4806}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004807
Antoine Pitrou244651a2009-05-04 18:56:13 +00004808#undef IS_BASE64
4809#undef FROM_BASE64
4810#undef TO_BASE64
4811#undef DECODE_DIRECT
4812#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004813
Guido van Rossumd57fd912000-03-10 22:53:23 +00004814/* --- UTF-8 Codec -------------------------------------------------------- */
4815
Alexander Belopolsky40018472011-02-26 01:02:56 +00004816PyObject *
4817PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004818 Py_ssize_t size,
4819 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004820{
Walter Dörwald69652032004-09-07 20:24:22 +00004821 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4822}
4823
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004824#include "stringlib/asciilib.h"
4825#include "stringlib/codecs.h"
4826#include "stringlib/undef.h"
4827
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004828#include "stringlib/ucs1lib.h"
4829#include "stringlib/codecs.h"
4830#include "stringlib/undef.h"
4831
4832#include "stringlib/ucs2lib.h"
4833#include "stringlib/codecs.h"
4834#include "stringlib/undef.h"
4835
4836#include "stringlib/ucs4lib.h"
4837#include "stringlib/codecs.h"
4838#include "stringlib/undef.h"
4839
Antoine Pitrouab868312009-01-10 15:40:25 +00004840/* Mask to quickly check whether a C 'long' contains a
4841 non-ASCII, UTF8-encoded char. */
4842#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004843# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004844#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004845# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004846#else
4847# error C 'long' size should be either 4 or 8!
4848#endif
4849
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004850static Py_ssize_t
4851ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004852{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004853 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004854 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004855
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004856 /*
4857 * Issue #17237: m68k is a bit different from most architectures in
4858 * that objects do not use "natural alignment" - for example, int and
4859 * long are only aligned at 2-byte boundaries. Therefore the assert()
4860 * won't work; also, tests have shown that skipping the "optimised
4861 * version" will even speed up m68k.
4862 */
4863#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004864#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004865 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4866 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004867 /* Fast path, see in STRINGLIB(utf8_decode) for
4868 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004869 /* Help allocation */
4870 const char *_p = p;
4871 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004872 while (_p < aligned_end) {
4873 unsigned long value = *(const unsigned long *) _p;
4874 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004875 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004876 *((unsigned long *)q) = value;
4877 _p += SIZEOF_LONG;
4878 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004879 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004880 p = _p;
4881 while (p < end) {
4882 if ((unsigned char)*p & 0x80)
4883 break;
4884 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004885 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004886 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004887 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004888#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004889#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004890 while (p < end) {
4891 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4892 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004893 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004894 /* Help allocation */
4895 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004896 while (_p < aligned_end) {
4897 unsigned long value = *(unsigned long *) _p;
4898 if (value & ASCII_CHAR_MASK)
4899 break;
4900 _p += SIZEOF_LONG;
4901 }
4902 p = _p;
4903 if (_p == end)
4904 break;
4905 }
4906 if ((unsigned char)*p & 0x80)
4907 break;
4908 ++p;
4909 }
4910 memcpy(dest, start, p - start);
4911 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004912}
Antoine Pitrouab868312009-01-10 15:40:25 +00004913
Victor Stinner785938e2011-12-11 20:09:03 +01004914PyObject *
4915PyUnicode_DecodeUTF8Stateful(const char *s,
4916 Py_ssize_t size,
4917 const char *errors,
4918 Py_ssize_t *consumed)
4919{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004920 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004921 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004922 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004923
4924 Py_ssize_t startinpos;
4925 Py_ssize_t endinpos;
4926 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004927 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004928 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004929 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004930
4931 if (size == 0) {
4932 if (consumed)
4933 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004934 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004935 }
4936
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004937 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4938 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004939 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004940 *consumed = 1;
4941 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004942 }
4943
Victor Stinner8f674cc2013-04-17 23:02:17 +02004944 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004945 writer.min_length = size;
4946 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004947 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004948
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004949 writer.pos = ascii_decode(s, end, writer.data);
4950 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004951 while (s < end) {
4952 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004953 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004954
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004955 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004956 if (PyUnicode_IS_ASCII(writer.buffer))
4957 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004958 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004959 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004960 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004961 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004962 } else {
4963 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004964 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004965 }
4966
4967 switch (ch) {
4968 case 0:
4969 if (s == end || consumed)
4970 goto End;
4971 errmsg = "unexpected end of data";
4972 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004973 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004974 break;
4975 case 1:
4976 errmsg = "invalid start byte";
4977 startinpos = s - starts;
4978 endinpos = startinpos + 1;
4979 break;
4980 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004981 case 3:
4982 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004983 errmsg = "invalid continuation byte";
4984 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004985 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004986 break;
4987 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004988 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004989 goto onError;
4990 continue;
4991 }
4992
Victor Stinner1d65d912015-10-05 13:43:50 +02004993 if (error_handler == _Py_ERROR_UNKNOWN)
4994 error_handler = get_error_handler(errors);
4995
4996 switch (error_handler) {
4997 case _Py_ERROR_IGNORE:
4998 s += (endinpos - startinpos);
4999 break;
5000
5001 case _Py_ERROR_REPLACE:
5002 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5003 goto onError;
5004 s += (endinpos - startinpos);
5005 break;
5006
5007 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005008 {
5009 Py_ssize_t i;
5010
Victor Stinner1d65d912015-10-05 13:43:50 +02005011 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5012 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005013 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005014 ch = (Py_UCS4)(unsigned char)(starts[i]);
5015 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5016 ch + 0xdc00);
5017 writer.pos++;
5018 }
5019 s += (endinpos - startinpos);
5020 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005021 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005022
5023 default:
5024 if (unicode_decode_call_errorhandler_writer(
5025 errors, &error_handler_obj,
5026 "utf-8", errmsg,
5027 &starts, &end, &startinpos, &endinpos, &exc, &s,
5028 &writer))
5029 goto onError;
5030 }
Victor Stinner785938e2011-12-11 20:09:03 +01005031 }
5032
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005033End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005034 if (consumed)
5035 *consumed = s - starts;
5036
Victor Stinner1d65d912015-10-05 13:43:50 +02005037 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005038 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005039 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005040
5041onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005042 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005043 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005044 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005045 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005046}
5047
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005048#ifdef __APPLE__
5049
5050/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005051 used to decode the command line arguments on Mac OS X.
5052
5053 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005054 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005055
5056wchar_t*
5057_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5058{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005059 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005060 wchar_t *unicode;
5061 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005062
5063 /* Note: size will always be longer than the resulting Unicode
5064 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005065 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005066 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005067 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005068 if (!unicode)
5069 return NULL;
5070
5071 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005072 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005073 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005074 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005075 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005076#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005077 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005078#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005079 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005080#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005081 if (ch > 0xFF) {
5082#if SIZEOF_WCHAR_T == 4
5083 assert(0);
5084#else
5085 assert(Py_UNICODE_IS_SURROGATE(ch));
5086 /* compute and append the two surrogates: */
5087 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5088 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5089#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005090 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005091 else {
5092 if (!ch && s == e)
5093 break;
5094 /* surrogateescape */
5095 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5096 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005097 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005098 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005099 return unicode;
5100}
5101
5102#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005104/* Primary internal function which creates utf8 encoded bytes objects.
5105
5106 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005107 and allocate exactly as much space needed at the end. Else allocate the
5108 maximum possible needed (4 result bytes per Unicode character), and return
5109 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005110*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005111PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005112_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005113{
Victor Stinner6099a032011-12-18 14:22:26 +01005114 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005115 void *data;
5116 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005118 if (!PyUnicode_Check(unicode)) {
5119 PyErr_BadArgument();
5120 return NULL;
5121 }
5122
5123 if (PyUnicode_READY(unicode) == -1)
5124 return NULL;
5125
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005126 if (PyUnicode_UTF8(unicode))
5127 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5128 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005129
5130 kind = PyUnicode_KIND(unicode);
5131 data = PyUnicode_DATA(unicode);
5132 size = PyUnicode_GET_LENGTH(unicode);
5133
Benjamin Petersonead6b532011-12-20 17:23:42 -06005134 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005135 default:
5136 assert(0);
5137 case PyUnicode_1BYTE_KIND:
5138 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5139 assert(!PyUnicode_IS_ASCII(unicode));
5140 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5141 case PyUnicode_2BYTE_KIND:
5142 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5143 case PyUnicode_4BYTE_KIND:
5144 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005145 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005146}
5147
Alexander Belopolsky40018472011-02-26 01:02:56 +00005148PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005149PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5150 Py_ssize_t size,
5151 const char *errors)
5152{
5153 PyObject *v, *unicode;
5154
5155 unicode = PyUnicode_FromUnicode(s, size);
5156 if (unicode == NULL)
5157 return NULL;
5158 v = _PyUnicode_AsUTF8String(unicode, errors);
5159 Py_DECREF(unicode);
5160 return v;
5161}
5162
5163PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005164PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005165{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005166 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005167}
5168
Walter Dörwald41980ca2007-08-16 21:55:45 +00005169/* --- UTF-32 Codec ------------------------------------------------------- */
5170
5171PyObject *
5172PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005173 Py_ssize_t size,
5174 const char *errors,
5175 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005176{
5177 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5178}
5179
5180PyObject *
5181PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005182 Py_ssize_t size,
5183 const char *errors,
5184 int *byteorder,
5185 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005186{
5187 const char *starts = s;
5188 Py_ssize_t startinpos;
5189 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005190 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005191 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005192 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005193 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005194 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005195 PyObject *errorHandler = NULL;
5196 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005197
Walter Dörwald41980ca2007-08-16 21:55:45 +00005198 q = (unsigned char *)s;
5199 e = q + size;
5200
5201 if (byteorder)
5202 bo = *byteorder;
5203
5204 /* Check for BOM marks (U+FEFF) in the input and adjust current
5205 byte order setting accordingly. In native mode, the leading BOM
5206 mark is skipped, in all other modes, it is copied to the output
5207 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005208 if (bo == 0 && size >= 4) {
5209 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5210 if (bom == 0x0000FEFF) {
5211 bo = -1;
5212 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005213 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005214 else if (bom == 0xFFFE0000) {
5215 bo = 1;
5216 q += 4;
5217 }
5218 if (byteorder)
5219 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005220 }
5221
Victor Stinnere64322e2012-10-30 23:12:47 +01005222 if (q == e) {
5223 if (consumed)
5224 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005225 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005226 }
5227
Victor Stinnere64322e2012-10-30 23:12:47 +01005228#ifdef WORDS_BIGENDIAN
5229 le = bo < 0;
5230#else
5231 le = bo <= 0;
5232#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005233 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005234
Victor Stinner8f674cc2013-04-17 23:02:17 +02005235 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005236 writer.min_length = (e - q + 3) / 4;
5237 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005238 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005239
Victor Stinnere64322e2012-10-30 23:12:47 +01005240 while (1) {
5241 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005242 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005243
Victor Stinnere64322e2012-10-30 23:12:47 +01005244 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005245 enum PyUnicode_Kind kind = writer.kind;
5246 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005247 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005248 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005249 if (le) {
5250 do {
5251 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5252 if (ch > maxch)
5253 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005254 if (kind != PyUnicode_1BYTE_KIND &&
5255 Py_UNICODE_IS_SURROGATE(ch))
5256 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005257 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005258 q += 4;
5259 } while (q <= last);
5260 }
5261 else {
5262 do {
5263 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5264 if (ch > maxch)
5265 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005266 if (kind != PyUnicode_1BYTE_KIND &&
5267 Py_UNICODE_IS_SURROGATE(ch))
5268 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005269 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005270 q += 4;
5271 } while (q <= last);
5272 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005273 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005274 }
5275
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005276 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005277 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005278 startinpos = ((const char *)q) - starts;
5279 endinpos = startinpos + 4;
5280 }
5281 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005282 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005283 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005284 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005285 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005286 startinpos = ((const char *)q) - starts;
5287 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005288 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005289 else {
5290 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005291 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005292 goto onError;
5293 q += 4;
5294 continue;
5295 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005296 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005297 startinpos = ((const char *)q) - starts;
5298 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005299 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005300
5301 /* The remaining input chars are ignored if the callback
5302 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005303 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005304 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005305 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005306 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005307 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005308 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005309 }
5310
Walter Dörwald41980ca2007-08-16 21:55:45 +00005311 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005312 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005313
Walter Dörwald41980ca2007-08-16 21:55:45 +00005314 Py_XDECREF(errorHandler);
5315 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005316 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005317
Benjamin Peterson29060642009-01-31 22:14:21 +00005318 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005319 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005320 Py_XDECREF(errorHandler);
5321 Py_XDECREF(exc);
5322 return NULL;
5323}
5324
5325PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005326_PyUnicode_EncodeUTF32(PyObject *str,
5327 const char *errors,
5328 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005329{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005330 enum PyUnicode_Kind kind;
5331 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005332 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005333 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005334 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005335#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005336 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005337#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005338 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005339#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005340 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005341 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005342 PyObject *errorHandler = NULL;
5343 PyObject *exc = NULL;
5344 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005345
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005346 if (!PyUnicode_Check(str)) {
5347 PyErr_BadArgument();
5348 return NULL;
5349 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005350 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005351 return NULL;
5352 kind = PyUnicode_KIND(str);
5353 data = PyUnicode_DATA(str);
5354 len = PyUnicode_GET_LENGTH(str);
5355
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005356 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005357 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005358 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005359 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005360 if (v == NULL)
5361 return NULL;
5362
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005363 /* output buffer is 4-bytes aligned */
5364 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005365 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005366 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005367 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005368 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005369 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005370
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005371 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005372 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005373 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005374 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005375 else
5376 encoding = "utf-32";
5377
5378 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005379 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5380 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005381 }
5382
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005383 pos = 0;
5384 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005385 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005386
5387 if (kind == PyUnicode_2BYTE_KIND) {
5388 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5389 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005390 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005391 else {
5392 assert(kind == PyUnicode_4BYTE_KIND);
5393 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5394 &out, native_ordering);
5395 }
5396 if (pos == len)
5397 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005398
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005399 rep = unicode_encode_call_errorhandler(
5400 errors, &errorHandler,
5401 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005402 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005403 if (!rep)
5404 goto error;
5405
5406 if (PyBytes_Check(rep)) {
5407 repsize = PyBytes_GET_SIZE(rep);
5408 if (repsize & 3) {
5409 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005410 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005411 "surrogates not allowed");
5412 goto error;
5413 }
5414 moreunits = repsize / 4;
5415 }
5416 else {
5417 assert(PyUnicode_Check(rep));
5418 if (PyUnicode_READY(rep) < 0)
5419 goto error;
5420 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5421 if (!PyUnicode_IS_ASCII(rep)) {
5422 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005423 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005424 "surrogates not allowed");
5425 goto error;
5426 }
5427 }
5428
5429 /* four bytes are reserved for each surrogate */
5430 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005431 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005432 Py_ssize_t morebytes = 4 * (moreunits - 1);
5433 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5434 /* integer overflow */
5435 PyErr_NoMemory();
5436 goto error;
5437 }
5438 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5439 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005440 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005441 }
5442
5443 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005444 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5445 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005446 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005447 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005448 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5449 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005450 }
5451
5452 Py_CLEAR(rep);
5453 }
5454
5455 /* Cut back to size actually needed. This is necessary for, for example,
5456 encoding of a string containing isolated surrogates and the 'ignore'
5457 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005458 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005459 if (nsize != PyBytes_GET_SIZE(v))
5460 _PyBytes_Resize(&v, nsize);
5461 Py_XDECREF(errorHandler);
5462 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005463 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005464 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005465 error:
5466 Py_XDECREF(rep);
5467 Py_XDECREF(errorHandler);
5468 Py_XDECREF(exc);
5469 Py_XDECREF(v);
5470 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005471}
5472
Alexander Belopolsky40018472011-02-26 01:02:56 +00005473PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005474PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5475 Py_ssize_t size,
5476 const char *errors,
5477 int byteorder)
5478{
5479 PyObject *result;
5480 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5481 if (tmp == NULL)
5482 return NULL;
5483 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5484 Py_DECREF(tmp);
5485 return result;
5486}
5487
5488PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005489PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005490{
Victor Stinnerb960b342011-11-20 19:12:52 +01005491 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005492}
5493
Guido van Rossumd57fd912000-03-10 22:53:23 +00005494/* --- UTF-16 Codec ------------------------------------------------------- */
5495
Tim Peters772747b2001-08-09 22:21:55 +00005496PyObject *
5497PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005498 Py_ssize_t size,
5499 const char *errors,
5500 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005501{
Walter Dörwald69652032004-09-07 20:24:22 +00005502 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5503}
5504
5505PyObject *
5506PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005507 Py_ssize_t size,
5508 const char *errors,
5509 int *byteorder,
5510 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005511{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005512 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005513 Py_ssize_t startinpos;
5514 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005515 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005516 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005517 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005518 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005519 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005520 PyObject *errorHandler = NULL;
5521 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005522 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005523
Tim Peters772747b2001-08-09 22:21:55 +00005524 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005525 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005526
5527 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005528 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005529
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005530 /* Check for BOM marks (U+FEFF) in the input and adjust current
5531 byte order setting accordingly. In native mode, the leading BOM
5532 mark is skipped, in all other modes, it is copied to the output
5533 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005534 if (bo == 0 && size >= 2) {
5535 const Py_UCS4 bom = (q[1] << 8) | q[0];
5536 if (bom == 0xFEFF) {
5537 q += 2;
5538 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005539 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005540 else if (bom == 0xFFFE) {
5541 q += 2;
5542 bo = 1;
5543 }
5544 if (byteorder)
5545 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005546 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005547
Antoine Pitrou63065d72012-05-15 23:48:04 +02005548 if (q == e) {
5549 if (consumed)
5550 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005551 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005552 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005553
Christian Heimes743e0cd2012-10-17 23:52:17 +02005554#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005555 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005556 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005557#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005558 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005559 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005560#endif
Tim Peters772747b2001-08-09 22:21:55 +00005561
Antoine Pitrou63065d72012-05-15 23:48:04 +02005562 /* Note: size will always be longer than the resulting Unicode
5563 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005564 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005565 writer.min_length = (e - q + 1) / 2;
5566 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005567 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005568
Antoine Pitrou63065d72012-05-15 23:48:04 +02005569 while (1) {
5570 Py_UCS4 ch = 0;
5571 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005572 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005573 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005574 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005575 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005576 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005577 native_ordering);
5578 else
5579 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005580 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005581 native_ordering);
5582 } else if (kind == PyUnicode_2BYTE_KIND) {
5583 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005584 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005585 native_ordering);
5586 } else {
5587 assert(kind == PyUnicode_4BYTE_KIND);
5588 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005589 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005590 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005591 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005592 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005593
Antoine Pitrou63065d72012-05-15 23:48:04 +02005594 switch (ch)
5595 {
5596 case 0:
5597 /* remaining byte at the end? (size should be even) */
5598 if (q == e || consumed)
5599 goto End;
5600 errmsg = "truncated data";
5601 startinpos = ((const char *)q) - starts;
5602 endinpos = ((const char *)e) - starts;
5603 break;
5604 /* The remaining input chars are ignored if the callback
5605 chooses to skip the input */
5606 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005607 q -= 2;
5608 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005609 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005610 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005611 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005612 endinpos = ((const char *)e) - starts;
5613 break;
5614 case 2:
5615 errmsg = "illegal encoding";
5616 startinpos = ((const char *)q) - 2 - starts;
5617 endinpos = startinpos + 2;
5618 break;
5619 case 3:
5620 errmsg = "illegal UTF-16 surrogate";
5621 startinpos = ((const char *)q) - 4 - starts;
5622 endinpos = startinpos + 2;
5623 break;
5624 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005625 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005626 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005627 continue;
5628 }
5629
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005630 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005631 errors,
5632 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005633 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005634 &starts,
5635 (const char **)&e,
5636 &startinpos,
5637 &endinpos,
5638 &exc,
5639 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005640 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005641 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005642 }
5643
Antoine Pitrou63065d72012-05-15 23:48:04 +02005644End:
Walter Dörwald69652032004-09-07 20:24:22 +00005645 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005646 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005647
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005648 Py_XDECREF(errorHandler);
5649 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005650 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005651
Benjamin Peterson29060642009-01-31 22:14:21 +00005652 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005653 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005654 Py_XDECREF(errorHandler);
5655 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005656 return NULL;
5657}
5658
Tim Peters772747b2001-08-09 22:21:55 +00005659PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005660_PyUnicode_EncodeUTF16(PyObject *str,
5661 const char *errors,
5662 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005664 enum PyUnicode_Kind kind;
5665 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005666 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005667 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005668 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005669 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005670#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005671 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005672#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005673 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005674#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005675 const char *encoding;
5676 Py_ssize_t nsize, pos;
5677 PyObject *errorHandler = NULL;
5678 PyObject *exc = NULL;
5679 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005680
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005681 if (!PyUnicode_Check(str)) {
5682 PyErr_BadArgument();
5683 return NULL;
5684 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005685 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005686 return NULL;
5687 kind = PyUnicode_KIND(str);
5688 data = PyUnicode_DATA(str);
5689 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005690
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005691 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005692 if (kind == PyUnicode_4BYTE_KIND) {
5693 const Py_UCS4 *in = (const Py_UCS4 *)data;
5694 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005695 while (in < end) {
5696 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005697 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005698 }
5699 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005700 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005701 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005702 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005703 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005704 nsize = len + pairs + (byteorder == 0);
5705 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005706 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005707 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005708 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005709
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005710 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005711 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005712 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005713 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005714 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005715 }
5716 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005717 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005718 }
Tim Peters772747b2001-08-09 22:21:55 +00005719
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005720 if (kind == PyUnicode_1BYTE_KIND) {
5721 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5722 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005723 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005724
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005725 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005726 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005727 }
5728 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005729 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005730 }
5731 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005732 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005733 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005734
5735 pos = 0;
5736 while (pos < len) {
5737 Py_ssize_t repsize, moreunits;
5738
5739 if (kind == PyUnicode_2BYTE_KIND) {
5740 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5741 &out, native_ordering);
5742 }
5743 else {
5744 assert(kind == PyUnicode_4BYTE_KIND);
5745 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5746 &out, native_ordering);
5747 }
5748 if (pos == len)
5749 break;
5750
5751 rep = unicode_encode_call_errorhandler(
5752 errors, &errorHandler,
5753 encoding, "surrogates not allowed",
5754 str, &exc, pos, pos + 1, &pos);
5755 if (!rep)
5756 goto error;
5757
5758 if (PyBytes_Check(rep)) {
5759 repsize = PyBytes_GET_SIZE(rep);
5760 if (repsize & 1) {
5761 raise_encode_exception(&exc, encoding,
5762 str, pos - 1, pos,
5763 "surrogates not allowed");
5764 goto error;
5765 }
5766 moreunits = repsize / 2;
5767 }
5768 else {
5769 assert(PyUnicode_Check(rep));
5770 if (PyUnicode_READY(rep) < 0)
5771 goto error;
5772 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5773 if (!PyUnicode_IS_ASCII(rep)) {
5774 raise_encode_exception(&exc, encoding,
5775 str, pos - 1, pos,
5776 "surrogates not allowed");
5777 goto error;
5778 }
5779 }
5780
5781 /* two bytes are reserved for each surrogate */
5782 if (moreunits > 1) {
5783 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5784 Py_ssize_t morebytes = 2 * (moreunits - 1);
5785 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5786 /* integer overflow */
5787 PyErr_NoMemory();
5788 goto error;
5789 }
5790 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5791 goto error;
5792 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5793 }
5794
5795 if (PyBytes_Check(rep)) {
5796 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5797 out += moreunits;
5798 } else /* rep is unicode */ {
5799 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5800 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5801 &out, native_ordering);
5802 }
5803
5804 Py_CLEAR(rep);
5805 }
5806
5807 /* Cut back to size actually needed. This is necessary for, for example,
5808 encoding of a string containing isolated surrogates and the 'ignore' handler
5809 is used. */
5810 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5811 if (nsize != PyBytes_GET_SIZE(v))
5812 _PyBytes_Resize(&v, nsize);
5813 Py_XDECREF(errorHandler);
5814 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005815 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005816 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005817 error:
5818 Py_XDECREF(rep);
5819 Py_XDECREF(errorHandler);
5820 Py_XDECREF(exc);
5821 Py_XDECREF(v);
5822 return NULL;
5823#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005824}
5825
Alexander Belopolsky40018472011-02-26 01:02:56 +00005826PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005827PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5828 Py_ssize_t size,
5829 const char *errors,
5830 int byteorder)
5831{
5832 PyObject *result;
5833 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5834 if (tmp == NULL)
5835 return NULL;
5836 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5837 Py_DECREF(tmp);
5838 return result;
5839}
5840
5841PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005842PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005843{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005844 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005845}
5846
5847/* --- Unicode Escape Codec ----------------------------------------------- */
5848
Fredrik Lundh06d12682001-01-24 07:59:11 +00005849static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005850
Alexander Belopolsky40018472011-02-26 01:02:56 +00005851PyObject *
5852PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005853 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005854 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005855{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005856 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005857 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005858 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005859 PyObject *errorHandler = NULL;
5860 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005861
Victor Stinner62ec3312016-09-06 17:04:34 -07005862 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005863 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005864 }
5865 /* Escaped strings will always be longer than the resulting
5866 Unicode string, so we start with size here and then reduce the
5867 length after conversion to the true value.
5868 (but if the error callback returns a long replacement string
5869 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005870 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005871 writer.min_length = size;
5872 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5873 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005874 }
5875
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876 end = s + size;
5877 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005878 unsigned char c = (unsigned char) *s++;
5879 Py_UCS4 ch;
5880 int count;
5881 Py_ssize_t startinpos;
5882 Py_ssize_t endinpos;
5883 const char *message;
5884
5885#define WRITE_ASCII_CHAR(ch) \
5886 do { \
5887 assert(ch <= 127); \
5888 assert(writer.pos < writer.size); \
5889 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5890 } while(0)
5891
5892#define WRITE_CHAR(ch) \
5893 do { \
5894 if (ch <= writer.maxchar) { \
5895 assert(writer.pos < writer.size); \
5896 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5897 } \
5898 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5899 goto onError; \
5900 } \
5901 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005902
5903 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005904 if (c != '\\') {
5905 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005906 continue;
5907 }
5908
Victor Stinner62ec3312016-09-06 17:04:34 -07005909 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005911 if (s >= end) {
5912 message = "\\ at end of string";
5913 goto error;
5914 }
5915 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005916
Victor Stinner62ec3312016-09-06 17:04:34 -07005917 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005918 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919
Benjamin Peterson29060642009-01-31 22:14:21 +00005920 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005921 case '\n': continue;
5922 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5923 case '\'': WRITE_ASCII_CHAR('\''); continue;
5924 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5925 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005926 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005927 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5928 case 't': WRITE_ASCII_CHAR('\t'); continue;
5929 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5930 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005931 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005932 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005933 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005934 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935
Benjamin Peterson29060642009-01-31 22:14:21 +00005936 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937 case '0': case '1': case '2': case '3':
5938 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005939 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005940 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005941 ch = (ch<<3) + *s++ - '0';
5942 if (s < end && '0' <= *s && *s <= '7') {
5943 ch = (ch<<3) + *s++ - '0';
5944 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005945 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005946 WRITE_CHAR(ch);
5947 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005948
Benjamin Peterson29060642009-01-31 22:14:21 +00005949 /* hex escapes */
5950 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005951 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005952 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005953 message = "truncated \\xXX escape";
5954 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005955
Benjamin Peterson29060642009-01-31 22:14:21 +00005956 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005957 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005958 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005959 message = "truncated \\uXXXX escape";
5960 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005961
Benjamin Peterson29060642009-01-31 22:14:21 +00005962 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005963 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005964 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005965 message = "truncated \\UXXXXXXXX escape";
5966 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07005967 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02005968 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07005969 ch <<= 4;
5970 if (c >= '0' && c <= '9') {
5971 ch += c - '0';
5972 }
5973 else if (c >= 'a' && c <= 'f') {
5974 ch += c - ('a' - 10);
5975 }
5976 else if (c >= 'A' && c <= 'F') {
5977 ch += c - ('A' - 10);
5978 }
5979 else {
5980 break;
5981 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00005982 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005983 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02005984 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07005985 }
5986
5987 /* when we get here, ch is a 32-bit unicode character */
5988 if (ch > MAX_UNICODE) {
5989 message = "illegal Unicode character";
5990 goto error;
5991 }
5992
5993 WRITE_CHAR(ch);
5994 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005995
Benjamin Peterson29060642009-01-31 22:14:21 +00005996 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005997 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005998 if (ucnhash_CAPI == NULL) {
5999 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006000 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6001 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006002 if (ucnhash_CAPI == NULL) {
6003 PyErr_SetString(
6004 PyExc_UnicodeError,
6005 "\\N escapes not supported (can't load unicodedata module)"
6006 );
6007 goto onError;
6008 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006009 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006010
6011 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006012 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006013 const char *start = ++s;
6014 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006015 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006016 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006017 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006018 namelen = s - start;
6019 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006020 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006021 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006022 ch = 0xffffffff; /* in case 'getcode' messes up */
6023 if (namelen <= INT_MAX &&
6024 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6025 &ch, 0)) {
6026 assert(ch <= MAX_UNICODE);
6027 WRITE_CHAR(ch);
6028 continue;
6029 }
6030 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006031 }
6032 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006033 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006034
6035 default:
Victor Stinner62ec3312016-09-06 17:04:34 -07006036 WRITE_ASCII_CHAR('\\');
6037 WRITE_CHAR(c);
6038 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006040
6041 error:
6042 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006043 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006044 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006045 errors, &errorHandler,
6046 "unicodeescape", message,
6047 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006048 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006049 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006050 }
6051 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6052 goto onError;
6053 }
6054
6055#undef WRITE_ASCII_CHAR
6056#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006058
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006059 Py_XDECREF(errorHandler);
6060 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006061 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006062
Benjamin Peterson29060642009-01-31 22:14:21 +00006063 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006064 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006065 Py_XDECREF(errorHandler);
6066 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067 return NULL;
6068}
6069
6070/* Return a Unicode-Escape string version of the Unicode object.
6071
6072 If quotes is true, the string is enclosed in u"" or u'' quotes as
6073 appropriate.
6074
6075*/
6076
Alexander Belopolsky40018472011-02-26 01:02:56 +00006077PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006078PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006080 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006081 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006083 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006084 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006085 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086
Ezio Melottie7f90372012-10-05 03:33:31 +03006087 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006088 escape.
6089
Ezio Melottie7f90372012-10-05 03:33:31 +03006090 For UCS1 strings it's '\xxx', 4 bytes per source character.
6091 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6092 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006093 */
6094
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006095 if (!PyUnicode_Check(unicode)) {
6096 PyErr_BadArgument();
6097 return NULL;
6098 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006099 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006100 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006101 }
Victor Stinner358af132015-10-12 22:36:57 +02006102
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006103 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006104 if (len == 0) {
6105 return PyBytes_FromStringAndSize(NULL, 0);
6106 }
6107
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006108 kind = PyUnicode_KIND(unicode);
6109 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006110 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6111 bytes, and 1 byte characters 4. */
6112 expandsize = kind * 2 + 2;
6113 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize) {
6114 return PyErr_NoMemory();
6115 }
6116 repr = PyBytes_FromStringAndSize(NULL, 2 + expandsize * len + 1);
6117 if (repr == NULL) {
6118 return NULL;
6119 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006120
Victor Stinner62ec3312016-09-06 17:04:34 -07006121 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006122 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006123 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006124
Victor Stinner62ec3312016-09-06 17:04:34 -07006125 /* U+0000-U+00ff range */
6126 if (ch < 0x100) {
6127 if (ch >= ' ' && ch < 127) {
6128 if (ch != '\\') {
6129 /* Copy printable US ASCII as-is */
6130 *p++ = (char) ch;
6131 }
6132 /* Escape backslashes */
6133 else {
6134 *p++ = '\\';
6135 *p++ = '\\';
6136 }
6137 }
Victor Stinner358af132015-10-12 22:36:57 +02006138
Victor Stinner62ec3312016-09-06 17:04:34 -07006139 /* Map special whitespace to '\t', \n', '\r' */
6140 else if (ch == '\t') {
6141 *p++ = '\\';
6142 *p++ = 't';
6143 }
6144 else if (ch == '\n') {
6145 *p++ = '\\';
6146 *p++ = 'n';
6147 }
6148 else if (ch == '\r') {
6149 *p++ = '\\';
6150 *p++ = 'r';
6151 }
6152
6153 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6154 else {
6155 *p++ = '\\';
6156 *p++ = 'x';
6157 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6158 *p++ = Py_hexdigits[ch & 0x000F];
6159 }
Tim Petersced69f82003-09-16 20:30:58 +00006160 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006161 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6162 else if (ch < 0x10000) {
6163 /* U+0100-U+ffff */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006164 *p++ = '\\';
6165 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006166 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6167 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6168 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6169 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006170 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006171 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6172 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006173
Victor Stinner62ec3312016-09-06 17:04:34 -07006174 /* Make sure that the first two digits are zero */
6175 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006176 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006177 *p++ = 'U';
6178 *p++ = '0';
6179 *p++ = '0';
6180 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6181 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6182 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6183 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6184 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6185 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006186 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188
Victor Stinner62ec3312016-09-06 17:04:34 -07006189 assert(p - PyBytes_AS_STRING(repr) > 0);
6190 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6191 return NULL;
6192 }
6193 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006194}
6195
Alexander Belopolsky40018472011-02-26 01:02:56 +00006196PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006197PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6198 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006200 PyObject *result;
6201 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006202 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006203 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006204 }
6205
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006206 result = PyUnicode_AsUnicodeEscapeString(tmp);
6207 Py_DECREF(tmp);
6208 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209}
6210
6211/* --- Raw Unicode Escape Codec ------------------------------------------- */
6212
Alexander Belopolsky40018472011-02-26 01:02:56 +00006213PyObject *
6214PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006215 Py_ssize_t size,
6216 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006217{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006218 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006219 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006220 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006221 PyObject *errorHandler = NULL;
6222 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006223
Victor Stinner62ec3312016-09-06 17:04:34 -07006224 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006225 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006226 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006227
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228 /* Escaped strings will always be longer than the resulting
6229 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006230 length after conversion to the true value. (But decoding error
6231 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006232 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006233 writer.min_length = size;
6234 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6235 goto onError;
6236 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006237
Guido van Rossumd57fd912000-03-10 22:53:23 +00006238 end = s + size;
6239 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006240 unsigned char c = (unsigned char) *s++;
6241 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006242 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006243 Py_ssize_t startinpos;
6244 Py_ssize_t endinpos;
6245 const char *message;
6246
6247#define WRITE_CHAR(ch) \
6248 do { \
6249 if (ch <= writer.maxchar) { \
6250 assert(writer.pos < writer.size); \
6251 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6252 } \
6253 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6254 goto onError; \
6255 } \
6256 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006257
Benjamin Peterson29060642009-01-31 22:14:21 +00006258 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006259 if (c != '\\' || s >= end) {
6260 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006261 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006262 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006263
Victor Stinner62ec3312016-09-06 17:04:34 -07006264 c = (unsigned char) *s++;
6265 if (c == 'u') {
6266 count = 4;
6267 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006268 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006269 else if (c == 'U') {
6270 count = 8;
6271 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006272 }
6273 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006274 assert(writer.pos < writer.size);
6275 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6276 WRITE_CHAR(c);
6277 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006278 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006279 startinpos = s - starts - 2;
6280
6281 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6282 for (ch = 0; count && s < end; ++s, --count) {
6283 c = (unsigned char)*s;
6284 ch <<= 4;
6285 if (c >= '0' && c <= '9') {
6286 ch += c - '0';
6287 }
6288 else if (c >= 'a' && c <= 'f') {
6289 ch += c - ('a' - 10);
6290 }
6291 else if (c >= 'A' && c <= 'F') {
6292 ch += c - ('A' - 10);
6293 }
6294 else {
6295 break;
6296 }
6297 }
6298 if (!count) {
6299 if (ch <= MAX_UNICODE) {
6300 WRITE_CHAR(ch);
6301 continue;
6302 }
6303 message = "\\Uxxxxxxxx out of range";
6304 }
6305
6306 endinpos = s-starts;
6307 writer.min_length = end - s + writer.pos;
6308 if (unicode_decode_call_errorhandler_writer(
6309 errors, &errorHandler,
6310 "rawunicodeescape", message,
6311 &starts, &end, &startinpos, &endinpos, &exc, &s,
6312 &writer)) {
6313 goto onError;
6314 }
6315 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6316 goto onError;
6317 }
6318
6319#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006320 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006321 Py_XDECREF(errorHandler);
6322 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006323 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006324
Benjamin Peterson29060642009-01-31 22:14:21 +00006325 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006326 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006327 Py_XDECREF(errorHandler);
6328 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006329 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006330
Guido van Rossumd57fd912000-03-10 22:53:23 +00006331}
6332
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006333
Alexander Belopolsky40018472011-02-26 01:02:56 +00006334PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006335PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006336{
Victor Stinner62ec3312016-09-06 17:04:34 -07006337 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006338 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006339 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006340 int kind;
6341 void *data;
6342 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006344 if (!PyUnicode_Check(unicode)) {
6345 PyErr_BadArgument();
6346 return NULL;
6347 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006348 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006349 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006350 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006351 kind = PyUnicode_KIND(unicode);
6352 data = PyUnicode_DATA(unicode);
6353 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006354 if (kind == PyUnicode_1BYTE_KIND) {
6355 return PyBytes_FromStringAndSize(data, len);
6356 }
Victor Stinner0e368262011-11-10 20:12:49 +01006357
Victor Stinner62ec3312016-09-06 17:04:34 -07006358 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6359 bytes, and 1 byte characters 4. */
6360 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006361
Victor Stinner62ec3312016-09-06 17:04:34 -07006362 if (len > PY_SSIZE_T_MAX / expandsize) {
6363 return PyErr_NoMemory();
6364 }
6365 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6366 if (repr == NULL) {
6367 return NULL;
6368 }
6369 if (len == 0) {
6370 return repr;
6371 }
6372
6373 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006374 for (pos = 0; pos < len; pos++) {
6375 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006376
Victor Stinner62ec3312016-09-06 17:04:34 -07006377 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6378 if (ch < 0x100) {
6379 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006380 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006381 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6382 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006383 *p++ = '\\';
6384 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006385 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6386 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6387 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6388 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006389 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006390 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6391 else {
6392 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6393 *p++ = '\\';
6394 *p++ = 'U';
6395 *p++ = '0';
6396 *p++ = '0';
6397 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6398 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6399 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6400 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6401 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6402 *p++ = Py_hexdigits[ch & 15];
6403 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006404 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006405
Victor Stinner62ec3312016-09-06 17:04:34 -07006406 assert(p > PyBytes_AS_STRING(repr));
6407 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6408 return NULL;
6409 }
6410 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006411}
6412
Alexander Belopolsky40018472011-02-26 01:02:56 +00006413PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006414PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6415 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006416{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006417 PyObject *result;
6418 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6419 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006420 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006421 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6422 Py_DECREF(tmp);
6423 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006424}
6425
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006426/* --- Unicode Internal Codec ------------------------------------------- */
6427
Alexander Belopolsky40018472011-02-26 01:02:56 +00006428PyObject *
6429_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006430 Py_ssize_t size,
6431 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006432{
6433 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006434 Py_ssize_t startinpos;
6435 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006436 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006437 const char *end;
6438 const char *reason;
6439 PyObject *errorHandler = NULL;
6440 PyObject *exc = NULL;
6441
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006442 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006443 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006444 1))
6445 return NULL;
6446
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006447 if (size == 0)
6448 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006449
Victor Stinner8f674cc2013-04-17 23:02:17 +02006450 _PyUnicodeWriter_Init(&writer);
6451 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6452 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006453 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006454 }
6455 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006456
Victor Stinner8f674cc2013-04-17 23:02:17 +02006457 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006458 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006459 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006460 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006461 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006462 endinpos = end-starts;
6463 reason = "truncated input";
6464 goto error;
6465 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006466 /* We copy the raw representation one byte at a time because the
6467 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006468 ((char *) &uch)[0] = s[0];
6469 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006470#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006471 ((char *) &uch)[2] = s[2];
6472 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006473#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006474 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006475#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006476 /* We have to sanity check the raw data, otherwise doom looms for
6477 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006478 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006479 endinpos = s - starts + Py_UNICODE_SIZE;
6480 reason = "illegal code point (> 0x10FFFF)";
6481 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006482 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006483#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006484 s += Py_UNICODE_SIZE;
6485#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006486 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006487 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006488 Py_UNICODE uch2;
6489 ((char *) &uch2)[0] = s[0];
6490 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006491 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006492 {
Victor Stinner551ac952011-11-29 22:58:13 +01006493 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006494 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006495 }
6496 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006497#endif
6498
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006499 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006500 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006501 continue;
6502
6503 error:
6504 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006505 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006506 errors, &errorHandler,
6507 "unicode_internal", reason,
6508 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006509 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006510 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006511 }
6512
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006513 Py_XDECREF(errorHandler);
6514 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006515 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006516
Benjamin Peterson29060642009-01-31 22:14:21 +00006517 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006518 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006519 Py_XDECREF(errorHandler);
6520 Py_XDECREF(exc);
6521 return NULL;
6522}
6523
Guido van Rossumd57fd912000-03-10 22:53:23 +00006524/* --- Latin-1 Codec ------------------------------------------------------ */
6525
Alexander Belopolsky40018472011-02-26 01:02:56 +00006526PyObject *
6527PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006528 Py_ssize_t size,
6529 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006530{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006531 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006532 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006533}
6534
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006535/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006536static void
6537make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006538 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006539 PyObject *unicode,
6540 Py_ssize_t startpos, Py_ssize_t endpos,
6541 const char *reason)
6542{
6543 if (*exceptionObject == NULL) {
6544 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006545 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006546 encoding, unicode, startpos, endpos, reason);
6547 }
6548 else {
6549 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6550 goto onError;
6551 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6552 goto onError;
6553 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6554 goto onError;
6555 return;
6556 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006557 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006558 }
6559}
6560
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006561/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006562static void
6563raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006564 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006565 PyObject *unicode,
6566 Py_ssize_t startpos, Py_ssize_t endpos,
6567 const char *reason)
6568{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006569 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006570 encoding, unicode, startpos, endpos, reason);
6571 if (*exceptionObject != NULL)
6572 PyCodec_StrictErrors(*exceptionObject);
6573}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006574
6575/* error handling callback helper:
6576 build arguments, call the callback and check the arguments,
6577 put the result into newpos and return the replacement string, which
6578 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006579static PyObject *
6580unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006581 PyObject **errorHandler,
6582 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006583 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006584 Py_ssize_t startpos, Py_ssize_t endpos,
6585 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006586{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006587 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006588 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006589 PyObject *restuple;
6590 PyObject *resunicode;
6591
6592 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006594 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006595 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006596 }
6597
Benjamin Petersonbac79492012-01-14 13:34:47 -05006598 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006599 return NULL;
6600 len = PyUnicode_GET_LENGTH(unicode);
6601
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006602 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006603 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006604 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006605 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006606
6607 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006608 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006610 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006611 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006612 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 Py_DECREF(restuple);
6614 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006615 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006616 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006617 &resunicode, newpos)) {
6618 Py_DECREF(restuple);
6619 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006620 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006621 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6622 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6623 Py_DECREF(restuple);
6624 return NULL;
6625 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006626 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006627 *newpos = len + *newpos;
6628 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006629 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006630 Py_DECREF(restuple);
6631 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006632 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006633 Py_INCREF(resunicode);
6634 Py_DECREF(restuple);
6635 return resunicode;
6636}
6637
Alexander Belopolsky40018472011-02-26 01:02:56 +00006638static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006639unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006640 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006641 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 /* input state */
6644 Py_ssize_t pos=0, size;
6645 int kind;
6646 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006647 /* pointer into the output */
6648 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006649 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6650 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006651 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006652 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006653 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006654 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006655 /* output object */
6656 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006657
Benjamin Petersonbac79492012-01-14 13:34:47 -05006658 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006659 return NULL;
6660 size = PyUnicode_GET_LENGTH(unicode);
6661 kind = PyUnicode_KIND(unicode);
6662 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006663 /* allocate enough for a simple encoding without
6664 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006665 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006666 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006667
6668 _PyBytesWriter_Init(&writer);
6669 str = _PyBytesWriter_Alloc(&writer, size);
6670 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006671 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006672
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006673 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006674 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006675
Benjamin Peterson29060642009-01-31 22:14:21 +00006676 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006677 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006678 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006679 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006680 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006681 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006682 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006683 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006684 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006685 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006686 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006687 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006688
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006689 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006690 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006691
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006692 /* Only overallocate the buffer if it's not the last write */
6693 writer.overallocate = (collend < size);
6694
Benjamin Peterson29060642009-01-31 22:14:21 +00006695 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006696 if (error_handler == _Py_ERROR_UNKNOWN)
6697 error_handler = get_error_handler(errors);
6698
6699 switch (error_handler) {
6700 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006701 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006702 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006703
6704 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006705 memset(str, '?', collend - collstart);
6706 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006707 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006708 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006709 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006710 break;
Victor Stinner50149202015-09-22 00:26:54 +02006711
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006712 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006713 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006714 writer.min_size -= (collend - collstart);
6715 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006716 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006717 if (str == NULL)
6718 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006719 pos = collend;
6720 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006721
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006722 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006723 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006724 writer.min_size -= (collend - collstart);
6725 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006726 unicode, collstart, collend);
6727 if (str == NULL)
6728 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006729 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006730 break;
Victor Stinner50149202015-09-22 00:26:54 +02006731
Victor Stinnerc3713e92015-09-29 12:32:13 +02006732 case _Py_ERROR_SURROGATEESCAPE:
6733 for (i = collstart; i < collend; ++i) {
6734 ch = PyUnicode_READ(kind, data, i);
6735 if (ch < 0xdc80 || 0xdcff < ch) {
6736 /* Not a UTF-8b surrogate */
6737 break;
6738 }
6739 *str++ = (char)(ch - 0xdc00);
6740 ++pos;
6741 }
6742 if (i >= collend)
6743 break;
6744 collstart = pos;
6745 assert(collstart != collend);
6746 /* fallback to general error handling */
6747
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006749 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6750 encoding, reason, unicode, &exc,
6751 collstart, collend, &newpos);
6752 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006753 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006754
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006755 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006756 writer.min_size -= 1;
6757
Victor Stinner6bd525b2015-10-09 13:10:05 +02006758 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006759 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006760 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006761 PyBytes_AS_STRING(rep),
6762 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006763 if (str == NULL)
6764 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006765 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006766 else {
6767 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006768
Victor Stinner6bd525b2015-10-09 13:10:05 +02006769 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006771
6772 if (PyUnicode_IS_ASCII(rep)) {
6773 /* Fast path: all characters are smaller than limit */
6774 assert(limit >= 128);
6775 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6776 str = _PyBytesWriter_WriteBytes(&writer, str,
6777 PyUnicode_DATA(rep),
6778 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006779 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006780 else {
6781 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6782
6783 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6784 if (str == NULL)
6785 goto onError;
6786
6787 /* check if there is anything unencodable in the
6788 replacement and copy it to the output */
6789 for (i = 0; repsize-->0; ++i, ++str) {
6790 ch = PyUnicode_READ_CHAR(rep, i);
6791 if (ch >= limit) {
6792 raise_encode_exception(&exc, encoding, unicode,
6793 pos, pos+1, reason);
6794 goto onError;
6795 }
6796 *str = (char)ch;
6797 }
6798 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006799 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006800 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006801 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006802 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006803
6804 /* If overallocation was disabled, ensure that it was the last
6805 write. Otherwise, we missed an optimization */
6806 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006807 }
6808 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006809
Victor Stinner50149202015-09-22 00:26:54 +02006810 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006811 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006812 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006813
6814 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006815 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006816 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006817 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006818 Py_XDECREF(exc);
6819 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006820}
6821
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006822/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006823PyObject *
6824PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006825 Py_ssize_t size,
6826 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006827{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006828 PyObject *result;
6829 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6830 if (unicode == NULL)
6831 return NULL;
6832 result = unicode_encode_ucs1(unicode, errors, 256);
6833 Py_DECREF(unicode);
6834 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835}
6836
Alexander Belopolsky40018472011-02-26 01:02:56 +00006837PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006838_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006839{
6840 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006841 PyErr_BadArgument();
6842 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006843 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006844 if (PyUnicode_READY(unicode) == -1)
6845 return NULL;
6846 /* Fast path: if it is a one-byte string, construct
6847 bytes object directly. */
6848 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6849 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6850 PyUnicode_GET_LENGTH(unicode));
6851 /* Non-Latin-1 characters present. Defer to above function to
6852 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006853 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006854}
6855
6856PyObject*
6857PyUnicode_AsLatin1String(PyObject *unicode)
6858{
6859 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006860}
6861
6862/* --- 7-bit ASCII Codec -------------------------------------------------- */
6863
Alexander Belopolsky40018472011-02-26 01:02:56 +00006864PyObject *
6865PyUnicode_DecodeASCII(const char *s,
6866 Py_ssize_t size,
6867 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006868{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006869 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006870 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006871 int kind;
6872 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006873 Py_ssize_t startinpos;
6874 Py_ssize_t endinpos;
6875 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006876 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006877 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006878 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006879 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006880
Guido van Rossumd57fd912000-03-10 22:53:23 +00006881 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006882 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006883
Guido van Rossumd57fd912000-03-10 22:53:23 +00006884 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006885 if (size == 1 && (unsigned char)s[0] < 128)
6886 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006887
Victor Stinner8f674cc2013-04-17 23:02:17 +02006888 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006889 writer.min_length = size;
6890 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006891 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006892
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006893 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006894 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006895 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006896 writer.pos = outpos;
6897 if (writer.pos == size)
6898 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006899
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006900 s += writer.pos;
6901 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006902 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006903 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006904 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006905 PyUnicode_WRITE(kind, data, writer.pos, c);
6906 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006907 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006908 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006909 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006910
6911 /* byte outsize range 0x00..0x7f: call the error handler */
6912
6913 if (error_handler == _Py_ERROR_UNKNOWN)
6914 error_handler = get_error_handler(errors);
6915
6916 switch (error_handler)
6917 {
6918 case _Py_ERROR_REPLACE:
6919 case _Py_ERROR_SURROGATEESCAPE:
6920 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006921 but we may switch to UCS2 at the first write */
6922 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6923 goto onError;
6924 kind = writer.kind;
6925 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006926
6927 if (error_handler == _Py_ERROR_REPLACE)
6928 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6929 else
6930 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6931 writer.pos++;
6932 ++s;
6933 break;
6934
6935 case _Py_ERROR_IGNORE:
6936 ++s;
6937 break;
6938
6939 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006940 startinpos = s-starts;
6941 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006942 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006943 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006944 "ascii", "ordinal not in range(128)",
6945 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006946 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006947 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006948 kind = writer.kind;
6949 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006950 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006951 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006952 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006953 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006954 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006955
Benjamin Peterson29060642009-01-31 22:14:21 +00006956 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006957 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006958 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006959 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006960 return NULL;
6961}
6962
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006963/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006964PyObject *
6965PyUnicode_EncodeASCII(const Py_UNICODE *p,
6966 Py_ssize_t size,
6967 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006968{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006969 PyObject *result;
6970 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6971 if (unicode == NULL)
6972 return NULL;
6973 result = unicode_encode_ucs1(unicode, errors, 128);
6974 Py_DECREF(unicode);
6975 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006976}
6977
Alexander Belopolsky40018472011-02-26 01:02:56 +00006978PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006979_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006980{
6981 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006982 PyErr_BadArgument();
6983 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006984 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006985 if (PyUnicode_READY(unicode) == -1)
6986 return NULL;
6987 /* Fast path: if it is an ASCII-only string, construct bytes object
6988 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006989 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006990 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6991 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006992 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006993}
6994
6995PyObject *
6996PyUnicode_AsASCIIString(PyObject *unicode)
6997{
6998 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006999}
7000
Victor Stinner99b95382011-07-04 14:23:54 +02007001#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007002
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007003/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007004
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007005#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007006#define NEED_RETRY
7007#endif
7008
Victor Stinner3a50e702011-10-18 21:21:00 +02007009#ifndef WC_ERR_INVALID_CHARS
7010# define WC_ERR_INVALID_CHARS 0x0080
7011#endif
7012
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007013static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007014code_page_name(UINT code_page, PyObject **obj)
7015{
7016 *obj = NULL;
7017 if (code_page == CP_ACP)
7018 return "mbcs";
7019 if (code_page == CP_UTF7)
7020 return "CP_UTF7";
7021 if (code_page == CP_UTF8)
7022 return "CP_UTF8";
7023
7024 *obj = PyBytes_FromFormat("cp%u", code_page);
7025 if (*obj == NULL)
7026 return NULL;
7027 return PyBytes_AS_STRING(*obj);
7028}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007029
Victor Stinner3a50e702011-10-18 21:21:00 +02007030static DWORD
7031decode_code_page_flags(UINT code_page)
7032{
7033 if (code_page == CP_UTF7) {
7034 /* The CP_UTF7 decoder only supports flags=0 */
7035 return 0;
7036 }
7037 else
7038 return MB_ERR_INVALID_CHARS;
7039}
7040
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007041/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007042 * Decode a byte string from a Windows code page into unicode object in strict
7043 * mode.
7044 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007045 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7046 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007047 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007048static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007049decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007050 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007051 const char *in,
7052 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007053{
Victor Stinner3a50e702011-10-18 21:21:00 +02007054 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007055 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007056 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007057
7058 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007059 assert(insize > 0);
7060 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7061 if (outsize <= 0)
7062 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063
7064 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007065 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007066 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007067 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007068 if (*v == NULL)
7069 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007070 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007071 }
7072 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007073 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007074 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007075 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007076 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007077 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007078 }
7079
7080 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007081 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7082 if (outsize <= 0)
7083 goto error;
7084 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007085
Victor Stinner3a50e702011-10-18 21:21:00 +02007086error:
7087 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7088 return -2;
7089 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007090 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007091}
7092
Victor Stinner3a50e702011-10-18 21:21:00 +02007093/*
7094 * Decode a byte string from a code page into unicode object with an error
7095 * handler.
7096 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007097 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007098 * UnicodeDecodeError exception and returns -1 on error.
7099 */
7100static int
7101decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007102 PyObject **v,
7103 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007104 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007105{
7106 const char *startin = in;
7107 const char *endin = in + size;
7108 const DWORD flags = decode_code_page_flags(code_page);
7109 /* Ideally, we should get reason from FormatMessage. This is the Windows
7110 2000 English version of the message. */
7111 const char *reason = "No mapping for the Unicode character exists "
7112 "in the target code page.";
7113 /* each step cannot decode more than 1 character, but a character can be
7114 represented as a surrogate pair */
7115 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007116 int insize;
7117 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007118 PyObject *errorHandler = NULL;
7119 PyObject *exc = NULL;
7120 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007121 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007122 DWORD err;
7123 int ret = -1;
7124
7125 assert(size > 0);
7126
7127 encoding = code_page_name(code_page, &encoding_obj);
7128 if (encoding == NULL)
7129 return -1;
7130
Victor Stinner7d00cc12014-03-17 23:08:06 +01007131 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007132 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7133 UnicodeDecodeError. */
7134 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7135 if (exc != NULL) {
7136 PyCodec_StrictErrors(exc);
7137 Py_CLEAR(exc);
7138 }
7139 goto error;
7140 }
7141
7142 if (*v == NULL) {
7143 /* Create unicode object */
7144 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7145 PyErr_NoMemory();
7146 goto error;
7147 }
Victor Stinnerab595942011-12-17 04:59:06 +01007148 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007149 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007150 if (*v == NULL)
7151 goto error;
7152 startout = PyUnicode_AS_UNICODE(*v);
7153 }
7154 else {
7155 /* Extend unicode object */
7156 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7157 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7158 PyErr_NoMemory();
7159 goto error;
7160 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007161 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007162 goto error;
7163 startout = PyUnicode_AS_UNICODE(*v) + n;
7164 }
7165
7166 /* Decode the byte string character per character */
7167 out = startout;
7168 while (in < endin)
7169 {
7170 /* Decode a character */
7171 insize = 1;
7172 do
7173 {
7174 outsize = MultiByteToWideChar(code_page, flags,
7175 in, insize,
7176 buffer, Py_ARRAY_LENGTH(buffer));
7177 if (outsize > 0)
7178 break;
7179 err = GetLastError();
7180 if (err != ERROR_NO_UNICODE_TRANSLATION
7181 && err != ERROR_INSUFFICIENT_BUFFER)
7182 {
7183 PyErr_SetFromWindowsErr(0);
7184 goto error;
7185 }
7186 insize++;
7187 }
7188 /* 4=maximum length of a UTF-8 sequence */
7189 while (insize <= 4 && (in + insize) <= endin);
7190
7191 if (outsize <= 0) {
7192 Py_ssize_t startinpos, endinpos, outpos;
7193
Victor Stinner7d00cc12014-03-17 23:08:06 +01007194 /* last character in partial decode? */
7195 if (in + insize >= endin && !final)
7196 break;
7197
Victor Stinner3a50e702011-10-18 21:21:00 +02007198 startinpos = in - startin;
7199 endinpos = startinpos + 1;
7200 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007201 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007202 errors, &errorHandler,
7203 encoding, reason,
7204 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007205 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007206 {
7207 goto error;
7208 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007209 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007210 }
7211 else {
7212 in += insize;
7213 memcpy(out, buffer, outsize * sizeof(wchar_t));
7214 out += outsize;
7215 }
7216 }
7217
7218 /* write a NUL character at the end */
7219 *out = 0;
7220
7221 /* Extend unicode object */
7222 outsize = out - startout;
7223 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007224 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007225 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007226 /* (in - startin) <= size and size is an int */
7227 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007228
7229error:
7230 Py_XDECREF(encoding_obj);
7231 Py_XDECREF(errorHandler);
7232 Py_XDECREF(exc);
7233 return ret;
7234}
7235
Victor Stinner3a50e702011-10-18 21:21:00 +02007236static PyObject *
7237decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007238 const char *s, Py_ssize_t size,
7239 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007240{
Victor Stinner76a31a62011-11-04 00:05:13 +01007241 PyObject *v = NULL;
7242 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007243
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 if (code_page < 0) {
7245 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7246 return NULL;
7247 }
7248
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007249 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007250 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007251
Victor Stinner76a31a62011-11-04 00:05:13 +01007252 do
7253 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007254#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007255 if (size > INT_MAX) {
7256 chunk_size = INT_MAX;
7257 final = 0;
7258 done = 0;
7259 }
7260 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007261#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007262 {
7263 chunk_size = (int)size;
7264 final = (consumed == NULL);
7265 done = 1;
7266 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007267
Victor Stinner76a31a62011-11-04 00:05:13 +01007268 if (chunk_size == 0 && done) {
7269 if (v != NULL)
7270 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007271 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007272 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007273
Victor Stinner76a31a62011-11-04 00:05:13 +01007274 converted = decode_code_page_strict(code_page, &v,
7275 s, chunk_size);
7276 if (converted == -2)
7277 converted = decode_code_page_errors(code_page, &v,
7278 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007279 errors, final);
7280 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007281
7282 if (converted < 0) {
7283 Py_XDECREF(v);
7284 return NULL;
7285 }
7286
7287 if (consumed)
7288 *consumed += converted;
7289
7290 s += converted;
7291 size -= converted;
7292 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007293
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007294 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007295}
7296
Alexander Belopolsky40018472011-02-26 01:02:56 +00007297PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007298PyUnicode_DecodeCodePageStateful(int code_page,
7299 const char *s,
7300 Py_ssize_t size,
7301 const char *errors,
7302 Py_ssize_t *consumed)
7303{
7304 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7305}
7306
7307PyObject *
7308PyUnicode_DecodeMBCSStateful(const char *s,
7309 Py_ssize_t size,
7310 const char *errors,
7311 Py_ssize_t *consumed)
7312{
7313 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7314}
7315
7316PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007317PyUnicode_DecodeMBCS(const char *s,
7318 Py_ssize_t size,
7319 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007320{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007321 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7322}
7323
Victor Stinner3a50e702011-10-18 21:21:00 +02007324static DWORD
7325encode_code_page_flags(UINT code_page, const char *errors)
7326{
7327 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007328 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007329 }
7330 else if (code_page == CP_UTF7) {
7331 /* CP_UTF7 only supports flags=0 */
7332 return 0;
7333 }
7334 else {
7335 if (errors != NULL && strcmp(errors, "replace") == 0)
7336 return 0;
7337 else
7338 return WC_NO_BEST_FIT_CHARS;
7339 }
7340}
7341
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007342/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007343 * Encode a Unicode string to a Windows code page into a byte string in strict
7344 * mode.
7345 *
7346 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007347 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007348 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007349static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007350encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007351 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007352 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007353{
Victor Stinner554f3f02010-06-16 23:33:54 +00007354 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 BOOL *pusedDefaultChar = &usedDefaultChar;
7356 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007357 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007358 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007359 const DWORD flags = encode_code_page_flags(code_page, NULL);
7360 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007361 /* Create a substring so that we can get the UTF-16 representation
7362 of just the slice under consideration. */
7363 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007364
Martin v. Löwis3d325192011-11-04 18:23:06 +01007365 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007366
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007368 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007369 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007370 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007371
Victor Stinner2fc507f2011-11-04 20:06:39 +01007372 substring = PyUnicode_Substring(unicode, offset, offset+len);
7373 if (substring == NULL)
7374 return -1;
7375 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7376 if (p == NULL) {
7377 Py_DECREF(substring);
7378 return -1;
7379 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007380 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007381
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007382 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007383 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007384 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007385 NULL, 0,
7386 NULL, pusedDefaultChar);
7387 if (outsize <= 0)
7388 goto error;
7389 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007390 if (pusedDefaultChar && *pusedDefaultChar) {
7391 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007393 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007394
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007396 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007397 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007398 if (*outbytes == NULL) {
7399 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007400 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007401 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007402 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007403 }
7404 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007405 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 const Py_ssize_t n = PyBytes_Size(*outbytes);
7407 if (outsize > PY_SSIZE_T_MAX - n) {
7408 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007409 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007410 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007412 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7413 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007414 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007415 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007417 }
7418
7419 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007421 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007422 out, outsize,
7423 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007424 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007425 if (outsize <= 0)
7426 goto error;
7427 if (pusedDefaultChar && *pusedDefaultChar)
7428 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007429 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007430
Victor Stinner3a50e702011-10-18 21:21:00 +02007431error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007432 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007433 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7434 return -2;
7435 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007436 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007437}
7438
Victor Stinner3a50e702011-10-18 21:21:00 +02007439/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007440 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007441 * error handler.
7442 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007443 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 * -1 on other error.
7445 */
7446static int
7447encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007448 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007449 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007450{
Victor Stinner3a50e702011-10-18 21:21:00 +02007451 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007452 Py_ssize_t pos = unicode_offset;
7453 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 /* Ideally, we should get reason from FormatMessage. This is the Windows
7455 2000 English version of the message. */
7456 const char *reason = "invalid character";
7457 /* 4=maximum length of a UTF-8 sequence */
7458 char buffer[4];
7459 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7460 Py_ssize_t outsize;
7461 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007462 PyObject *errorHandler = NULL;
7463 PyObject *exc = NULL;
7464 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007465 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007466 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007467 PyObject *rep;
7468 int ret = -1;
7469
7470 assert(insize > 0);
7471
7472 encoding = code_page_name(code_page, &encoding_obj);
7473 if (encoding == NULL)
7474 return -1;
7475
7476 if (errors == NULL || strcmp(errors, "strict") == 0) {
7477 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7478 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007479 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007480 if (exc != NULL) {
7481 PyCodec_StrictErrors(exc);
7482 Py_DECREF(exc);
7483 }
7484 Py_XDECREF(encoding_obj);
7485 return -1;
7486 }
7487
7488 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7489 pusedDefaultChar = &usedDefaultChar;
7490 else
7491 pusedDefaultChar = NULL;
7492
7493 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7494 PyErr_NoMemory();
7495 goto error;
7496 }
7497 outsize = insize * Py_ARRAY_LENGTH(buffer);
7498
7499 if (*outbytes == NULL) {
7500 /* Create string object */
7501 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7502 if (*outbytes == NULL)
7503 goto error;
7504 out = PyBytes_AS_STRING(*outbytes);
7505 }
7506 else {
7507 /* Extend string object */
7508 Py_ssize_t n = PyBytes_Size(*outbytes);
7509 if (n > PY_SSIZE_T_MAX - outsize) {
7510 PyErr_NoMemory();
7511 goto error;
7512 }
7513 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7514 goto error;
7515 out = PyBytes_AS_STRING(*outbytes) + n;
7516 }
7517
7518 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007519 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007520 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007521 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7522 wchar_t chars[2];
7523 int charsize;
7524 if (ch < 0x10000) {
7525 chars[0] = (wchar_t)ch;
7526 charsize = 1;
7527 }
7528 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007529 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7530 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007531 charsize = 2;
7532 }
7533
Victor Stinner3a50e702011-10-18 21:21:00 +02007534 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007535 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007536 buffer, Py_ARRAY_LENGTH(buffer),
7537 NULL, pusedDefaultChar);
7538 if (outsize > 0) {
7539 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7540 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007541 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007542 memcpy(out, buffer, outsize);
7543 out += outsize;
7544 continue;
7545 }
7546 }
7547 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7548 PyErr_SetFromWindowsErr(0);
7549 goto error;
7550 }
7551
Victor Stinner3a50e702011-10-18 21:21:00 +02007552 rep = unicode_encode_call_errorhandler(
7553 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007554 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007555 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007556 if (rep == NULL)
7557 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007558 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007559
7560 if (PyBytes_Check(rep)) {
7561 outsize = PyBytes_GET_SIZE(rep);
7562 if (outsize != 1) {
7563 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7564 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7565 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7566 Py_DECREF(rep);
7567 goto error;
7568 }
7569 out = PyBytes_AS_STRING(*outbytes) + offset;
7570 }
7571 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7572 out += outsize;
7573 }
7574 else {
7575 Py_ssize_t i;
7576 enum PyUnicode_Kind kind;
7577 void *data;
7578
Benjamin Petersonbac79492012-01-14 13:34:47 -05007579 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007580 Py_DECREF(rep);
7581 goto error;
7582 }
7583
7584 outsize = PyUnicode_GET_LENGTH(rep);
7585 if (outsize != 1) {
7586 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7587 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7588 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7589 Py_DECREF(rep);
7590 goto error;
7591 }
7592 out = PyBytes_AS_STRING(*outbytes) + offset;
7593 }
7594 kind = PyUnicode_KIND(rep);
7595 data = PyUnicode_DATA(rep);
7596 for (i=0; i < outsize; i++) {
7597 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7598 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007599 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007600 encoding, unicode,
7601 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007602 "unable to encode error handler result to ASCII");
7603 Py_DECREF(rep);
7604 goto error;
7605 }
7606 *out = (unsigned char)ch;
7607 out++;
7608 }
7609 }
7610 Py_DECREF(rep);
7611 }
7612 /* write a NUL byte */
7613 *out = 0;
7614 outsize = out - PyBytes_AS_STRING(*outbytes);
7615 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7616 if (_PyBytes_Resize(outbytes, outsize) < 0)
7617 goto error;
7618 ret = 0;
7619
7620error:
7621 Py_XDECREF(encoding_obj);
7622 Py_XDECREF(errorHandler);
7623 Py_XDECREF(exc);
7624 return ret;
7625}
7626
Victor Stinner3a50e702011-10-18 21:21:00 +02007627static PyObject *
7628encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007629 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007630 const char *errors)
7631{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007632 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007633 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007634 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007635 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007636
Victor Stinner29dacf22015-01-26 16:41:32 +01007637 if (!PyUnicode_Check(unicode)) {
7638 PyErr_BadArgument();
7639 return NULL;
7640 }
7641
Benjamin Petersonbac79492012-01-14 13:34:47 -05007642 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007643 return NULL;
7644 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007645
Victor Stinner3a50e702011-10-18 21:21:00 +02007646 if (code_page < 0) {
7647 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7648 return NULL;
7649 }
7650
Martin v. Löwis3d325192011-11-04 18:23:06 +01007651 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007652 return PyBytes_FromStringAndSize(NULL, 0);
7653
Victor Stinner7581cef2011-11-03 22:32:33 +01007654 offset = 0;
7655 do
7656 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007657#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007658 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007659 chunks. */
7660 if (len > INT_MAX/2) {
7661 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007662 done = 0;
7663 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007664 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007665#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007666 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007667 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007668 done = 1;
7669 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007670
Victor Stinner76a31a62011-11-04 00:05:13 +01007671 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007672 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007673 errors);
7674 if (ret == -2)
7675 ret = encode_code_page_errors(code_page, &outbytes,
7676 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007677 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007678 if (ret < 0) {
7679 Py_XDECREF(outbytes);
7680 return NULL;
7681 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007682
Victor Stinner7581cef2011-11-03 22:32:33 +01007683 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007684 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007685 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007686
Victor Stinner3a50e702011-10-18 21:21:00 +02007687 return outbytes;
7688}
7689
7690PyObject *
7691PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7692 Py_ssize_t size,
7693 const char *errors)
7694{
Victor Stinner7581cef2011-11-03 22:32:33 +01007695 PyObject *unicode, *res;
7696 unicode = PyUnicode_FromUnicode(p, size);
7697 if (unicode == NULL)
7698 return NULL;
7699 res = encode_code_page(CP_ACP, unicode, errors);
7700 Py_DECREF(unicode);
7701 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007702}
7703
7704PyObject *
7705PyUnicode_EncodeCodePage(int code_page,
7706 PyObject *unicode,
7707 const char *errors)
7708{
Victor Stinner7581cef2011-11-03 22:32:33 +01007709 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007710}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007711
Alexander Belopolsky40018472011-02-26 01:02:56 +00007712PyObject *
7713PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007714{
Victor Stinner7581cef2011-11-03 22:32:33 +01007715 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007716}
7717
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007718#undef NEED_RETRY
7719
Victor Stinner99b95382011-07-04 14:23:54 +02007720#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007721
Guido van Rossumd57fd912000-03-10 22:53:23 +00007722/* --- Character Mapping Codec -------------------------------------------- */
7723
Victor Stinnerfb161b12013-04-18 01:44:27 +02007724static int
7725charmap_decode_string(const char *s,
7726 Py_ssize_t size,
7727 PyObject *mapping,
7728 const char *errors,
7729 _PyUnicodeWriter *writer)
7730{
7731 const char *starts = s;
7732 const char *e;
7733 Py_ssize_t startinpos, endinpos;
7734 PyObject *errorHandler = NULL, *exc = NULL;
7735 Py_ssize_t maplen;
7736 enum PyUnicode_Kind mapkind;
7737 void *mapdata;
7738 Py_UCS4 x;
7739 unsigned char ch;
7740
7741 if (PyUnicode_READY(mapping) == -1)
7742 return -1;
7743
7744 maplen = PyUnicode_GET_LENGTH(mapping);
7745 mapdata = PyUnicode_DATA(mapping);
7746 mapkind = PyUnicode_KIND(mapping);
7747
7748 e = s + size;
7749
7750 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7751 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7752 * is disabled in encoding aliases, latin1 is preferred because
7753 * its implementation is faster. */
7754 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7755 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7756 Py_UCS4 maxchar = writer->maxchar;
7757
7758 assert (writer->kind == PyUnicode_1BYTE_KIND);
7759 while (s < e) {
7760 ch = *s;
7761 x = mapdata_ucs1[ch];
7762 if (x > maxchar) {
7763 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7764 goto onError;
7765 maxchar = writer->maxchar;
7766 outdata = (Py_UCS1 *)writer->data;
7767 }
7768 outdata[writer->pos] = x;
7769 writer->pos++;
7770 ++s;
7771 }
7772 return 0;
7773 }
7774
7775 while (s < e) {
7776 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7777 enum PyUnicode_Kind outkind = writer->kind;
7778 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7779 if (outkind == PyUnicode_1BYTE_KIND) {
7780 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7781 Py_UCS4 maxchar = writer->maxchar;
7782 while (s < e) {
7783 ch = *s;
7784 x = mapdata_ucs2[ch];
7785 if (x > maxchar)
7786 goto Error;
7787 outdata[writer->pos] = x;
7788 writer->pos++;
7789 ++s;
7790 }
7791 break;
7792 }
7793 else if (outkind == PyUnicode_2BYTE_KIND) {
7794 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7795 while (s < e) {
7796 ch = *s;
7797 x = mapdata_ucs2[ch];
7798 if (x == 0xFFFE)
7799 goto Error;
7800 outdata[writer->pos] = x;
7801 writer->pos++;
7802 ++s;
7803 }
7804 break;
7805 }
7806 }
7807 ch = *s;
7808
7809 if (ch < maplen)
7810 x = PyUnicode_READ(mapkind, mapdata, ch);
7811 else
7812 x = 0xfffe; /* invalid value */
7813Error:
7814 if (x == 0xfffe)
7815 {
7816 /* undefined mapping */
7817 startinpos = s-starts;
7818 endinpos = startinpos+1;
7819 if (unicode_decode_call_errorhandler_writer(
7820 errors, &errorHandler,
7821 "charmap", "character maps to <undefined>",
7822 &starts, &e, &startinpos, &endinpos, &exc, &s,
7823 writer)) {
7824 goto onError;
7825 }
7826 continue;
7827 }
7828
7829 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7830 goto onError;
7831 ++s;
7832 }
7833 Py_XDECREF(errorHandler);
7834 Py_XDECREF(exc);
7835 return 0;
7836
7837onError:
7838 Py_XDECREF(errorHandler);
7839 Py_XDECREF(exc);
7840 return -1;
7841}
7842
7843static int
7844charmap_decode_mapping(const char *s,
7845 Py_ssize_t size,
7846 PyObject *mapping,
7847 const char *errors,
7848 _PyUnicodeWriter *writer)
7849{
7850 const char *starts = s;
7851 const char *e;
7852 Py_ssize_t startinpos, endinpos;
7853 PyObject *errorHandler = NULL, *exc = NULL;
7854 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007855 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007856
7857 e = s + size;
7858
7859 while (s < e) {
7860 ch = *s;
7861
7862 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7863 key = PyLong_FromLong((long)ch);
7864 if (key == NULL)
7865 goto onError;
7866
7867 item = PyObject_GetItem(mapping, key);
7868 Py_DECREF(key);
7869 if (item == NULL) {
7870 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7871 /* No mapping found means: mapping is undefined. */
7872 PyErr_Clear();
7873 goto Undefined;
7874 } else
7875 goto onError;
7876 }
7877
7878 /* Apply mapping */
7879 if (item == Py_None)
7880 goto Undefined;
7881 if (PyLong_Check(item)) {
7882 long value = PyLong_AS_LONG(item);
7883 if (value == 0xFFFE)
7884 goto Undefined;
7885 if (value < 0 || value > MAX_UNICODE) {
7886 PyErr_Format(PyExc_TypeError,
7887 "character mapping must be in range(0x%lx)",
7888 (unsigned long)MAX_UNICODE + 1);
7889 goto onError;
7890 }
7891
7892 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7893 goto onError;
7894 }
7895 else if (PyUnicode_Check(item)) {
7896 if (PyUnicode_READY(item) == -1)
7897 goto onError;
7898 if (PyUnicode_GET_LENGTH(item) == 1) {
7899 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7900 if (value == 0xFFFE)
7901 goto Undefined;
7902 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7903 goto onError;
7904 }
7905 else {
7906 writer->overallocate = 1;
7907 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7908 goto onError;
7909 }
7910 }
7911 else {
7912 /* wrong return value */
7913 PyErr_SetString(PyExc_TypeError,
7914 "character mapping must return integer, None or str");
7915 goto onError;
7916 }
7917 Py_CLEAR(item);
7918 ++s;
7919 continue;
7920
7921Undefined:
7922 /* undefined mapping */
7923 Py_CLEAR(item);
7924 startinpos = s-starts;
7925 endinpos = startinpos+1;
7926 if (unicode_decode_call_errorhandler_writer(
7927 errors, &errorHandler,
7928 "charmap", "character maps to <undefined>",
7929 &starts, &e, &startinpos, &endinpos, &exc, &s,
7930 writer)) {
7931 goto onError;
7932 }
7933 }
7934 Py_XDECREF(errorHandler);
7935 Py_XDECREF(exc);
7936 return 0;
7937
7938onError:
7939 Py_XDECREF(item);
7940 Py_XDECREF(errorHandler);
7941 Py_XDECREF(exc);
7942 return -1;
7943}
7944
Alexander Belopolsky40018472011-02-26 01:02:56 +00007945PyObject *
7946PyUnicode_DecodeCharmap(const char *s,
7947 Py_ssize_t size,
7948 PyObject *mapping,
7949 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007950{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007951 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007952
Guido van Rossumd57fd912000-03-10 22:53:23 +00007953 /* Default to Latin-1 */
7954 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007955 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007956
Guido van Rossumd57fd912000-03-10 22:53:23 +00007957 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007958 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007959 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007960 writer.min_length = size;
7961 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007962 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007963
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007964 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007965 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7966 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007967 }
7968 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007969 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7970 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007971 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007972 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007973
Benjamin Peterson29060642009-01-31 22:14:21 +00007974 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007975 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007976 return NULL;
7977}
7978
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007979/* Charmap encoding: the lookup table */
7980
Alexander Belopolsky40018472011-02-26 01:02:56 +00007981struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007982 PyObject_HEAD
7983 unsigned char level1[32];
7984 int count2, count3;
7985 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007986};
7987
7988static PyObject*
7989encoding_map_size(PyObject *obj, PyObject* args)
7990{
7991 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007992 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007993 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007994}
7995
7996static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007997 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007998 PyDoc_STR("Return the size (in bytes) of this object") },
7999 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008000};
8001
8002static void
8003encoding_map_dealloc(PyObject* o)
8004{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008005 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008006}
8007
8008static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008009 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 "EncodingMap", /*tp_name*/
8011 sizeof(struct encoding_map), /*tp_basicsize*/
8012 0, /*tp_itemsize*/
8013 /* methods */
8014 encoding_map_dealloc, /*tp_dealloc*/
8015 0, /*tp_print*/
8016 0, /*tp_getattr*/
8017 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008018 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008019 0, /*tp_repr*/
8020 0, /*tp_as_number*/
8021 0, /*tp_as_sequence*/
8022 0, /*tp_as_mapping*/
8023 0, /*tp_hash*/
8024 0, /*tp_call*/
8025 0, /*tp_str*/
8026 0, /*tp_getattro*/
8027 0, /*tp_setattro*/
8028 0, /*tp_as_buffer*/
8029 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8030 0, /*tp_doc*/
8031 0, /*tp_traverse*/
8032 0, /*tp_clear*/
8033 0, /*tp_richcompare*/
8034 0, /*tp_weaklistoffset*/
8035 0, /*tp_iter*/
8036 0, /*tp_iternext*/
8037 encoding_map_methods, /*tp_methods*/
8038 0, /*tp_members*/
8039 0, /*tp_getset*/
8040 0, /*tp_base*/
8041 0, /*tp_dict*/
8042 0, /*tp_descr_get*/
8043 0, /*tp_descr_set*/
8044 0, /*tp_dictoffset*/
8045 0, /*tp_init*/
8046 0, /*tp_alloc*/
8047 0, /*tp_new*/
8048 0, /*tp_free*/
8049 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008050};
8051
8052PyObject*
8053PyUnicode_BuildEncodingMap(PyObject* string)
8054{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008055 PyObject *result;
8056 struct encoding_map *mresult;
8057 int i;
8058 int need_dict = 0;
8059 unsigned char level1[32];
8060 unsigned char level2[512];
8061 unsigned char *mlevel1, *mlevel2, *mlevel3;
8062 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008063 int kind;
8064 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008065 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008066 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008067
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008068 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008069 PyErr_BadArgument();
8070 return NULL;
8071 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008072 kind = PyUnicode_KIND(string);
8073 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008074 length = PyUnicode_GET_LENGTH(string);
8075 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008076 memset(level1, 0xFF, sizeof level1);
8077 memset(level2, 0xFF, sizeof level2);
8078
8079 /* If there isn't a one-to-one mapping of NULL to \0,
8080 or if there are non-BMP characters, we need to use
8081 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008082 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008083 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008084 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008085 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008086 ch = PyUnicode_READ(kind, data, i);
8087 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008088 need_dict = 1;
8089 break;
8090 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008091 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092 /* unmapped character */
8093 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008094 l1 = ch >> 11;
8095 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008096 if (level1[l1] == 0xFF)
8097 level1[l1] = count2++;
8098 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008099 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008100 }
8101
8102 if (count2 >= 0xFF || count3 >= 0xFF)
8103 need_dict = 1;
8104
8105 if (need_dict) {
8106 PyObject *result = PyDict_New();
8107 PyObject *key, *value;
8108 if (!result)
8109 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008110 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008111 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008112 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113 if (!key || !value)
8114 goto failed1;
8115 if (PyDict_SetItem(result, key, value) == -1)
8116 goto failed1;
8117 Py_DECREF(key);
8118 Py_DECREF(value);
8119 }
8120 return result;
8121 failed1:
8122 Py_XDECREF(key);
8123 Py_XDECREF(value);
8124 Py_DECREF(result);
8125 return NULL;
8126 }
8127
8128 /* Create a three-level trie */
8129 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8130 16*count2 + 128*count3 - 1);
8131 if (!result)
8132 return PyErr_NoMemory();
8133 PyObject_Init(result, &EncodingMapType);
8134 mresult = (struct encoding_map*)result;
8135 mresult->count2 = count2;
8136 mresult->count3 = count3;
8137 mlevel1 = mresult->level1;
8138 mlevel2 = mresult->level23;
8139 mlevel3 = mresult->level23 + 16*count2;
8140 memcpy(mlevel1, level1, 32);
8141 memset(mlevel2, 0xFF, 16*count2);
8142 memset(mlevel3, 0, 128*count3);
8143 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008144 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008145 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008146 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8147 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008148 /* unmapped character */
8149 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008150 o1 = ch>>11;
8151 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008152 i2 = 16*mlevel1[o1] + o2;
8153 if (mlevel2[i2] == 0xFF)
8154 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008155 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008156 i3 = 128*mlevel2[i2] + o3;
8157 mlevel3[i3] = i;
8158 }
8159 return result;
8160}
8161
8162static int
Victor Stinner22168992011-11-20 17:09:18 +01008163encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008164{
8165 struct encoding_map *map = (struct encoding_map*)mapping;
8166 int l1 = c>>11;
8167 int l2 = (c>>7) & 0xF;
8168 int l3 = c & 0x7F;
8169 int i;
8170
Victor Stinner22168992011-11-20 17:09:18 +01008171 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008172 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008173 if (c == 0)
8174 return 0;
8175 /* level 1*/
8176 i = map->level1[l1];
8177 if (i == 0xFF) {
8178 return -1;
8179 }
8180 /* level 2*/
8181 i = map->level23[16*i+l2];
8182 if (i == 0xFF) {
8183 return -1;
8184 }
8185 /* level 3 */
8186 i = map->level23[16*map->count2 + 128*i + l3];
8187 if (i == 0) {
8188 return -1;
8189 }
8190 return i;
8191}
8192
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008193/* Lookup the character ch in the mapping. If the character
8194 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008195 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008196static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008197charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008198{
Christian Heimes217cfd12007-12-02 14:31:20 +00008199 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008200 PyObject *x;
8201
8202 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008203 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008204 x = PyObject_GetItem(mapping, w);
8205 Py_DECREF(w);
8206 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008207 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8208 /* No mapping found means: mapping is undefined. */
8209 PyErr_Clear();
8210 x = Py_None;
8211 Py_INCREF(x);
8212 return x;
8213 } else
8214 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008215 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008216 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008217 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008218 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008219 long value = PyLong_AS_LONG(x);
8220 if (value < 0 || value > 255) {
8221 PyErr_SetString(PyExc_TypeError,
8222 "character mapping must be in range(256)");
8223 Py_DECREF(x);
8224 return NULL;
8225 }
8226 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008227 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008228 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008230 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008231 /* wrong return value */
8232 PyErr_Format(PyExc_TypeError,
8233 "character mapping must return integer, bytes or None, not %.400s",
8234 x->ob_type->tp_name);
8235 Py_DECREF(x);
8236 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008237 }
8238}
8239
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008240static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008241charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008242{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008243 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8244 /* exponentially overallocate to minimize reallocations */
8245 if (requiredsize < 2*outsize)
8246 requiredsize = 2*outsize;
8247 if (_PyBytes_Resize(outobj, requiredsize))
8248 return -1;
8249 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008250}
8251
Benjamin Peterson14339b62009-01-31 16:36:08 +00008252typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008254} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008256 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008257 space is available. Return a new reference to the object that
8258 was put in the output buffer, or Py_None, if the mapping was undefined
8259 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008260 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008261static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008262charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008263 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008264{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008265 PyObject *rep;
8266 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008267 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268
Christian Heimes90aa7642007-12-19 02:45:37 +00008269 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008270 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008271 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008272 if (res == -1)
8273 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 if (outsize<requiredsize)
8275 if (charmapencode_resize(outobj, outpos, requiredsize))
8276 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008277 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 outstart[(*outpos)++] = (char)res;
8279 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008280 }
8281
8282 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008283 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008284 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008285 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008286 Py_DECREF(rep);
8287 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008288 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 if (PyLong_Check(rep)) {
8290 Py_ssize_t requiredsize = *outpos+1;
8291 if (outsize<requiredsize)
8292 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8293 Py_DECREF(rep);
8294 return enc_EXCEPTION;
8295 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008296 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008297 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008298 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 else {
8300 const char *repchars = PyBytes_AS_STRING(rep);
8301 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8302 Py_ssize_t requiredsize = *outpos+repsize;
8303 if (outsize<requiredsize)
8304 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8305 Py_DECREF(rep);
8306 return enc_EXCEPTION;
8307 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008308 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 memcpy(outstart + *outpos, repchars, repsize);
8310 *outpos += repsize;
8311 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008312 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008313 Py_DECREF(rep);
8314 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008315}
8316
8317/* handle an error in PyUnicode_EncodeCharmap
8318 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008319static int
8320charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008321 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008323 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008324 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325{
8326 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008327 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008328 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008329 enum PyUnicode_Kind kind;
8330 void *data;
8331 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008333 Py_ssize_t collstartpos = *inpos;
8334 Py_ssize_t collendpos = *inpos+1;
8335 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008336 char *encoding = "charmap";
8337 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008338 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008339 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008340 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008341
Benjamin Petersonbac79492012-01-14 13:34:47 -05008342 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008343 return -1;
8344 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008345 /* find all unencodable characters */
8346 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008347 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008348 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008349 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008350 val = encoding_map_lookup(ch, mapping);
8351 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 break;
8353 ++collendpos;
8354 continue;
8355 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008356
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008357 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8358 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008359 if (rep==NULL)
8360 return -1;
8361 else if (rep!=Py_None) {
8362 Py_DECREF(rep);
8363 break;
8364 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008365 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367 }
8368 /* cache callback name lookup
8369 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008370 if (*error_handler == _Py_ERROR_UNKNOWN)
8371 *error_handler = get_error_handler(errors);
8372
8373 switch (*error_handler) {
8374 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008375 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008376 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008377
8378 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008379 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 x = charmapencode_output('?', mapping, res, respos);
8381 if (x==enc_EXCEPTION) {
8382 return -1;
8383 }
8384 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008385 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 return -1;
8387 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008388 }
8389 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008390 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008391 *inpos = collendpos;
8392 break;
Victor Stinner50149202015-09-22 00:26:54 +02008393
8394 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008395 /* generate replacement (temporarily (mis)uses p) */
8396 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 char buffer[2+29+1+1];
8398 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008399 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 for (cp = buffer; *cp; ++cp) {
8401 x = charmapencode_output(*cp, mapping, res, respos);
8402 if (x==enc_EXCEPTION)
8403 return -1;
8404 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008405 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 return -1;
8407 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008408 }
8409 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008410 *inpos = collendpos;
8411 break;
Victor Stinner50149202015-09-22 00:26:54 +02008412
Benjamin Peterson14339b62009-01-31 16:36:08 +00008413 default:
Victor Stinner50149202015-09-22 00:26:54 +02008414 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008415 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008417 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008419 if (PyBytes_Check(repunicode)) {
8420 /* Directly copy bytes result to output. */
8421 Py_ssize_t outsize = PyBytes_Size(*res);
8422 Py_ssize_t requiredsize;
8423 repsize = PyBytes_Size(repunicode);
8424 requiredsize = *respos + repsize;
8425 if (requiredsize > outsize)
8426 /* Make room for all additional bytes. */
8427 if (charmapencode_resize(res, respos, requiredsize)) {
8428 Py_DECREF(repunicode);
8429 return -1;
8430 }
8431 memcpy(PyBytes_AsString(*res) + *respos,
8432 PyBytes_AsString(repunicode), repsize);
8433 *respos += repsize;
8434 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008435 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008436 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008437 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008438 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008439 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008440 Py_DECREF(repunicode);
8441 return -1;
8442 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008443 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008444 data = PyUnicode_DATA(repunicode);
8445 kind = PyUnicode_KIND(repunicode);
8446 for (index = 0; index < repsize; index++) {
8447 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8448 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008449 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008450 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 return -1;
8452 }
8453 else if (x==enc_FAILED) {
8454 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008455 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 return -1;
8457 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008458 }
8459 *inpos = newpos;
8460 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008461 }
8462 return 0;
8463}
8464
Alexander Belopolsky40018472011-02-26 01:02:56 +00008465PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008466_PyUnicode_EncodeCharmap(PyObject *unicode,
8467 PyObject *mapping,
8468 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008469{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 /* output object */
8471 PyObject *res = NULL;
8472 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008473 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008474 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008475 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008476 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008477 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008478 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008479 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008480 void *data;
8481 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008482
Benjamin Petersonbac79492012-01-14 13:34:47 -05008483 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008484 return NULL;
8485 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008486 data = PyUnicode_DATA(unicode);
8487 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008488
Guido van Rossumd57fd912000-03-10 22:53:23 +00008489 /* Default to Latin-1 */
8490 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008491 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008492
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008493 /* allocate enough for a simple encoding without
8494 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008495 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 if (res == NULL)
8497 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008498 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008500
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008502 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008504 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 if (x==enc_EXCEPTION) /* error */
8506 goto onError;
8507 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008508 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008510 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008511 &res, &respos)) {
8512 goto onError;
8513 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008514 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008515 else
8516 /* done with this character => adjust input position */
8517 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008518 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008519
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008521 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008522 if (_PyBytes_Resize(&res, respos) < 0)
8523 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008524
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008525 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008526 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 return res;
8528
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008530 Py_XDECREF(res);
8531 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008532 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008533 return NULL;
8534}
8535
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008536/* Deprecated */
8537PyObject *
8538PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8539 Py_ssize_t size,
8540 PyObject *mapping,
8541 const char *errors)
8542{
8543 PyObject *result;
8544 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8545 if (unicode == NULL)
8546 return NULL;
8547 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8548 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008549 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008550}
8551
Alexander Belopolsky40018472011-02-26 01:02:56 +00008552PyObject *
8553PyUnicode_AsCharmapString(PyObject *unicode,
8554 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008555{
8556 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 PyErr_BadArgument();
8558 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008559 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008560 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008561}
8562
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008563/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008564static void
8565make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008567 Py_ssize_t startpos, Py_ssize_t endpos,
8568 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008570 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 *exceptionObject = _PyUnicodeTranslateError_Create(
8572 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008573 }
8574 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008575 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8576 goto onError;
8577 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8578 goto onError;
8579 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8580 goto onError;
8581 return;
8582 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008583 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008584 }
8585}
8586
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587/* error handling callback helper:
8588 build arguments, call the callback and check the arguments,
8589 put the result into newpos and return the replacement string, which
8590 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008591static PyObject *
8592unicode_translate_call_errorhandler(const char *errors,
8593 PyObject **errorHandler,
8594 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008595 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008596 Py_ssize_t startpos, Py_ssize_t endpos,
8597 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008598{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008599 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008600
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008601 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008602 PyObject *restuple;
8603 PyObject *resunicode;
8604
8605 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008606 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008607 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008608 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008609 }
8610
8611 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008613 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008615
8616 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008620 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008621 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008622 Py_DECREF(restuple);
8623 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624 }
8625 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 &resunicode, &i_newpos)) {
8627 Py_DECREF(restuple);
8628 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008629 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008630 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008631 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008632 else
8633 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008635 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 Py_DECREF(restuple);
8637 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008638 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639 Py_INCREF(resunicode);
8640 Py_DECREF(restuple);
8641 return resunicode;
8642}
8643
8644/* Lookup the character ch in the mapping and put the result in result,
8645 which must be decrefed by the caller.
8646 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008647static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649{
Christian Heimes217cfd12007-12-02 14:31:20 +00008650 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008651 PyObject *x;
8652
8653 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008655 x = PyObject_GetItem(mapping, w);
8656 Py_DECREF(w);
8657 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8659 /* No mapping found means: use 1:1 mapping. */
8660 PyErr_Clear();
8661 *result = NULL;
8662 return 0;
8663 } else
8664 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665 }
8666 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 *result = x;
8668 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008670 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008672 if (value < 0 || value > MAX_UNICODE) {
8673 PyErr_Format(PyExc_ValueError,
8674 "character mapping must be in range(0x%x)",
8675 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 Py_DECREF(x);
8677 return -1;
8678 }
8679 *result = x;
8680 return 0;
8681 }
8682 else if (PyUnicode_Check(x)) {
8683 *result = x;
8684 return 0;
8685 }
8686 else {
8687 /* wrong return value */
8688 PyErr_SetString(PyExc_TypeError,
8689 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008690 Py_DECREF(x);
8691 return -1;
8692 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008693}
Victor Stinner1194ea02014-04-04 19:37:40 +02008694
8695/* lookup the character, write the result into the writer.
8696 Return 1 if the result was written into the writer, return 0 if the mapping
8697 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008698static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008699charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8700 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008701{
Victor Stinner1194ea02014-04-04 19:37:40 +02008702 PyObject *item;
8703
8704 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008706
8707 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008708 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008709 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008710 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008712 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008713 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008714
8715 if (item == Py_None) {
8716 Py_DECREF(item);
8717 return 0;
8718 }
8719
8720 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008721 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8722 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8723 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008724 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8725 Py_DECREF(item);
8726 return -1;
8727 }
8728 Py_DECREF(item);
8729 return 1;
8730 }
8731
8732 if (!PyUnicode_Check(item)) {
8733 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008734 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008735 }
8736
8737 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8738 Py_DECREF(item);
8739 return -1;
8740 }
8741
8742 Py_DECREF(item);
8743 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008744}
8745
Victor Stinner89a76ab2014-04-05 11:44:04 +02008746static int
8747unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8748 Py_UCS1 *translate)
8749{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008750 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008751 int ret = 0;
8752
Victor Stinner89a76ab2014-04-05 11:44:04 +02008753 if (charmaptranslate_lookup(ch, mapping, &item)) {
8754 return -1;
8755 }
8756
8757 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008758 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008759 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008760 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008761 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008762 /* not found => default to 1:1 mapping */
8763 translate[ch] = ch;
8764 return 1;
8765 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008766 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008767 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008768 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8769 used it */
8770 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008771 /* invalid character or character outside ASCII:
8772 skip the fast translate */
8773 goto exit;
8774 }
8775 translate[ch] = (Py_UCS1)replace;
8776 }
8777 else if (PyUnicode_Check(item)) {
8778 Py_UCS4 replace;
8779
8780 if (PyUnicode_READY(item) == -1) {
8781 Py_DECREF(item);
8782 return -1;
8783 }
8784 if (PyUnicode_GET_LENGTH(item) != 1)
8785 goto exit;
8786
8787 replace = PyUnicode_READ_CHAR(item, 0);
8788 if (replace > 127)
8789 goto exit;
8790 translate[ch] = (Py_UCS1)replace;
8791 }
8792 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008793 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008794 goto exit;
8795 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008796 ret = 1;
8797
Benjamin Peterson1365de72014-04-07 20:15:41 -04008798 exit:
8799 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008800 return ret;
8801}
8802
8803/* Fast path for ascii => ascii translation. Return 1 if the whole string
8804 was translated into writer, return 0 if the input string was partially
8805 translated into writer, raise an exception and return -1 on error. */
8806static int
8807unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008808 _PyUnicodeWriter *writer, int ignore,
8809 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008810{
Victor Stinner872b2912014-04-05 14:27:07 +02008811 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008812 Py_ssize_t len;
8813 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008814 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008815
Victor Stinner89a76ab2014-04-05 11:44:04 +02008816 len = PyUnicode_GET_LENGTH(input);
8817
Victor Stinner872b2912014-04-05 14:27:07 +02008818 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008819
8820 in = PyUnicode_1BYTE_DATA(input);
8821 end = in + len;
8822
8823 assert(PyUnicode_IS_ASCII(writer->buffer));
8824 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8825 out = PyUnicode_1BYTE_DATA(writer->buffer);
8826
Victor Stinner872b2912014-04-05 14:27:07 +02008827 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008828 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008829 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008830 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008831 int translate = unicode_fast_translate_lookup(mapping, ch,
8832 ascii_table);
8833 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008834 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008835 if (translate == 0)
8836 goto exit;
8837 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008838 }
Victor Stinner872b2912014-04-05 14:27:07 +02008839 if (ch2 == 0xfe) {
8840 if (ignore)
8841 continue;
8842 goto exit;
8843 }
8844 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008845 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008846 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008847 }
Victor Stinner872b2912014-04-05 14:27:07 +02008848 res = 1;
8849
8850exit:
8851 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008852 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008853 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008854}
8855
Victor Stinner3222da22015-10-01 22:07:32 +02008856static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008857_PyUnicode_TranslateCharmap(PyObject *input,
8858 PyObject *mapping,
8859 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008860{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008861 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008862 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008863 Py_ssize_t size, i;
8864 int kind;
8865 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008866 _PyUnicodeWriter writer;
8867 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008868 char *reason = "character maps to <undefined>";
8869 PyObject *errorHandler = NULL;
8870 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008871 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008872 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008873
Guido van Rossumd57fd912000-03-10 22:53:23 +00008874 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008875 PyErr_BadArgument();
8876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008877 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008878
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008879 if (PyUnicode_READY(input) == -1)
8880 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008881 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008882 kind = PyUnicode_KIND(input);
8883 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008884
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008885 if (size == 0)
8886 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008887
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008888 /* allocate enough for a simple 1:1 translation without
8889 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008890 _PyUnicodeWriter_Init(&writer);
8891 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008892 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008893
Victor Stinner872b2912014-04-05 14:27:07 +02008894 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8895
Victor Stinner33798672016-03-01 21:59:58 +01008896 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008897 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008898 if (PyUnicode_IS_ASCII(input)) {
8899 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8900 if (res < 0) {
8901 _PyUnicodeWriter_Dealloc(&writer);
8902 return NULL;
8903 }
8904 if (res == 1)
8905 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008906 }
Victor Stinner33798672016-03-01 21:59:58 +01008907 else {
8908 i = 0;
8909 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008911 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008912 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008913 int translate;
8914 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8915 Py_ssize_t newpos;
8916 /* startpos for collecting untranslatable chars */
8917 Py_ssize_t collstart;
8918 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008919 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008920
Victor Stinner1194ea02014-04-04 19:37:40 +02008921 ch = PyUnicode_READ(kind, data, i);
8922 translate = charmaptranslate_output(ch, mapping, &writer);
8923 if (translate < 0)
8924 goto onError;
8925
8926 if (translate != 0) {
8927 /* it worked => adjust input pointer */
8928 ++i;
8929 continue;
8930 }
8931
8932 /* untranslatable character */
8933 collstart = i;
8934 collend = i+1;
8935
8936 /* find all untranslatable characters */
8937 while (collend < size) {
8938 PyObject *x;
8939 ch = PyUnicode_READ(kind, data, collend);
8940 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008941 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008942 Py_XDECREF(x);
8943 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008944 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008945 ++collend;
8946 }
8947
8948 if (ignore) {
8949 i = collend;
8950 }
8951 else {
8952 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8953 reason, input, &exc,
8954 collstart, collend, &newpos);
8955 if (repunicode == NULL)
8956 goto onError;
8957 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008958 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008959 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008960 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008961 Py_DECREF(repunicode);
8962 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008963 }
8964 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008965 Py_XDECREF(exc);
8966 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008967 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008968
Benjamin Peterson29060642009-01-31 22:14:21 +00008969 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008970 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008971 Py_XDECREF(exc);
8972 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008973 return NULL;
8974}
8975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008976/* Deprecated. Use PyUnicode_Translate instead. */
8977PyObject *
8978PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8979 Py_ssize_t size,
8980 PyObject *mapping,
8981 const char *errors)
8982{
Christian Heimes5f520f42012-09-11 14:03:25 +02008983 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008984 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8985 if (!unicode)
8986 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008987 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8988 Py_DECREF(unicode);
8989 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008990}
8991
Alexander Belopolsky40018472011-02-26 01:02:56 +00008992PyObject *
8993PyUnicode_Translate(PyObject *str,
8994 PyObject *mapping,
8995 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008996{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008997 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02008998 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008999 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009000}
Tim Petersced69f82003-09-16 20:30:58 +00009001
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009002static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009003fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009004{
9005 /* No need to call PyUnicode_READY(self) because this function is only
9006 called as a callback from fixup() which does it already. */
9007 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9008 const int kind = PyUnicode_KIND(self);
9009 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009010 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009011 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009012 Py_ssize_t i;
9013
9014 for (i = 0; i < len; ++i) {
9015 ch = PyUnicode_READ(kind, data, i);
9016 fixed = 0;
9017 if (ch > 127) {
9018 if (Py_UNICODE_ISSPACE(ch))
9019 fixed = ' ';
9020 else {
9021 const int decimal = Py_UNICODE_TODECIMAL(ch);
9022 if (decimal >= 0)
9023 fixed = '0' + decimal;
9024 }
9025 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009026 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009027 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009028 PyUnicode_WRITE(kind, data, i, fixed);
9029 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009030 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009031 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009032 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009033 }
9034
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009035 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009036}
9037
9038PyObject *
9039_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9040{
9041 if (!PyUnicode_Check(unicode)) {
9042 PyErr_BadInternalCall();
9043 return NULL;
9044 }
9045 if (PyUnicode_READY(unicode) == -1)
9046 return NULL;
9047 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9048 /* If the string is already ASCII, just return the same string */
9049 Py_INCREF(unicode);
9050 return unicode;
9051 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009052 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053}
9054
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009055PyObject *
9056PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9057 Py_ssize_t length)
9058{
Victor Stinnerf0124502011-11-21 23:12:56 +01009059 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009060 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009061 Py_UCS4 maxchar;
9062 enum PyUnicode_Kind kind;
9063 void *data;
9064
Victor Stinner99d7ad02012-02-22 13:37:39 +01009065 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009066 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009067 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009068 if (ch > 127) {
9069 int decimal = Py_UNICODE_TODECIMAL(ch);
9070 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009071 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009072 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009073 }
9074 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009075
9076 /* Copy to a new string */
9077 decimal = PyUnicode_New(length, maxchar);
9078 if (decimal == NULL)
9079 return decimal;
9080 kind = PyUnicode_KIND(decimal);
9081 data = PyUnicode_DATA(decimal);
9082 /* Iterate over code points */
9083 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009084 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009085 if (ch > 127) {
9086 int decimal = Py_UNICODE_TODECIMAL(ch);
9087 if (decimal >= 0)
9088 ch = '0' + decimal;
9089 }
9090 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009092 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009093}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009094/* --- Decimal Encoder ---------------------------------------------------- */
9095
Alexander Belopolsky40018472011-02-26 01:02:56 +00009096int
9097PyUnicode_EncodeDecimal(Py_UNICODE *s,
9098 Py_ssize_t length,
9099 char *output,
9100 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009101{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009102 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009103 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009104 enum PyUnicode_Kind kind;
9105 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009106
9107 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009108 PyErr_BadArgument();
9109 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009110 }
9111
Victor Stinner42bf7752011-11-21 22:52:58 +01009112 unicode = PyUnicode_FromUnicode(s, length);
9113 if (unicode == NULL)
9114 return -1;
9115
Benjamin Petersonbac79492012-01-14 13:34:47 -05009116 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009117 Py_DECREF(unicode);
9118 return -1;
9119 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009120 kind = PyUnicode_KIND(unicode);
9121 data = PyUnicode_DATA(unicode);
9122
Victor Stinnerb84d7232011-11-22 01:50:07 +01009123 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009124 PyObject *exc;
9125 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009126 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009127 Py_ssize_t startpos;
9128
9129 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009130
Benjamin Peterson29060642009-01-31 22:14:21 +00009131 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009132 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009133 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009134 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009135 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009136 decimal = Py_UNICODE_TODECIMAL(ch);
9137 if (decimal >= 0) {
9138 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009139 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009140 continue;
9141 }
9142 if (0 < ch && ch < 256) {
9143 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009144 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009145 continue;
9146 }
Victor Stinner6345be92011-11-25 20:09:01 +01009147
Victor Stinner42bf7752011-11-21 22:52:58 +01009148 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009149 exc = NULL;
9150 raise_encode_exception(&exc, "decimal", unicode,
9151 startpos, startpos+1,
9152 "invalid decimal Unicode string");
9153 Py_XDECREF(exc);
9154 Py_DECREF(unicode);
9155 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009156 }
9157 /* 0-terminate the output string */
9158 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009159 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009160 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009161}
9162
Guido van Rossumd57fd912000-03-10 22:53:23 +00009163/* --- Helpers ------------------------------------------------------------ */
9164
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009165/* helper macro to fixup start/end slice values */
9166#define ADJUST_INDICES(start, end, len) \
9167 if (end > len) \
9168 end = len; \
9169 else if (end < 0) { \
9170 end += len; \
9171 if (end < 0) \
9172 end = 0; \
9173 } \
9174 if (start < 0) { \
9175 start += len; \
9176 if (start < 0) \
9177 start = 0; \
9178 }
9179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009180static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009181any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009183 Py_ssize_t end,
9184 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009185{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009186 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009187 void *buf1, *buf2;
9188 Py_ssize_t len1, len2, result;
9189
9190 kind1 = PyUnicode_KIND(s1);
9191 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009192 if (kind1 < kind2)
9193 return -1;
9194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009195 len1 = PyUnicode_GET_LENGTH(s1);
9196 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009197 ADJUST_INDICES(start, end, len1);
9198 if (end - start < len2)
9199 return -1;
9200
9201 buf1 = PyUnicode_DATA(s1);
9202 buf2 = PyUnicode_DATA(s2);
9203 if (len2 == 1) {
9204 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9205 result = findchar((const char *)buf1 + kind1*start,
9206 kind1, end - start, ch, direction);
9207 if (result == -1)
9208 return -1;
9209 else
9210 return start + result;
9211 }
9212
9213 if (kind2 != kind1) {
9214 buf2 = _PyUnicode_AsKind(s2, kind1);
9215 if (!buf2)
9216 return -2;
9217 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218
Victor Stinner794d5672011-10-10 03:21:36 +02009219 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009220 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009221 case PyUnicode_1BYTE_KIND:
9222 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9223 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9224 else
9225 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9226 break;
9227 case PyUnicode_2BYTE_KIND:
9228 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9229 break;
9230 case PyUnicode_4BYTE_KIND:
9231 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9232 break;
9233 default:
9234 assert(0); result = -2;
9235 }
9236 }
9237 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009238 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009239 case PyUnicode_1BYTE_KIND:
9240 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9241 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9242 else
9243 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9244 break;
9245 case PyUnicode_2BYTE_KIND:
9246 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9247 break;
9248 case PyUnicode_4BYTE_KIND:
9249 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9250 break;
9251 default:
9252 assert(0); result = -2;
9253 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 }
9255
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009256 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009257 PyMem_Free(buf2);
9258
9259 return result;
9260}
9261
9262Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009263_PyUnicode_InsertThousandsGrouping(
9264 PyObject *unicode, Py_ssize_t index,
9265 Py_ssize_t n_buffer,
9266 void *digits, Py_ssize_t n_digits,
9267 Py_ssize_t min_width,
9268 const char *grouping, PyObject *thousands_sep,
9269 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009270{
Victor Stinner41a863c2012-02-24 00:37:51 +01009271 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009272 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009273 Py_ssize_t thousands_sep_len;
9274 Py_ssize_t len;
9275
9276 if (unicode != NULL) {
9277 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009278 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009279 }
9280 else {
9281 kind = PyUnicode_1BYTE_KIND;
9282 data = NULL;
9283 }
9284 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9285 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9286 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9287 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009288 if (thousands_sep_kind < kind) {
9289 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9290 if (!thousands_sep_data)
9291 return -1;
9292 }
9293 else {
9294 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9295 if (!data)
9296 return -1;
9297 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009298 }
9299
Benjamin Petersonead6b532011-12-20 17:23:42 -06009300 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009302 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009303 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009304 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009305 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009306 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009307 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009308 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009309 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009310 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009311 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009312 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009313 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009314 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009315 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009316 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009317 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009318 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009320 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009321 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009322 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009323 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009324 break;
9325 default:
9326 assert(0);
9327 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009328 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009329 if (unicode != NULL && thousands_sep_kind != kind) {
9330 if (thousands_sep_kind < kind)
9331 PyMem_Free(thousands_sep_data);
9332 else
9333 PyMem_Free(data);
9334 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009335 if (unicode == NULL) {
9336 *maxchar = 127;
9337 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009338 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009339 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009340 }
9341 }
9342 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009343}
9344
9345
Alexander Belopolsky40018472011-02-26 01:02:56 +00009346Py_ssize_t
9347PyUnicode_Count(PyObject *str,
9348 PyObject *substr,
9349 Py_ssize_t start,
9350 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009351{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009352 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009353 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009354 void *buf1 = NULL, *buf2 = NULL;
9355 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009356
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009357 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009358 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009359
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009360 kind1 = PyUnicode_KIND(str);
9361 kind2 = PyUnicode_KIND(substr);
9362 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009363 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009364
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009365 len1 = PyUnicode_GET_LENGTH(str);
9366 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009367 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009368 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009369 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009370
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009371 buf1 = PyUnicode_DATA(str);
9372 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009373 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009374 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009375 if (!buf2)
9376 goto onError;
9377 }
9378
9379 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009380 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009381 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009382 result = asciilib_count(
9383 ((Py_UCS1*)buf1) + start, end - start,
9384 buf2, len2, PY_SSIZE_T_MAX
9385 );
9386 else
9387 result = ucs1lib_count(
9388 ((Py_UCS1*)buf1) + start, end - start,
9389 buf2, len2, PY_SSIZE_T_MAX
9390 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009391 break;
9392 case PyUnicode_2BYTE_KIND:
9393 result = ucs2lib_count(
9394 ((Py_UCS2*)buf1) + start, end - start,
9395 buf2, len2, PY_SSIZE_T_MAX
9396 );
9397 break;
9398 case PyUnicode_4BYTE_KIND:
9399 result = ucs4lib_count(
9400 ((Py_UCS4*)buf1) + start, end - start,
9401 buf2, len2, PY_SSIZE_T_MAX
9402 );
9403 break;
9404 default:
9405 assert(0); result = 0;
9406 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009407
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009408 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009409 PyMem_Free(buf2);
9410
Guido van Rossumd57fd912000-03-10 22:53:23 +00009411 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009412 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009413 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414 PyMem_Free(buf2);
9415 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009416}
9417
Alexander Belopolsky40018472011-02-26 01:02:56 +00009418Py_ssize_t
9419PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009420 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009421 Py_ssize_t start,
9422 Py_ssize_t end,
9423 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009424{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009425 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009426 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009427
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009428 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429}
9430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431Py_ssize_t
9432PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9433 Py_ssize_t start, Py_ssize_t end,
9434 int direction)
9435{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009436 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009437 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009438 if (PyUnicode_READY(str) == -1)
9439 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009440 if (start < 0 || end < 0) {
9441 PyErr_SetString(PyExc_IndexError, "string index out of range");
9442 return -2;
9443 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444 if (end > PyUnicode_GET_LENGTH(str))
9445 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009446 if (start >= end)
9447 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009448 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009449 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9450 kind, end-start, ch, direction);
9451 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009453 else
9454 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455}
9456
Alexander Belopolsky40018472011-02-26 01:02:56 +00009457static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009458tailmatch(PyObject *self,
9459 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009460 Py_ssize_t start,
9461 Py_ssize_t end,
9462 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009463{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009464 int kind_self;
9465 int kind_sub;
9466 void *data_self;
9467 void *data_sub;
9468 Py_ssize_t offset;
9469 Py_ssize_t i;
9470 Py_ssize_t end_sub;
9471
9472 if (PyUnicode_READY(self) == -1 ||
9473 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009474 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9477 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009479 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009480
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009481 if (PyUnicode_GET_LENGTH(substring) == 0)
9482 return 1;
9483
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 kind_self = PyUnicode_KIND(self);
9485 data_self = PyUnicode_DATA(self);
9486 kind_sub = PyUnicode_KIND(substring);
9487 data_sub = PyUnicode_DATA(substring);
9488 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9489
9490 if (direction > 0)
9491 offset = end;
9492 else
9493 offset = start;
9494
9495 if (PyUnicode_READ(kind_self, data_self, offset) ==
9496 PyUnicode_READ(kind_sub, data_sub, 0) &&
9497 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9498 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9499 /* If both are of the same kind, memcmp is sufficient */
9500 if (kind_self == kind_sub) {
9501 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009502 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503 data_sub,
9504 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009505 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009507 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 else {
9509 /* We do not need to compare 0 and len(substring)-1 because
9510 the if statement above ensured already that they are equal
9511 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512 for (i = 1; i < end_sub; ++i) {
9513 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9514 PyUnicode_READ(kind_sub, data_sub, i))
9515 return 0;
9516 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009517 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009519 }
9520
9521 return 0;
9522}
9523
Alexander Belopolsky40018472011-02-26 01:02:56 +00009524Py_ssize_t
9525PyUnicode_Tailmatch(PyObject *str,
9526 PyObject *substr,
9527 Py_ssize_t start,
9528 Py_ssize_t end,
9529 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009531 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009532 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009533
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009534 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009535}
9536
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537/* Apply fixfct filter to the Unicode object self and return a
9538 reference to the modified object */
9539
Alexander Belopolsky40018472011-02-26 01:02:56 +00009540static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009541fixup(PyObject *self,
9542 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009543{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 PyObject *u;
9545 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009546 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009547
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009548 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009549 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009550 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009551 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009552
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009553 /* fix functions return the new maximum character in a string,
9554 if the kind of the resulting unicode object does not change,
9555 everything is fine. Otherwise we need to change the string kind
9556 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009557 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009558
9559 if (maxchar_new == 0) {
9560 /* no changes */;
9561 if (PyUnicode_CheckExact(self)) {
9562 Py_DECREF(u);
9563 Py_INCREF(self);
9564 return self;
9565 }
9566 else
9567 return u;
9568 }
9569
Victor Stinnere6abb482012-05-02 01:15:40 +02009570 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009571
Victor Stinnereaab6042011-12-11 22:22:39 +01009572 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009573 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009574
9575 /* In case the maximum character changed, we need to
9576 convert the string to the new category. */
9577 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9578 if (v == NULL) {
9579 Py_DECREF(u);
9580 return NULL;
9581 }
9582 if (maxchar_new > maxchar_old) {
9583 /* If the maxchar increased so that the kind changed, not all
9584 characters are representable anymore and we need to fix the
9585 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009586 _PyUnicode_FastCopyCharacters(v, 0,
9587 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009588 maxchar_old = fixfct(v);
9589 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590 }
9591 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009592 _PyUnicode_FastCopyCharacters(v, 0,
9593 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009594 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009595 Py_DECREF(u);
9596 assert(_PyUnicode_CheckConsistency(v, 1));
9597 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009598}
9599
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009600static PyObject *
9601ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009602{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009603 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9604 char *resdata, *data = PyUnicode_DATA(self);
9605 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009606
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009607 res = PyUnicode_New(len, 127);
9608 if (res == NULL)
9609 return NULL;
9610 resdata = PyUnicode_DATA(res);
9611 if (lower)
9612 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009614 _Py_bytes_upper(resdata, data, len);
9615 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009616}
9617
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009618static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009619handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009620{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009621 Py_ssize_t j;
9622 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009623 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009624 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009625
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009626 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9627
9628 where ! is a negation and \p{xxx} is a character with property xxx.
9629 */
9630 for (j = i - 1; j >= 0; j--) {
9631 c = PyUnicode_READ(kind, data, j);
9632 if (!_PyUnicode_IsCaseIgnorable(c))
9633 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009635 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9636 if (final_sigma) {
9637 for (j = i + 1; j < length; j++) {
9638 c = PyUnicode_READ(kind, data, j);
9639 if (!_PyUnicode_IsCaseIgnorable(c))
9640 break;
9641 }
9642 final_sigma = j == length || !_PyUnicode_IsCased(c);
9643 }
9644 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009645}
9646
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009647static int
9648lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9649 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009651 /* Obscure special case. */
9652 if (c == 0x3A3) {
9653 mapped[0] = handle_capital_sigma(kind, data, length, i);
9654 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009655 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009656 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009657}
9658
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009659static Py_ssize_t
9660do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009661{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009662 Py_ssize_t i, k = 0;
9663 int n_res, j;
9664 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009665
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009666 c = PyUnicode_READ(kind, data, 0);
9667 n_res = _PyUnicode_ToUpperFull(c, mapped);
9668 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009669 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009671 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009672 for (i = 1; i < length; i++) {
9673 c = PyUnicode_READ(kind, data, i);
9674 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9675 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009676 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009677 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009678 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009679 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009680 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009681}
9682
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009683static Py_ssize_t
9684do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9685 Py_ssize_t i, k = 0;
9686
9687 for (i = 0; i < length; i++) {
9688 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9689 int n_res, j;
9690 if (Py_UNICODE_ISUPPER(c)) {
9691 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9692 }
9693 else if (Py_UNICODE_ISLOWER(c)) {
9694 n_res = _PyUnicode_ToUpperFull(c, mapped);
9695 }
9696 else {
9697 n_res = 1;
9698 mapped[0] = c;
9699 }
9700 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009701 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009702 res[k++] = mapped[j];
9703 }
9704 }
9705 return k;
9706}
9707
9708static Py_ssize_t
9709do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9710 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009711{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009712 Py_ssize_t i, k = 0;
9713
9714 for (i = 0; i < length; i++) {
9715 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9716 int n_res, j;
9717 if (lower)
9718 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9719 else
9720 n_res = _PyUnicode_ToUpperFull(c, mapped);
9721 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009722 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009723 res[k++] = mapped[j];
9724 }
9725 }
9726 return k;
9727}
9728
9729static Py_ssize_t
9730do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9731{
9732 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9733}
9734
9735static Py_ssize_t
9736do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9737{
9738 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9739}
9740
Benjamin Petersone51757f2012-01-12 21:10:29 -05009741static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009742do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9743{
9744 Py_ssize_t i, k = 0;
9745
9746 for (i = 0; i < length; i++) {
9747 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9748 Py_UCS4 mapped[3];
9749 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9750 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009751 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009752 res[k++] = mapped[j];
9753 }
9754 }
9755 return k;
9756}
9757
9758static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009759do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9760{
9761 Py_ssize_t i, k = 0;
9762 int previous_is_cased;
9763
9764 previous_is_cased = 0;
9765 for (i = 0; i < length; i++) {
9766 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9767 Py_UCS4 mapped[3];
9768 int n_res, j;
9769
9770 if (previous_is_cased)
9771 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9772 else
9773 n_res = _PyUnicode_ToTitleFull(c, mapped);
9774
9775 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009776 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009777 res[k++] = mapped[j];
9778 }
9779
9780 previous_is_cased = _PyUnicode_IsCased(c);
9781 }
9782 return k;
9783}
9784
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009785static PyObject *
9786case_operation(PyObject *self,
9787 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9788{
9789 PyObject *res = NULL;
9790 Py_ssize_t length, newlength = 0;
9791 int kind, outkind;
9792 void *data, *outdata;
9793 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9794
Benjamin Petersoneea48462012-01-16 14:28:50 -05009795 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009796
9797 kind = PyUnicode_KIND(self);
9798 data = PyUnicode_DATA(self);
9799 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009800 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009801 PyErr_SetString(PyExc_OverflowError, "string is too long");
9802 return NULL;
9803 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009804 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009805 if (tmp == NULL)
9806 return PyErr_NoMemory();
9807 newlength = perform(kind, data, length, tmp, &maxchar);
9808 res = PyUnicode_New(newlength, maxchar);
9809 if (res == NULL)
9810 goto leave;
9811 tmpend = tmp + newlength;
9812 outdata = PyUnicode_DATA(res);
9813 outkind = PyUnicode_KIND(res);
9814 switch (outkind) {
9815 case PyUnicode_1BYTE_KIND:
9816 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9817 break;
9818 case PyUnicode_2BYTE_KIND:
9819 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9820 break;
9821 case PyUnicode_4BYTE_KIND:
9822 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9823 break;
9824 default:
9825 assert(0);
9826 break;
9827 }
9828 leave:
9829 PyMem_FREE(tmp);
9830 return res;
9831}
9832
Tim Peters8ce9f162004-08-27 01:49:32 +00009833PyObject *
9834PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009835{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009836 PyObject *res;
9837 PyObject *fseq;
9838 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009839 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009840
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009841 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009842 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009843 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009844 }
9845
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009846 /* NOTE: the following code can't call back into Python code,
9847 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009848 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009849
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009850 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009851 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009852 res = _PyUnicode_JoinArray(separator, items, seqlen);
9853 Py_DECREF(fseq);
9854 return res;
9855}
9856
9857PyObject *
9858_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9859{
9860 PyObject *res = NULL; /* the result */
9861 PyObject *sep = NULL;
9862 Py_ssize_t seplen;
9863 PyObject *item;
9864 Py_ssize_t sz, i, res_offset;
9865 Py_UCS4 maxchar;
9866 Py_UCS4 item_maxchar;
9867 int use_memcpy;
9868 unsigned char *res_data = NULL, *sep_data = NULL;
9869 PyObject *last_obj;
9870 unsigned int kind = 0;
9871
Tim Peters05eba1f2004-08-27 21:32:02 +00009872 /* If empty sequence, return u"". */
9873 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009874 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009875 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009876
Tim Peters05eba1f2004-08-27 21:32:02 +00009877 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009878 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009879 if (seqlen == 1) {
9880 if (PyUnicode_CheckExact(items[0])) {
9881 res = items[0];
9882 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009883 return res;
9884 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009885 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009886 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009887 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009888 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009889 /* Set up sep and seplen */
9890 if (separator == NULL) {
9891 /* fall back to a blank space separator */
9892 sep = PyUnicode_FromOrdinal(' ');
9893 if (!sep)
9894 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009895 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009896 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009897 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009898 else {
9899 if (!PyUnicode_Check(separator)) {
9900 PyErr_Format(PyExc_TypeError,
9901 "separator: expected str instance,"
9902 " %.80s found",
9903 Py_TYPE(separator)->tp_name);
9904 goto onError;
9905 }
9906 if (PyUnicode_READY(separator))
9907 goto onError;
9908 sep = separator;
9909 seplen = PyUnicode_GET_LENGTH(separator);
9910 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9911 /* inc refcount to keep this code path symmetric with the
9912 above case of a blank separator */
9913 Py_INCREF(sep);
9914 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009915 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009916 }
9917
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009918 /* There are at least two things to join, or else we have a subclass
9919 * of str in the sequence.
9920 * Do a pre-pass to figure out the total amount of space we'll
9921 * need (sz), and see whether all argument are strings.
9922 */
9923 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009924#ifdef Py_DEBUG
9925 use_memcpy = 0;
9926#else
9927 use_memcpy = 1;
9928#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009929 for (i = 0; i < seqlen; i++) {
9930 const Py_ssize_t old_sz = sz;
9931 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009932 if (!PyUnicode_Check(item)) {
9933 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009934 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009935 " %.80s found",
9936 i, Py_TYPE(item)->tp_name);
9937 goto onError;
9938 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009939 if (PyUnicode_READY(item) == -1)
9940 goto onError;
9941 sz += PyUnicode_GET_LENGTH(item);
9942 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009943 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009944 if (i != 0)
9945 sz += seplen;
9946 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9947 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009948 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009949 goto onError;
9950 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009951 if (use_memcpy && last_obj != NULL) {
9952 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9953 use_memcpy = 0;
9954 }
9955 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009956 }
Tim Petersced69f82003-09-16 20:30:58 +00009957
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009958 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009959 if (res == NULL)
9960 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009961
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009962 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009963#ifdef Py_DEBUG
9964 use_memcpy = 0;
9965#else
9966 if (use_memcpy) {
9967 res_data = PyUnicode_1BYTE_DATA(res);
9968 kind = PyUnicode_KIND(res);
9969 if (seplen != 0)
9970 sep_data = PyUnicode_1BYTE_DATA(sep);
9971 }
9972#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009973 if (use_memcpy) {
9974 for (i = 0; i < seqlen; ++i) {
9975 Py_ssize_t itemlen;
9976 item = items[i];
9977
9978 /* Copy item, and maybe the separator. */
9979 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009980 Py_MEMCPY(res_data,
9981 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009982 kind * seplen);
9983 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009984 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009985
9986 itemlen = PyUnicode_GET_LENGTH(item);
9987 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009988 Py_MEMCPY(res_data,
9989 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009990 kind * itemlen);
9991 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009992 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009993 }
9994 assert(res_data == PyUnicode_1BYTE_DATA(res)
9995 + kind * PyUnicode_GET_LENGTH(res));
9996 }
9997 else {
9998 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9999 Py_ssize_t itemlen;
10000 item = items[i];
10001
10002 /* Copy item, and maybe the separator. */
10003 if (i && seplen != 0) {
10004 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10005 res_offset += seplen;
10006 }
10007
10008 itemlen = PyUnicode_GET_LENGTH(item);
10009 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010010 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010011 res_offset += itemlen;
10012 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010013 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010014 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010015 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010016
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010018 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010019 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010020
Benjamin Peterson29060642009-01-31 22:14:21 +000010021 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010022 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010023 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010024 return NULL;
10025}
10026
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010027#define FILL(kind, data, value, start, length) \
10028 do { \
10029 Py_ssize_t i_ = 0; \
10030 assert(kind != PyUnicode_WCHAR_KIND); \
10031 switch ((kind)) { \
10032 case PyUnicode_1BYTE_KIND: { \
10033 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010034 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 break; \
10036 } \
10037 case PyUnicode_2BYTE_KIND: { \
10038 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10039 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10040 break; \
10041 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010042 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10044 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10045 break; \
10046 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010047 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010048 } \
10049 } while (0)
10050
Victor Stinnerd3f08822012-05-29 12:57:52 +020010051void
10052_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10053 Py_UCS4 fill_char)
10054{
10055 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10056 const void *data = PyUnicode_DATA(unicode);
10057 assert(PyUnicode_IS_READY(unicode));
10058 assert(unicode_modifiable(unicode));
10059 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10060 assert(start >= 0);
10061 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10062 FILL(kind, data, fill_char, start, length);
10063}
10064
Victor Stinner3fe55312012-01-04 00:33:50 +010010065Py_ssize_t
10066PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10067 Py_UCS4 fill_char)
10068{
10069 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010070
10071 if (!PyUnicode_Check(unicode)) {
10072 PyErr_BadInternalCall();
10073 return -1;
10074 }
10075 if (PyUnicode_READY(unicode) == -1)
10076 return -1;
10077 if (unicode_check_modifiable(unicode))
10078 return -1;
10079
Victor Stinnerd3f08822012-05-29 12:57:52 +020010080 if (start < 0) {
10081 PyErr_SetString(PyExc_IndexError, "string index out of range");
10082 return -1;
10083 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010084 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10085 PyErr_SetString(PyExc_ValueError,
10086 "fill character is bigger than "
10087 "the string maximum character");
10088 return -1;
10089 }
10090
10091 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10092 length = Py_MIN(maxlen, length);
10093 if (length <= 0)
10094 return 0;
10095
Victor Stinnerd3f08822012-05-29 12:57:52 +020010096 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010097 return length;
10098}
10099
Victor Stinner9310abb2011-10-05 00:59:23 +020010100static PyObject *
10101pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010102 Py_ssize_t left,
10103 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010105{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 PyObject *u;
10107 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010108 int kind;
10109 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010110
10111 if (left < 0)
10112 left = 0;
10113 if (right < 0)
10114 right = 0;
10115
Victor Stinnerc4b49542011-12-11 22:44:26 +010010116 if (left == 0 && right == 0)
10117 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010118
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10120 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010121 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10122 return NULL;
10123 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010125 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010127 if (!u)
10128 return NULL;
10129
10130 kind = PyUnicode_KIND(u);
10131 data = PyUnicode_DATA(u);
10132 if (left)
10133 FILL(kind, data, fill, 0, left);
10134 if (right)
10135 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010136 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010137 assert(_PyUnicode_CheckConsistency(u, 1));
10138 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010139}
10140
Alexander Belopolsky40018472011-02-26 01:02:56 +000010141PyObject *
10142PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010143{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010144 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010145
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010146 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010147 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010148
Benjamin Petersonead6b532011-12-20 17:23:42 -060010149 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010151 if (PyUnicode_IS_ASCII(string))
10152 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010153 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010154 PyUnicode_GET_LENGTH(string), keepends);
10155 else
10156 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010157 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010158 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 break;
10160 case PyUnicode_2BYTE_KIND:
10161 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010162 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 PyUnicode_GET_LENGTH(string), keepends);
10164 break;
10165 case PyUnicode_4BYTE_KIND:
10166 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010167 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 PyUnicode_GET_LENGTH(string), keepends);
10169 break;
10170 default:
10171 assert(0);
10172 list = 0;
10173 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010174 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010175}
10176
Alexander Belopolsky40018472011-02-26 01:02:56 +000010177static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010178split(PyObject *self,
10179 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010180 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010181{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010182 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 void *buf1, *buf2;
10184 Py_ssize_t len1, len2;
10185 PyObject* out;
10186
Guido van Rossumd57fd912000-03-10 22:53:23 +000010187 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010188 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010189
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 if (PyUnicode_READY(self) == -1)
10191 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010194 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010196 if (PyUnicode_IS_ASCII(self))
10197 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010198 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010199 PyUnicode_GET_LENGTH(self), maxcount
10200 );
10201 else
10202 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010203 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010204 PyUnicode_GET_LENGTH(self), maxcount
10205 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 case PyUnicode_2BYTE_KIND:
10207 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010208 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 PyUnicode_GET_LENGTH(self), maxcount
10210 );
10211 case PyUnicode_4BYTE_KIND:
10212 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010213 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 PyUnicode_GET_LENGTH(self), maxcount
10215 );
10216 default:
10217 assert(0);
10218 return NULL;
10219 }
10220
10221 if (PyUnicode_READY(substring) == -1)
10222 return NULL;
10223
10224 kind1 = PyUnicode_KIND(self);
10225 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 len1 = PyUnicode_GET_LENGTH(self);
10227 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010228 if (kind1 < kind2 || len1 < len2) {
10229 out = PyList_New(1);
10230 if (out == NULL)
10231 return NULL;
10232 Py_INCREF(self);
10233 PyList_SET_ITEM(out, 0, self);
10234 return out;
10235 }
10236 buf1 = PyUnicode_DATA(self);
10237 buf2 = PyUnicode_DATA(substring);
10238 if (kind2 != kind1) {
10239 buf2 = _PyUnicode_AsKind(substring, kind1);
10240 if (!buf2)
10241 return NULL;
10242 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010244 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010246 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10247 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010248 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010249 else
10250 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010251 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 break;
10253 case PyUnicode_2BYTE_KIND:
10254 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010255 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 break;
10257 case PyUnicode_4BYTE_KIND:
10258 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010259 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 break;
10261 default:
10262 out = NULL;
10263 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010264 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010265 PyMem_Free(buf2);
10266 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010267}
10268
Alexander Belopolsky40018472011-02-26 01:02:56 +000010269static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010270rsplit(PyObject *self,
10271 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010272 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010273{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010274 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 void *buf1, *buf2;
10276 Py_ssize_t len1, len2;
10277 PyObject* out;
10278
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010279 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010280 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010281
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 if (PyUnicode_READY(self) == -1)
10283 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010284
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010286 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010288 if (PyUnicode_IS_ASCII(self))
10289 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010290 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010291 PyUnicode_GET_LENGTH(self), maxcount
10292 );
10293 else
10294 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010295 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010296 PyUnicode_GET_LENGTH(self), maxcount
10297 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 case PyUnicode_2BYTE_KIND:
10299 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010300 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 PyUnicode_GET_LENGTH(self), maxcount
10302 );
10303 case PyUnicode_4BYTE_KIND:
10304 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010305 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010306 PyUnicode_GET_LENGTH(self), maxcount
10307 );
10308 default:
10309 assert(0);
10310 return NULL;
10311 }
10312
10313 if (PyUnicode_READY(substring) == -1)
10314 return NULL;
10315
10316 kind1 = PyUnicode_KIND(self);
10317 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 len1 = PyUnicode_GET_LENGTH(self);
10319 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010320 if (kind1 < kind2 || len1 < len2) {
10321 out = PyList_New(1);
10322 if (out == NULL)
10323 return NULL;
10324 Py_INCREF(self);
10325 PyList_SET_ITEM(out, 0, self);
10326 return out;
10327 }
10328 buf1 = PyUnicode_DATA(self);
10329 buf2 = PyUnicode_DATA(substring);
10330 if (kind2 != kind1) {
10331 buf2 = _PyUnicode_AsKind(substring, kind1);
10332 if (!buf2)
10333 return NULL;
10334 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010335
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010336 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010338 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10339 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010340 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010341 else
10342 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010343 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 break;
10345 case PyUnicode_2BYTE_KIND:
10346 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010347 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 break;
10349 case PyUnicode_4BYTE_KIND:
10350 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010351 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 break;
10353 default:
10354 out = NULL;
10355 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010356 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010357 PyMem_Free(buf2);
10358 return out;
10359}
10360
10361static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010362anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10363 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010364{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010365 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010367 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10368 return asciilib_find(buf1, len1, buf2, len2, offset);
10369 else
10370 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371 case PyUnicode_2BYTE_KIND:
10372 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10373 case PyUnicode_4BYTE_KIND:
10374 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10375 }
10376 assert(0);
10377 return -1;
10378}
10379
10380static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010381anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10382 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010384 switch (kind) {
10385 case PyUnicode_1BYTE_KIND:
10386 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10387 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10388 else
10389 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10390 case PyUnicode_2BYTE_KIND:
10391 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10392 case PyUnicode_4BYTE_KIND:
10393 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10394 }
10395 assert(0);
10396 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010397}
10398
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010399static void
10400replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10401 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10402{
10403 int kind = PyUnicode_KIND(u);
10404 void *data = PyUnicode_DATA(u);
10405 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10406 if (kind == PyUnicode_1BYTE_KIND) {
10407 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10408 (Py_UCS1 *)data + len,
10409 u1, u2, maxcount);
10410 }
10411 else if (kind == PyUnicode_2BYTE_KIND) {
10412 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10413 (Py_UCS2 *)data + len,
10414 u1, u2, maxcount);
10415 }
10416 else {
10417 assert(kind == PyUnicode_4BYTE_KIND);
10418 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10419 (Py_UCS4 *)data + len,
10420 u1, u2, maxcount);
10421 }
10422}
10423
Alexander Belopolsky40018472011-02-26 01:02:56 +000010424static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425replace(PyObject *self, PyObject *str1,
10426 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010427{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 PyObject *u;
10429 char *sbuf = PyUnicode_DATA(self);
10430 char *buf1 = PyUnicode_DATA(str1);
10431 char *buf2 = PyUnicode_DATA(str2);
10432 int srelease = 0, release1 = 0, release2 = 0;
10433 int skind = PyUnicode_KIND(self);
10434 int kind1 = PyUnicode_KIND(str1);
10435 int kind2 = PyUnicode_KIND(str2);
10436 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10437 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10438 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010439 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010440 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010441
10442 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010443 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010445 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010446
Victor Stinner59de0ee2011-10-07 10:01:28 +020010447 if (str1 == str2)
10448 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010449
Victor Stinner49a0a212011-10-12 23:46:10 +020010450 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010451 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10452 if (maxchar < maxchar_str1)
10453 /* substring too wide to be present */
10454 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010455 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10456 /* Replacing str1 with str2 may cause a maxchar reduction in the
10457 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010458 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010459 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010462 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010464 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010466 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010467 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010468 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010469
Victor Stinner69ed0f42013-04-09 21:48:24 +020010470 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010471 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010472 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010473 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010474 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010476 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010478
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010479 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10480 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010481 }
10482 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483 int rkind = skind;
10484 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010485 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010486
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010487 if (kind1 < rkind) {
10488 /* widen substring */
10489 buf1 = _PyUnicode_AsKind(str1, rkind);
10490 if (!buf1) goto error;
10491 release1 = 1;
10492 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010493 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010494 if (i < 0)
10495 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 if (rkind > kind2) {
10497 /* widen replacement */
10498 buf2 = _PyUnicode_AsKind(str2, rkind);
10499 if (!buf2) goto error;
10500 release2 = 1;
10501 }
10502 else if (rkind < kind2) {
10503 /* widen self and buf1 */
10504 rkind = kind2;
10505 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010506 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010507 sbuf = _PyUnicode_AsKind(self, rkind);
10508 if (!sbuf) goto error;
10509 srelease = 1;
10510 buf1 = _PyUnicode_AsKind(str1, rkind);
10511 if (!buf1) goto error;
10512 release1 = 1;
10513 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010514 u = PyUnicode_New(slen, maxchar);
10515 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010516 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010517 assert(PyUnicode_KIND(u) == rkind);
10518 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010519
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010520 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010521 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010522 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010524 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010525 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010526
10527 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010528 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010529 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010530 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010531 if (i == -1)
10532 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010533 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010535 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010537 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010538 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010539 }
10540 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010542 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 int rkind = skind;
10544 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010547 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010548 buf1 = _PyUnicode_AsKind(str1, rkind);
10549 if (!buf1) goto error;
10550 release1 = 1;
10551 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010552 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010553 if (n == 0)
10554 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010556 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 buf2 = _PyUnicode_AsKind(str2, rkind);
10558 if (!buf2) goto error;
10559 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010562 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 rkind = kind2;
10564 sbuf = _PyUnicode_AsKind(self, rkind);
10565 if (!sbuf) goto error;
10566 srelease = 1;
10567 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010568 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 buf1 = _PyUnicode_AsKind(str1, rkind);
10570 if (!buf1) goto error;
10571 release1 = 1;
10572 }
10573 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10574 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010575 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 PyErr_SetString(PyExc_OverflowError,
10577 "replace string is too long");
10578 goto error;
10579 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010580 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010581 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010582 _Py_INCREF_UNICODE_EMPTY();
10583 if (!unicode_empty)
10584 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010585 u = unicode_empty;
10586 goto done;
10587 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010588 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 PyErr_SetString(PyExc_OverflowError,
10590 "replace string is too long");
10591 goto error;
10592 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010593 u = PyUnicode_New(new_size, maxchar);
10594 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010596 assert(PyUnicode_KIND(u) == rkind);
10597 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 ires = i = 0;
10599 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010600 while (n-- > 0) {
10601 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010602 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010603 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010604 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010605 if (j == -1)
10606 break;
10607 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010608 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010609 memcpy(res + rkind * ires,
10610 sbuf + rkind * i,
10611 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010613 }
10614 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010616 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010618 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010619 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010620 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010621 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010622 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010624 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010625 memcpy(res + rkind * ires,
10626 sbuf + rkind * i,
10627 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010628 }
10629 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010630 /* interleave */
10631 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010632 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010634 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010636 if (--n <= 0)
10637 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010638 memcpy(res + rkind * ires,
10639 sbuf + rkind * i,
10640 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 ires++;
10642 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010643 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010644 memcpy(res + rkind * ires,
10645 sbuf + rkind * i,
10646 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010647 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010648 }
10649
10650 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010651 unicode_adjust_maxchar(&u);
10652 if (u == NULL)
10653 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010655
10656 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 if (srelease)
10658 PyMem_FREE(sbuf);
10659 if (release1)
10660 PyMem_FREE(buf1);
10661 if (release2)
10662 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010663 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010664 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010665
Benjamin Peterson29060642009-01-31 22:14:21 +000010666 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010667 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010668 if (srelease)
10669 PyMem_FREE(sbuf);
10670 if (release1)
10671 PyMem_FREE(buf1);
10672 if (release2)
10673 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010674 return unicode_result_unchanged(self);
10675
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 error:
10677 if (srelease && sbuf)
10678 PyMem_FREE(sbuf);
10679 if (release1 && buf1)
10680 PyMem_FREE(buf1);
10681 if (release2 && buf2)
10682 PyMem_FREE(buf2);
10683 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010684}
10685
10686/* --- Unicode Object Methods --------------------------------------------- */
10687
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010688PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010689 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010690\n\
10691Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010692characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010693
10694static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010695unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010696{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010697 if (PyUnicode_READY(self) == -1)
10698 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010699 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010700}
10701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010702PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010703 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010704\n\
10705Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010706have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010707
10708static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010709unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010710{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010711 if (PyUnicode_READY(self) == -1)
10712 return NULL;
10713 if (PyUnicode_GET_LENGTH(self) == 0)
10714 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010715 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010716}
10717
Benjamin Petersond5890c82012-01-14 13:23:30 -050010718PyDoc_STRVAR(casefold__doc__,
10719 "S.casefold() -> str\n\
10720\n\
10721Return a version of S suitable for caseless comparisons.");
10722
10723static PyObject *
10724unicode_casefold(PyObject *self)
10725{
10726 if (PyUnicode_READY(self) == -1)
10727 return NULL;
10728 if (PyUnicode_IS_ASCII(self))
10729 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010730 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010731}
10732
10733
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010734/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010735
10736static int
10737convert_uc(PyObject *obj, void *addr)
10738{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010739 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010740
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010741 if (!PyUnicode_Check(obj)) {
10742 PyErr_Format(PyExc_TypeError,
10743 "The fill character must be a unicode character, "
10744 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010745 return 0;
10746 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010747 if (PyUnicode_READY(obj) < 0)
10748 return 0;
10749 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010750 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010751 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010752 return 0;
10753 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010754 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010755 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010756}
10757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010758PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010759 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010761Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010762done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763
10764static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010765unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010766{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010767 Py_ssize_t marg, left;
10768 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010769 Py_UCS4 fillchar = ' ';
10770
Victor Stinnere9a29352011-10-01 02:14:59 +020010771 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010772 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773
Benjamin Petersonbac79492012-01-14 13:34:47 -050010774 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010775 return NULL;
10776
Victor Stinnerc4b49542011-12-11 22:44:26 +010010777 if (PyUnicode_GET_LENGTH(self) >= width)
10778 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010779
Victor Stinnerc4b49542011-12-11 22:44:26 +010010780 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010781 left = marg / 2 + (marg & width & 1);
10782
Victor Stinner9310abb2011-10-05 00:59:23 +020010783 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010784}
10785
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786/* This function assumes that str1 and str2 are readied by the caller. */
10787
Marc-André Lemburge5034372000-08-08 08:04:29 +000010788static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010789unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010790{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010791#define COMPARE(TYPE1, TYPE2) \
10792 do { \
10793 TYPE1* p1 = (TYPE1 *)data1; \
10794 TYPE2* p2 = (TYPE2 *)data2; \
10795 TYPE1* end = p1 + len; \
10796 Py_UCS4 c1, c2; \
10797 for (; p1 != end; p1++, p2++) { \
10798 c1 = *p1; \
10799 c2 = *p2; \
10800 if (c1 != c2) \
10801 return (c1 < c2) ? -1 : 1; \
10802 } \
10803 } \
10804 while (0)
10805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 int kind1, kind2;
10807 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010808 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010809
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010810 kind1 = PyUnicode_KIND(str1);
10811 kind2 = PyUnicode_KIND(str2);
10812 data1 = PyUnicode_DATA(str1);
10813 data2 = PyUnicode_DATA(str2);
10814 len1 = PyUnicode_GET_LENGTH(str1);
10815 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010816 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010817
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010818 switch(kind1) {
10819 case PyUnicode_1BYTE_KIND:
10820 {
10821 switch(kind2) {
10822 case PyUnicode_1BYTE_KIND:
10823 {
10824 int cmp = memcmp(data1, data2, len);
10825 /* normalize result of memcmp() into the range [-1; 1] */
10826 if (cmp < 0)
10827 return -1;
10828 if (cmp > 0)
10829 return 1;
10830 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010831 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010832 case PyUnicode_2BYTE_KIND:
10833 COMPARE(Py_UCS1, Py_UCS2);
10834 break;
10835 case PyUnicode_4BYTE_KIND:
10836 COMPARE(Py_UCS1, Py_UCS4);
10837 break;
10838 default:
10839 assert(0);
10840 }
10841 break;
10842 }
10843 case PyUnicode_2BYTE_KIND:
10844 {
10845 switch(kind2) {
10846 case PyUnicode_1BYTE_KIND:
10847 COMPARE(Py_UCS2, Py_UCS1);
10848 break;
10849 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010850 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010851 COMPARE(Py_UCS2, Py_UCS2);
10852 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010853 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010854 case PyUnicode_4BYTE_KIND:
10855 COMPARE(Py_UCS2, Py_UCS4);
10856 break;
10857 default:
10858 assert(0);
10859 }
10860 break;
10861 }
10862 case PyUnicode_4BYTE_KIND:
10863 {
10864 switch(kind2) {
10865 case PyUnicode_1BYTE_KIND:
10866 COMPARE(Py_UCS4, Py_UCS1);
10867 break;
10868 case PyUnicode_2BYTE_KIND:
10869 COMPARE(Py_UCS4, Py_UCS2);
10870 break;
10871 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010872 {
10873#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10874 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10875 /* normalize result of wmemcmp() into the range [-1; 1] */
10876 if (cmp < 0)
10877 return -1;
10878 if (cmp > 0)
10879 return 1;
10880#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010881 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010882#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010883 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010884 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010885 default:
10886 assert(0);
10887 }
10888 break;
10889 }
10890 default:
10891 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010892 }
10893
Victor Stinner770e19e2012-10-04 22:59:45 +020010894 if (len1 == len2)
10895 return 0;
10896 if (len1 < len2)
10897 return -1;
10898 else
10899 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010900
10901#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010902}
10903
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010904Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010905unicode_compare_eq(PyObject *str1, PyObject *str2)
10906{
10907 int kind;
10908 void *data1, *data2;
10909 Py_ssize_t len;
10910 int cmp;
10911
Victor Stinnere5567ad2012-10-23 02:48:49 +020010912 len = PyUnicode_GET_LENGTH(str1);
10913 if (PyUnicode_GET_LENGTH(str2) != len)
10914 return 0;
10915 kind = PyUnicode_KIND(str1);
10916 if (PyUnicode_KIND(str2) != kind)
10917 return 0;
10918 data1 = PyUnicode_DATA(str1);
10919 data2 = PyUnicode_DATA(str2);
10920
10921 cmp = memcmp(data1, data2, len * kind);
10922 return (cmp == 0);
10923}
10924
10925
Alexander Belopolsky40018472011-02-26 01:02:56 +000010926int
10927PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010928{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010929 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10930 if (PyUnicode_READY(left) == -1 ||
10931 PyUnicode_READY(right) == -1)
10932 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010933
10934 /* a string is equal to itself */
10935 if (left == right)
10936 return 0;
10937
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010938 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010939 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010940 PyErr_Format(PyExc_TypeError,
10941 "Can't compare %.100s and %.100s",
10942 left->ob_type->tp_name,
10943 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010944 return -1;
10945}
10946
Martin v. Löwis5b222132007-06-10 09:51:05 +000010947int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010948_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10949{
10950 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10951 if (right_str == NULL)
10952 return -1;
10953 return PyUnicode_Compare(left, right_str);
10954}
10955
10956int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010957PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10958{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010959 Py_ssize_t i;
10960 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010961 Py_UCS4 chr;
10962
Victor Stinner910337b2011-10-03 03:20:16 +020010963 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964 if (PyUnicode_READY(uni) == -1)
10965 return -1;
10966 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010967 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010968 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010969 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010970 size_t len, len2 = strlen(str);
10971 int cmp;
10972
10973 len = Py_MIN(len1, len2);
10974 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010975 if (cmp != 0) {
10976 if (cmp < 0)
10977 return -1;
10978 else
10979 return 1;
10980 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010981 if (len1 > len2)
10982 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010983 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010984 return -1; /* str is longer */
10985 return 0;
10986 }
10987 else {
10988 void *data = PyUnicode_DATA(uni);
10989 /* Compare Unicode string and source character set string */
10990 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010991 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010992 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10993 /* This check keeps Python strings that end in '\0' from comparing equal
10994 to C strings identical up to that point. */
10995 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10996 return 1; /* uni is longer */
10997 if (str[i])
10998 return -1; /* str is longer */
10999 return 0;
11000 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011001}
11002
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011003
Benjamin Peterson29060642009-01-31 22:14:21 +000011004#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011005 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011006
Alexander Belopolsky40018472011-02-26 01:02:56 +000011007PyObject *
11008PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011009{
11010 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011011 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011012
Victor Stinnere5567ad2012-10-23 02:48:49 +020011013 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11014 Py_RETURN_NOTIMPLEMENTED;
11015
11016 if (PyUnicode_READY(left) == -1 ||
11017 PyUnicode_READY(right) == -1)
11018 return NULL;
11019
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011020 if (left == right) {
11021 switch (op) {
11022 case Py_EQ:
11023 case Py_LE:
11024 case Py_GE:
11025 /* a string is equal to itself */
11026 v = Py_True;
11027 break;
11028 case Py_NE:
11029 case Py_LT:
11030 case Py_GT:
11031 v = Py_False;
11032 break;
11033 default:
11034 PyErr_BadArgument();
11035 return NULL;
11036 }
11037 }
11038 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011039 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011040 result ^= (op == Py_NE);
11041 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011042 }
11043 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011044 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011045
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011046 /* Convert the return value to a Boolean */
11047 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011048 case Py_LE:
11049 v = TEST_COND(result <= 0);
11050 break;
11051 case Py_GE:
11052 v = TEST_COND(result >= 0);
11053 break;
11054 case Py_LT:
11055 v = TEST_COND(result == -1);
11056 break;
11057 case Py_GT:
11058 v = TEST_COND(result == 1);
11059 break;
11060 default:
11061 PyErr_BadArgument();
11062 return NULL;
11063 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011064 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011065 Py_INCREF(v);
11066 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011067}
11068
Alexander Belopolsky40018472011-02-26 01:02:56 +000011069int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011070_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11071{
11072 return unicode_eq(aa, bb);
11073}
11074
11075int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011076PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011077{
Victor Stinner77282cb2013-04-14 19:22:47 +020011078 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011079 void *buf1, *buf2;
11080 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011081 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011082
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011083 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011084 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011085 "'in <string>' requires string as left operand, not %.100s",
11086 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011087 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011088 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011089 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011090 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011091 if (ensure_unicode(str) < 0)
11092 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011094 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011095 kind2 = PyUnicode_KIND(substr);
11096 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011097 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011098 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011099 len2 = PyUnicode_GET_LENGTH(substr);
11100 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011101 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011102 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011103 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011104 if (len2 == 1) {
11105 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11106 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011107 return result;
11108 }
11109 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011110 buf2 = _PyUnicode_AsKind(substr, kind1);
11111 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011112 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011113 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114
Victor Stinner77282cb2013-04-14 19:22:47 +020011115 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011116 case PyUnicode_1BYTE_KIND:
11117 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11118 break;
11119 case PyUnicode_2BYTE_KIND:
11120 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11121 break;
11122 case PyUnicode_4BYTE_KIND:
11123 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11124 break;
11125 default:
11126 result = -1;
11127 assert(0);
11128 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011129
Victor Stinner77282cb2013-04-14 19:22:47 +020011130 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011131 PyMem_Free(buf2);
11132
Guido van Rossum403d68b2000-03-13 15:55:09 +000011133 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011134}
11135
Guido van Rossumd57fd912000-03-10 22:53:23 +000011136/* Concat to string or Unicode object giving a new Unicode object. */
11137
Alexander Belopolsky40018472011-02-26 01:02:56 +000011138PyObject *
11139PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011141 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011142 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011143 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011145 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11146 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011147
11148 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011149 if (left == unicode_empty)
11150 return PyUnicode_FromObject(right);
11151 if (right == unicode_empty)
11152 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011153
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011154 left_len = PyUnicode_GET_LENGTH(left);
11155 right_len = PyUnicode_GET_LENGTH(right);
11156 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011157 PyErr_SetString(PyExc_OverflowError,
11158 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011159 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011160 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011161 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011162
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011163 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11164 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011165 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011166
Guido van Rossumd57fd912000-03-10 22:53:23 +000011167 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011168 result = PyUnicode_New(new_len, maxchar);
11169 if (result == NULL)
11170 return NULL;
11171 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11172 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11173 assert(_PyUnicode_CheckConsistency(result, 1));
11174 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175}
11176
Walter Dörwald1ab83302007-05-18 17:15:44 +000011177void
Victor Stinner23e56682011-10-03 03:54:37 +020011178PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011179{
Victor Stinner23e56682011-10-03 03:54:37 +020011180 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011181 Py_UCS4 maxchar, maxchar2;
11182 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011183
11184 if (p_left == NULL) {
11185 if (!PyErr_Occurred())
11186 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011187 return;
11188 }
Victor Stinner23e56682011-10-03 03:54:37 +020011189 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011190 if (right == NULL || left == NULL
11191 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011192 if (!PyErr_Occurred())
11193 PyErr_BadInternalCall();
11194 goto error;
11195 }
11196
Benjamin Petersonbac79492012-01-14 13:34:47 -050011197 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011198 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011199 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011200 goto error;
11201
Victor Stinner488fa492011-12-12 00:01:39 +010011202 /* Shortcuts */
11203 if (left == unicode_empty) {
11204 Py_DECREF(left);
11205 Py_INCREF(right);
11206 *p_left = right;
11207 return;
11208 }
11209 if (right == unicode_empty)
11210 return;
11211
11212 left_len = PyUnicode_GET_LENGTH(left);
11213 right_len = PyUnicode_GET_LENGTH(right);
11214 if (left_len > PY_SSIZE_T_MAX - right_len) {
11215 PyErr_SetString(PyExc_OverflowError,
11216 "strings are too large to concat");
11217 goto error;
11218 }
11219 new_len = left_len + right_len;
11220
11221 if (unicode_modifiable(left)
11222 && PyUnicode_CheckExact(right)
11223 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011224 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11225 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011226 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011227 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011228 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11229 {
11230 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011231 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011232 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011233
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011234 /* copy 'right' into the newly allocated area of 'left' */
11235 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011236 }
Victor Stinner488fa492011-12-12 00:01:39 +010011237 else {
11238 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11239 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011240 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011241
Victor Stinner488fa492011-12-12 00:01:39 +010011242 /* Concat the two Unicode strings */
11243 res = PyUnicode_New(new_len, maxchar);
11244 if (res == NULL)
11245 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011246 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11247 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011248 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011249 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011250 }
11251 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011252 return;
11253
11254error:
Victor Stinner488fa492011-12-12 00:01:39 +010011255 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011256}
11257
11258void
11259PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11260{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011261 PyUnicode_Append(pleft, right);
11262 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011263}
11264
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011265/*
11266Wraps stringlib_parse_args_finds() and additionally ensures that the
11267first argument is a unicode object.
11268*/
11269
11270Py_LOCAL_INLINE(int)
11271parse_args_finds_unicode(const char * function_name, PyObject *args,
11272 PyObject **substring,
11273 Py_ssize_t *start, Py_ssize_t *end)
11274{
11275 if(stringlib_parse_args_finds(function_name, args, substring,
11276 start, end)) {
11277 if (ensure_unicode(*substring) < 0)
11278 return 0;
11279 return 1;
11280 }
11281 return 0;
11282}
11283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011284PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011285 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011287Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011288string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011289interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290
11291static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011292unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011294 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011295 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011296 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011298 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011299 void *buf1, *buf2;
11300 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011302 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011303 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011305 kind1 = PyUnicode_KIND(self);
11306 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011307 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011308 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011310 len1 = PyUnicode_GET_LENGTH(self);
11311 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011313 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011314 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011315
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011316 buf1 = PyUnicode_DATA(self);
11317 buf2 = PyUnicode_DATA(substring);
11318 if (kind2 != kind1) {
11319 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011320 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011321 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011322 }
11323 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011324 case PyUnicode_1BYTE_KIND:
11325 iresult = ucs1lib_count(
11326 ((Py_UCS1*)buf1) + start, end - start,
11327 buf2, len2, PY_SSIZE_T_MAX
11328 );
11329 break;
11330 case PyUnicode_2BYTE_KIND:
11331 iresult = ucs2lib_count(
11332 ((Py_UCS2*)buf1) + start, end - start,
11333 buf2, len2, PY_SSIZE_T_MAX
11334 );
11335 break;
11336 case PyUnicode_4BYTE_KIND:
11337 iresult = ucs4lib_count(
11338 ((Py_UCS4*)buf1) + start, end - start,
11339 buf2, len2, PY_SSIZE_T_MAX
11340 );
11341 break;
11342 default:
11343 assert(0); iresult = 0;
11344 }
11345
11346 result = PyLong_FromSsize_t(iresult);
11347
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011348 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351 return result;
11352}
11353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011354PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011355 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011357Encode S using the codec registered for encoding. Default encoding\n\
11358is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011359handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011360a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11361'xmlcharrefreplace' as well as any other name registered with\n\
11362codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363
11364static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011365unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011366{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011367 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011368 char *encoding = NULL;
11369 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011370
Benjamin Peterson308d6372009-09-18 21:42:35 +000011371 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11372 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011374 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011375}
11376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011377PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011378 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379\n\
11380Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011381If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011382
11383static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011384unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011386 Py_ssize_t i, j, line_pos, src_len, incr;
11387 Py_UCS4 ch;
11388 PyObject *u;
11389 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011390 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011392 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011393 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394
Ezio Melotti745d54d2013-11-16 19:10:57 +020011395 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11396 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011397 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398
Antoine Pitrou22425222011-10-04 19:10:51 +020011399 if (PyUnicode_READY(self) == -1)
11400 return NULL;
11401
Thomas Wouters7e474022000-07-16 12:04:32 +000011402 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011403 src_len = PyUnicode_GET_LENGTH(self);
11404 i = j = line_pos = 0;
11405 kind = PyUnicode_KIND(self);
11406 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011407 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011408 for (; i < src_len; i++) {
11409 ch = PyUnicode_READ(kind, src_data, i);
11410 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011411 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011412 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011413 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011415 goto overflow;
11416 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011417 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011418 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011419 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011421 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011422 goto overflow;
11423 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011425 if (ch == '\n' || ch == '\r')
11426 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011428 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011429 if (!found)
11430 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011431
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011433 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434 if (!u)
11435 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011436 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437
Antoine Pitroue71d5742011-10-04 15:55:09 +020011438 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439
Antoine Pitroue71d5742011-10-04 15:55:09 +020011440 for (; i < src_len; i++) {
11441 ch = PyUnicode_READ(kind, src_data, i);
11442 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011443 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011444 incr = tabsize - (line_pos % tabsize);
11445 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011446 FILL(kind, dest_data, ' ', j, incr);
11447 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011449 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011450 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011451 line_pos++;
11452 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011453 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011454 if (ch == '\n' || ch == '\r')
11455 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011457 }
11458 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011459 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011460
Antoine Pitroue71d5742011-10-04 15:55:09 +020011461 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011462 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11463 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464}
11465
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011466PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011467 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468\n\
11469Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011470such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471arguments start and end are interpreted as in slice notation.\n\
11472\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011473Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474
11475static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011478 /* initialize variables to prevent gcc warning */
11479 PyObject *substring = NULL;
11480 Py_ssize_t start = 0;
11481 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011482 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011484 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011487 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011489
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011490 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011491
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011492 if (result == -2)
11493 return NULL;
11494
Christian Heimes217cfd12007-12-02 14:31:20 +000011495 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496}
11497
11498static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011499unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011501 void *data;
11502 enum PyUnicode_Kind kind;
11503 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011504
11505 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11506 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011508 }
11509 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11510 PyErr_SetString(PyExc_IndexError, "string index out of range");
11511 return NULL;
11512 }
11513 kind = PyUnicode_KIND(self);
11514 data = PyUnicode_DATA(self);
11515 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011516 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517}
11518
Guido van Rossumc2504932007-09-18 19:42:40 +000011519/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011520 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011521static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011522unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523{
Guido van Rossumc2504932007-09-18 19:42:40 +000011524 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011525 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011526
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011527#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011528 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011529#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 if (_PyUnicode_HASH(self) != -1)
11531 return _PyUnicode_HASH(self);
11532 if (PyUnicode_READY(self) == -1)
11533 return -1;
11534 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011535 /*
11536 We make the hash of the empty string be 0, rather than using
11537 (prefix ^ suffix), since this slightly obfuscates the hash secret
11538 */
11539 if (len == 0) {
11540 _PyUnicode_HASH(self) = 0;
11541 return 0;
11542 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011543 x = _Py_HashBytes(PyUnicode_DATA(self),
11544 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011545 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011546 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547}
11548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011549PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011550 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011552Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553
11554static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011555unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011557 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011558 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011559 PyObject *substring = NULL;
11560 Py_ssize_t start = 0;
11561 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011563 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011566 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011567 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011568
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011569 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011571 if (result == -2)
11572 return NULL;
11573
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574 if (result < 0) {
11575 PyErr_SetString(PyExc_ValueError, "substring not found");
11576 return NULL;
11577 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011578
Christian Heimes217cfd12007-12-02 14:31:20 +000011579 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580}
11581
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011582PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011583 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011585Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011586at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587
11588static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011589unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591 Py_ssize_t i, length;
11592 int kind;
11593 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594 int cased;
11595
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 if (PyUnicode_READY(self) == -1)
11597 return NULL;
11598 length = PyUnicode_GET_LENGTH(self);
11599 kind = PyUnicode_KIND(self);
11600 data = PyUnicode_DATA(self);
11601
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603 if (length == 1)
11604 return PyBool_FromLong(
11605 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011607 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011609 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011610
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 for (i = 0; i < length; i++) {
11613 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011614
Benjamin Peterson29060642009-01-31 22:14:21 +000011615 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11616 return PyBool_FromLong(0);
11617 else if (!cased && Py_UNICODE_ISLOWER(ch))
11618 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011620 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621}
11622
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011623PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011624 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011626Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011627at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628
11629static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011630unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632 Py_ssize_t i, length;
11633 int kind;
11634 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011635 int cased;
11636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011637 if (PyUnicode_READY(self) == -1)
11638 return NULL;
11639 length = PyUnicode_GET_LENGTH(self);
11640 kind = PyUnicode_KIND(self);
11641 data = PyUnicode_DATA(self);
11642
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (length == 1)
11645 return PyBool_FromLong(
11646 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011648 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011650 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011651
Guido van Rossumd57fd912000-03-10 22:53:23 +000011652 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 for (i = 0; i < length; i++) {
11654 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011655
Benjamin Peterson29060642009-01-31 22:14:21 +000011656 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11657 return PyBool_FromLong(0);
11658 else if (!cased && Py_UNICODE_ISUPPER(ch))
11659 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011661 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662}
11663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011664PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011665 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011667Return True if S is a titlecased string and there is at least one\n\
11668character in S, i.e. upper- and titlecase characters may only\n\
11669follow uncased characters and lowercase characters only cased ones.\n\
11670Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671
11672static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011673unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011674{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675 Py_ssize_t i, length;
11676 int kind;
11677 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678 int cased, previous_is_cased;
11679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 if (PyUnicode_READY(self) == -1)
11681 return NULL;
11682 length = PyUnicode_GET_LENGTH(self);
11683 kind = PyUnicode_KIND(self);
11684 data = PyUnicode_DATA(self);
11685
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011687 if (length == 1) {
11688 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11689 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11690 (Py_UNICODE_ISUPPER(ch) != 0));
11691 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011693 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011695 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011696
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697 cased = 0;
11698 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011699 for (i = 0; i < length; i++) {
11700 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011701
Benjamin Peterson29060642009-01-31 22:14:21 +000011702 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11703 if (previous_is_cased)
11704 return PyBool_FromLong(0);
11705 previous_is_cased = 1;
11706 cased = 1;
11707 }
11708 else if (Py_UNICODE_ISLOWER(ch)) {
11709 if (!previous_is_cased)
11710 return PyBool_FromLong(0);
11711 previous_is_cased = 1;
11712 cased = 1;
11713 }
11714 else
11715 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011717 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718}
11719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011720PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011721 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011723Return True if all characters in S are whitespace\n\
11724and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725
11726static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011727unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 Py_ssize_t i, length;
11730 int kind;
11731 void *data;
11732
11733 if (PyUnicode_READY(self) == -1)
11734 return NULL;
11735 length = PyUnicode_GET_LENGTH(self);
11736 kind = PyUnicode_KIND(self);
11737 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011740 if (length == 1)
11741 return PyBool_FromLong(
11742 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011743
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011744 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011745 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011746 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011748 for (i = 0; i < length; i++) {
11749 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011750 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011751 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011753 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754}
11755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011756PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011757 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011758\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011759Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011760and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011761
11762static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011763unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011764{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 Py_ssize_t i, length;
11766 int kind;
11767 void *data;
11768
11769 if (PyUnicode_READY(self) == -1)
11770 return NULL;
11771 length = PyUnicode_GET_LENGTH(self);
11772 kind = PyUnicode_KIND(self);
11773 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011774
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011775 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 if (length == 1)
11777 return PyBool_FromLong(
11778 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011779
11780 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011782 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784 for (i = 0; i < length; i++) {
11785 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011786 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011787 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011788 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011789}
11790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011791PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011792 "S.isalnum() -> 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 alphanumeric\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_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011799{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 int kind;
11801 void *data;
11802 Py_ssize_t len, i;
11803
11804 if (PyUnicode_READY(self) == -1)
11805 return NULL;
11806
11807 kind = PyUnicode_KIND(self);
11808 data = PyUnicode_DATA(self);
11809 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011810
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011811 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011812 if (len == 1) {
11813 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11814 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11815 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011816
11817 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011819 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011820
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 for (i = 0; i < len; i++) {
11822 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011823 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011824 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011825 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011826 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011827}
11828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011829PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011830 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011832Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011833False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834
11835static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011836unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011838 Py_ssize_t i, length;
11839 int kind;
11840 void *data;
11841
11842 if (PyUnicode_READY(self) == -1)
11843 return NULL;
11844 length = PyUnicode_GET_LENGTH(self);
11845 kind = PyUnicode_KIND(self);
11846 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847
Guido van Rossumd57fd912000-03-10 22:53:23 +000011848 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011849 if (length == 1)
11850 return PyBool_FromLong(
11851 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011852
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011853 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011854 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011855 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 for (i = 0; i < length; i++) {
11858 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011859 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011861 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862}
11863
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011864PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011865 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011867Return True if all characters in S are digits\n\
11868and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869
11870static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011871unicode_isdigit(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 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11886 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11887 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011889 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011891 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011892
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 for (i = 0; i < length; i++) {
11894 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011895 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011897 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011898}
11899
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011900PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011901 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011903Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011904False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905
11906static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011907unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 Py_ssize_t i, length;
11910 int kind;
11911 void *data;
11912
11913 if (PyUnicode_READY(self) == -1)
11914 return NULL;
11915 length = PyUnicode_GET_LENGTH(self);
11916 kind = PyUnicode_KIND(self);
11917 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011918
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920 if (length == 1)
11921 return PyBool_FromLong(
11922 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011924 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 if (length == 0)
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_ISNUMERIC(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öwis47383402007-08-15 07:32:56 +000011935int
11936PyUnicode_IsIdentifier(PyObject *self)
11937{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011938 int kind;
11939 void *data;
11940 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011941 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011943 if (PyUnicode_READY(self) == -1) {
11944 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011945 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011946 }
11947
11948 /* Special case for empty strings */
11949 if (PyUnicode_GET_LENGTH(self) == 0)
11950 return 0;
11951 kind = PyUnicode_KIND(self);
11952 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011953
11954 /* PEP 3131 says that the first character must be in
11955 XID_Start and subsequent characters in XID_Continue,
11956 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011957 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011958 letters, digits, underscore). However, given the current
11959 definition of XID_Start and XID_Continue, it is sufficient
11960 to check just for these, except that _ must be allowed
11961 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011962 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011963 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011964 return 0;
11965
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011966 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011967 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011968 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011969 return 1;
11970}
11971
11972PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011973 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011974\n\
11975Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011976to the language definition.\n\
11977\n\
11978Use keyword.iskeyword() to test for reserved identifiers\n\
11979such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011980
11981static PyObject*
11982unicode_isidentifier(PyObject *self)
11983{
11984 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11985}
11986
Georg Brandl559e5d72008-06-11 18:37:52 +000011987PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011988 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011989\n\
11990Return True if all characters in S are considered\n\
11991printable in repr() or S is empty, False otherwise.");
11992
11993static PyObject*
11994unicode_isprintable(PyObject *self)
11995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 Py_ssize_t i, length;
11997 int kind;
11998 void *data;
11999
12000 if (PyUnicode_READY(self) == -1)
12001 return NULL;
12002 length = PyUnicode_GET_LENGTH(self);
12003 kind = PyUnicode_KIND(self);
12004 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012005
12006 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007 if (length == 1)
12008 return PyBool_FromLong(
12009 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 for (i = 0; i < length; i++) {
12012 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012013 Py_RETURN_FALSE;
12014 }
12015 }
12016 Py_RETURN_TRUE;
12017}
12018
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012019PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012020 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012021\n\
12022Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012023iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024
12025static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012026unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012027{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012028 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012029}
12030
Martin v. Löwis18e16552006-02-15 17:27:45 +000012031static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012032unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 if (PyUnicode_READY(self) == -1)
12035 return -1;
12036 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012037}
12038
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012039PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012040 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012041\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012042Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012043done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012044
12045static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012046unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012047{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012048 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 Py_UCS4 fillchar = ' ';
12050
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012051 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012052 return NULL;
12053
Benjamin Petersonbac79492012-01-14 13:34:47 -050012054 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012055 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056
Victor Stinnerc4b49542011-12-11 22:44:26 +010012057 if (PyUnicode_GET_LENGTH(self) >= width)
12058 return unicode_result_unchanged(self);
12059
12060 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012061}
12062
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012063PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012064 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012065\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012066Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012067
12068static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012069unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012070{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012071 if (PyUnicode_READY(self) == -1)
12072 return NULL;
12073 if (PyUnicode_IS_ASCII(self))
12074 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012075 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012076}
12077
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012078#define LEFTSTRIP 0
12079#define RIGHTSTRIP 1
12080#define BOTHSTRIP 2
12081
12082/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012083static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012084
12085#define STRIPNAME(i) (stripformat[i]+3)
12086
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012087/* externally visible for str.strip(unicode) */
12088PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012089_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012090{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012091 void *data;
12092 int kind;
12093 Py_ssize_t i, j, len;
12094 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012095 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012096
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012097 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12098 return NULL;
12099
12100 kind = PyUnicode_KIND(self);
12101 data = PyUnicode_DATA(self);
12102 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012103 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012104 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12105 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012106 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012107
Benjamin Peterson14339b62009-01-31 16:36:08 +000012108 i = 0;
12109 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012110 while (i < len) {
12111 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12112 if (!BLOOM(sepmask, ch))
12113 break;
12114 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12115 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012116 i++;
12117 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012118 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012119
Benjamin Peterson14339b62009-01-31 16:36:08 +000012120 j = len;
12121 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012122 j--;
12123 while (j >= i) {
12124 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12125 if (!BLOOM(sepmask, ch))
12126 break;
12127 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12128 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012129 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012130 }
12131
Benjamin Peterson29060642009-01-31 22:14:21 +000012132 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012133 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012134
Victor Stinner7931d9a2011-11-04 00:22:48 +010012135 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012136}
12137
12138PyObject*
12139PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12140{
12141 unsigned char *data;
12142 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012143 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144
Victor Stinnerde636f32011-10-01 03:55:54 +020012145 if (PyUnicode_READY(self) == -1)
12146 return NULL;
12147
Victor Stinner684d5fd2012-05-03 02:32:34 +020012148 length = PyUnicode_GET_LENGTH(self);
12149 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012150
Victor Stinner684d5fd2012-05-03 02:32:34 +020012151 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012152 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012153
Victor Stinnerde636f32011-10-01 03:55:54 +020012154 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012155 PyErr_SetString(PyExc_IndexError, "string index out of range");
12156 return NULL;
12157 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012158 if (start >= length || end < start)
12159 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012160
Victor Stinner684d5fd2012-05-03 02:32:34 +020012161 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012162 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012163 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012164 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012165 }
12166 else {
12167 kind = PyUnicode_KIND(self);
12168 data = PyUnicode_1BYTE_DATA(self);
12169 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012170 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012171 length);
12172 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012173}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174
12175static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012176do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012178 Py_ssize_t len, i, j;
12179
12180 if (PyUnicode_READY(self) == -1)
12181 return NULL;
12182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012183 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012184
Victor Stinnercc7af722013-04-09 22:39:24 +020012185 if (PyUnicode_IS_ASCII(self)) {
12186 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12187
12188 i = 0;
12189 if (striptype != RIGHTSTRIP) {
12190 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012191 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012192 if (!_Py_ascii_whitespace[ch])
12193 break;
12194 i++;
12195 }
12196 }
12197
12198 j = len;
12199 if (striptype != LEFTSTRIP) {
12200 j--;
12201 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012202 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012203 if (!_Py_ascii_whitespace[ch])
12204 break;
12205 j--;
12206 }
12207 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012208 }
12209 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012210 else {
12211 int kind = PyUnicode_KIND(self);
12212 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012213
Victor Stinnercc7af722013-04-09 22:39:24 +020012214 i = 0;
12215 if (striptype != RIGHTSTRIP) {
12216 while (i < len) {
12217 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12218 if (!Py_UNICODE_ISSPACE(ch))
12219 break;
12220 i++;
12221 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012222 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012223
12224 j = len;
12225 if (striptype != LEFTSTRIP) {
12226 j--;
12227 while (j >= i) {
12228 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12229 if (!Py_UNICODE_ISSPACE(ch))
12230 break;
12231 j--;
12232 }
12233 j++;
12234 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012235 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012236
Victor Stinner7931d9a2011-11-04 00:22:48 +010012237 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238}
12239
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012240
12241static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012242do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012243{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012244 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012245
Serhiy Storchakac6792272013-10-19 21:03:34 +030012246 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012247 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012248
Benjamin Peterson14339b62009-01-31 16:36:08 +000012249 if (sep != NULL && sep != Py_None) {
12250 if (PyUnicode_Check(sep))
12251 return _PyUnicode_XStrip(self, striptype, sep);
12252 else {
12253 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012254 "%s arg must be None or str",
12255 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012256 return NULL;
12257 }
12258 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012259
Benjamin Peterson14339b62009-01-31 16:36:08 +000012260 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012261}
12262
12263
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012264PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012265 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012266\n\
12267Return a copy of the string S with leading and trailing\n\
12268whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012269If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012270
12271static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012272unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012273{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012274 if (PyTuple_GET_SIZE(args) == 0)
12275 return do_strip(self, BOTHSTRIP); /* Common case */
12276 else
12277 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012278}
12279
12280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012281PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012282 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012283\n\
12284Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012285If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012286
12287static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012288unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012289{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012290 if (PyTuple_GET_SIZE(args) == 0)
12291 return do_strip(self, LEFTSTRIP); /* Common case */
12292 else
12293 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012294}
12295
12296
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012297PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012298 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012299\n\
12300Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012301If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012302
12303static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012304unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012305{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012306 if (PyTuple_GET_SIZE(args) == 0)
12307 return do_strip(self, RIGHTSTRIP); /* Common case */
12308 else
12309 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012310}
12311
12312
Guido van Rossumd57fd912000-03-10 22:53:23 +000012313static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012314unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012316 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012317 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012318
Serhiy Storchaka05997252013-01-26 12:14:02 +020012319 if (len < 1)
12320 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012321
Victor Stinnerc4b49542011-12-11 22:44:26 +010012322 /* no repeat, return original string */
12323 if (len == 1)
12324 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012325
Benjamin Petersonbac79492012-01-14 13:34:47 -050012326 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 return NULL;
12328
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012329 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012330 PyErr_SetString(PyExc_OverflowError,
12331 "repeated string is too long");
12332 return NULL;
12333 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012334 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012335
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012336 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012337 if (!u)
12338 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012339 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012340
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012341 if (PyUnicode_GET_LENGTH(str) == 1) {
12342 const int kind = PyUnicode_KIND(str);
12343 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012344 if (kind == PyUnicode_1BYTE_KIND) {
12345 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012346 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012347 }
12348 else if (kind == PyUnicode_2BYTE_KIND) {
12349 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012350 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012351 ucs2[n] = fill_char;
12352 } else {
12353 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12354 assert(kind == PyUnicode_4BYTE_KIND);
12355 for (n = 0; n < len; ++n)
12356 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012357 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012358 }
12359 else {
12360 /* number of characters copied this far */
12361 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012362 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012363 char *to = (char *) PyUnicode_DATA(u);
12364 Py_MEMCPY(to, PyUnicode_DATA(str),
12365 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012366 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012367 n = (done <= nchars-done) ? done : nchars-done;
12368 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012369 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012370 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012371 }
12372
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012373 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012374 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012375}
12376
Alexander Belopolsky40018472011-02-26 01:02:56 +000012377PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012378PyUnicode_Replace(PyObject *str,
12379 PyObject *substr,
12380 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012381 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012382{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012383 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12384 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012385 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012386 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012387}
12388
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012389PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012390 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391\n\
12392Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012393old replaced by new. If the optional argument count is\n\
12394given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012395
12396static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012397unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012398{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012399 PyObject *str1;
12400 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012401 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012402
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012403 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012404 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012405 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012406 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012407 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012408}
12409
Alexander Belopolsky40018472011-02-26 01:02:56 +000012410static PyObject *
12411unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012412{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012413 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012414 Py_ssize_t isize;
12415 Py_ssize_t osize, squote, dquote, i, o;
12416 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012417 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012418 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012419
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012421 return NULL;
12422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012423 isize = PyUnicode_GET_LENGTH(unicode);
12424 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012425
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012426 /* Compute length of output, quote characters, and
12427 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012428 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012429 max = 127;
12430 squote = dquote = 0;
12431 ikind = PyUnicode_KIND(unicode);
12432 for (i = 0; i < isize; i++) {
12433 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012434 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012435 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012436 case '\'': squote++; break;
12437 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012438 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012439 incr = 2;
12440 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012441 default:
12442 /* Fast-path ASCII */
12443 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012444 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012446 ;
12447 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012449 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012450 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012451 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012452 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012453 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012454 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012455 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012456 if (osize > PY_SSIZE_T_MAX - incr) {
12457 PyErr_SetString(PyExc_OverflowError,
12458 "string is too long to generate repr");
12459 return NULL;
12460 }
12461 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012462 }
12463
12464 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012465 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012466 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012467 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012468 if (dquote)
12469 /* Both squote and dquote present. Use squote,
12470 and escape them */
12471 osize += squote;
12472 else
12473 quote = '"';
12474 }
Victor Stinner55c08782013-04-14 18:45:39 +020012475 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476
12477 repr = PyUnicode_New(osize, max);
12478 if (repr == NULL)
12479 return NULL;
12480 okind = PyUnicode_KIND(repr);
12481 odata = PyUnicode_DATA(repr);
12482
12483 PyUnicode_WRITE(okind, odata, 0, quote);
12484 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012485 if (unchanged) {
12486 _PyUnicode_FastCopyCharacters(repr, 1,
12487 unicode, 0,
12488 isize);
12489 }
12490 else {
12491 for (i = 0, o = 1; i < isize; i++) {
12492 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012493
Victor Stinner55c08782013-04-14 18:45:39 +020012494 /* Escape quotes and backslashes */
12495 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012496 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012498 continue;
12499 }
12500
12501 /* Map special whitespace to '\t', \n', '\r' */
12502 if (ch == '\t') {
12503 PyUnicode_WRITE(okind, odata, o++, '\\');
12504 PyUnicode_WRITE(okind, odata, o++, 't');
12505 }
12506 else if (ch == '\n') {
12507 PyUnicode_WRITE(okind, odata, o++, '\\');
12508 PyUnicode_WRITE(okind, odata, o++, 'n');
12509 }
12510 else if (ch == '\r') {
12511 PyUnicode_WRITE(okind, odata, o++, '\\');
12512 PyUnicode_WRITE(okind, odata, o++, 'r');
12513 }
12514
12515 /* Map non-printable US ASCII to '\xhh' */
12516 else if (ch < ' ' || ch == 0x7F) {
12517 PyUnicode_WRITE(okind, odata, o++, '\\');
12518 PyUnicode_WRITE(okind, odata, o++, 'x');
12519 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12520 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12521 }
12522
12523 /* Copy ASCII characters as-is */
12524 else if (ch < 0x7F) {
12525 PyUnicode_WRITE(okind, odata, o++, ch);
12526 }
12527
12528 /* Non-ASCII characters */
12529 else {
12530 /* Map Unicode whitespace and control characters
12531 (categories Z* and C* except ASCII space)
12532 */
12533 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12534 PyUnicode_WRITE(okind, odata, o++, '\\');
12535 /* Map 8-bit characters to '\xhh' */
12536 if (ch <= 0xff) {
12537 PyUnicode_WRITE(okind, odata, o++, 'x');
12538 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12539 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12540 }
12541 /* Map 16-bit characters to '\uxxxx' */
12542 else if (ch <= 0xffff) {
12543 PyUnicode_WRITE(okind, odata, o++, 'u');
12544 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12545 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12546 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12547 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12548 }
12549 /* Map 21-bit characters to '\U00xxxxxx' */
12550 else {
12551 PyUnicode_WRITE(okind, odata, o++, 'U');
12552 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12553 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12554 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12555 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12556 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12557 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12558 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12559 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12560 }
12561 }
12562 /* Copy characters as-is */
12563 else {
12564 PyUnicode_WRITE(okind, odata, o++, ch);
12565 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012566 }
12567 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012568 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012569 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012570 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012571 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012572}
12573
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012574PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012575 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012576\n\
12577Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012578such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012579arguments start and end are interpreted as in slice notation.\n\
12580\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012581Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012582
12583static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012585{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012586 /* initialize variables to prevent gcc warning */
12587 PyObject *substring = NULL;
12588 Py_ssize_t start = 0;
12589 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012590 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012592 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012593 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012595 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012596 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012597
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012598 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012599
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012600 if (result == -2)
12601 return NULL;
12602
Christian Heimes217cfd12007-12-02 14:31:20 +000012603 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012604}
12605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012606PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012607 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012609Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610
12611static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012612unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012613{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012614 /* initialize variables to prevent gcc warning */
12615 PyObject *substring = NULL;
12616 Py_ssize_t start = 0;
12617 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012618 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012620 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012621 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012623 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012624 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012625
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012626 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012627
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012628 if (result == -2)
12629 return NULL;
12630
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631 if (result < 0) {
12632 PyErr_SetString(PyExc_ValueError, "substring not found");
12633 return NULL;
12634 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012635
Christian Heimes217cfd12007-12-02 14:31:20 +000012636 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637}
12638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012639PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012640 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012642Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012643done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644
12645static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012646unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012648 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012649 Py_UCS4 fillchar = ' ';
12650
Victor Stinnere9a29352011-10-01 02:14:59 +020012651 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012652 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012653
Benjamin Petersonbac79492012-01-14 13:34:47 -050012654 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655 return NULL;
12656
Victor Stinnerc4b49542011-12-11 22:44:26 +010012657 if (PyUnicode_GET_LENGTH(self) >= width)
12658 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659
Victor Stinnerc4b49542011-12-11 22:44:26 +010012660 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012661}
12662
Alexander Belopolsky40018472011-02-26 01:02:56 +000012663PyObject *
12664PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012666 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012667 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012668
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012669 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670}
12671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012672PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012673 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674\n\
12675Return a list of the words in S, using sep as the\n\
12676delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012677splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012678whitespace string is a separator and empty strings are\n\
12679removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680
12681static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012682unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012683{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012684 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012686 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012688 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12689 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690 return NULL;
12691
12692 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012693 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012694
12695 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012696 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012697
12698 PyErr_Format(PyExc_TypeError,
12699 "must be str or None, not %.100s",
12700 Py_TYPE(substring)->tp_name);
12701 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702}
12703
Thomas Wouters477c8d52006-05-27 19:21:47 +000012704PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012705PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012706{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012707 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012708 int kind1, kind2;
12709 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012711
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012712 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012713 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012714
Victor Stinner14f8f022011-10-05 20:58:25 +020012715 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012716 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717 len1 = PyUnicode_GET_LENGTH(str_obj);
12718 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012719 if (kind1 < kind2 || len1 < len2) {
12720 _Py_INCREF_UNICODE_EMPTY();
12721 if (!unicode_empty)
12722 out = NULL;
12723 else {
12724 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12725 Py_DECREF(unicode_empty);
12726 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012727 return out;
12728 }
12729 buf1 = PyUnicode_DATA(str_obj);
12730 buf2 = PyUnicode_DATA(sep_obj);
12731 if (kind2 != kind1) {
12732 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12733 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012734 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012735 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012737 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012739 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12740 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12741 else
12742 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012743 break;
12744 case PyUnicode_2BYTE_KIND:
12745 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12746 break;
12747 case PyUnicode_4BYTE_KIND:
12748 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12749 break;
12750 default:
12751 assert(0);
12752 out = 0;
12753 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012754
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012755 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012756 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012757
12758 return out;
12759}
12760
12761
12762PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012763PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012764{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012765 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012766 int kind1, kind2;
12767 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012768 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012769
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012770 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012771 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012772
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012773 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012774 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012775 len1 = PyUnicode_GET_LENGTH(str_obj);
12776 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012777 if (kind1 < kind2 || len1 < len2) {
12778 _Py_INCREF_UNICODE_EMPTY();
12779 if (!unicode_empty)
12780 out = NULL;
12781 else {
12782 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12783 Py_DECREF(unicode_empty);
12784 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012785 return out;
12786 }
12787 buf1 = PyUnicode_DATA(str_obj);
12788 buf2 = PyUnicode_DATA(sep_obj);
12789 if (kind2 != kind1) {
12790 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12791 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012792 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012793 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012794
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012795 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012796 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012797 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12798 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12799 else
12800 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012801 break;
12802 case PyUnicode_2BYTE_KIND:
12803 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12804 break;
12805 case PyUnicode_4BYTE_KIND:
12806 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12807 break;
12808 default:
12809 assert(0);
12810 out = 0;
12811 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012812
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012813 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012814 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012815
12816 return out;
12817}
12818
12819PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012820 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012821\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012822Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012823the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012824found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012825
12826static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012827unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012828{
Victor Stinner9310abb2011-10-05 00:59:23 +020012829 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012830}
12831
12832PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012833 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012834\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012835Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012836the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012837separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012838
12839static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012840unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012841{
Victor Stinner9310abb2011-10-05 00:59:23 +020012842 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012843}
12844
Alexander Belopolsky40018472011-02-26 01:02:56 +000012845PyObject *
12846PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012847{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012848 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012849 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012850
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012851 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012852}
12853
12854PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012855 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012856\n\
12857Return a list of the words in S, using sep as the\n\
12858delimiter string, starting at the end of the string and\n\
12859working to the front. If maxsplit is given, at most maxsplit\n\
12860splits are done. If sep is not specified, any whitespace string\n\
12861is a separator.");
12862
12863static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012864unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012865{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012866 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012867 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012868 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012869
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012870 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12871 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012872 return NULL;
12873
12874 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012875 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012876
12877 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012878 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012879
12880 PyErr_Format(PyExc_TypeError,
12881 "must be str or None, not %.100s",
12882 Py_TYPE(substring)->tp_name);
12883 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012884}
12885
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012886PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012887 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012888\n\
12889Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012890Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012891is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892
12893static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012894unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012895{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012896 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012897 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012898
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012899 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12900 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012901 return NULL;
12902
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012903 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012904}
12905
12906static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012907PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012908{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012909 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012910}
12911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012912PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012913 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012914\n\
12915Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012916and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012917
12918static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012919unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012921 if (PyUnicode_READY(self) == -1)
12922 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012923 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012924}
12925
Larry Hastings61272b72014-01-07 12:41:53 -080012926/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012927
Larry Hastings31826802013-10-19 00:09:25 -070012928@staticmethod
12929str.maketrans as unicode_maketrans
12930
12931 x: object
12932
12933 y: unicode=NULL
12934
12935 z: unicode=NULL
12936
12937 /
12938
12939Return a translation table usable for str.translate().
12940
12941If there is only one argument, it must be a dictionary mapping Unicode
12942ordinals (integers) or characters to Unicode ordinals, strings or None.
12943Character keys will be then converted to ordinals.
12944If there are two arguments, they must be strings of equal length, and
12945in the resulting dictionary, each character in x will be mapped to the
12946character at the same position in y. If there is a third argument, it
12947must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012948[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012949
Larry Hastings31826802013-10-19 00:09:25 -070012950static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012951unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012952/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012953{
Georg Brandlceee0772007-11-27 23:48:05 +000012954 PyObject *new = NULL, *key, *value;
12955 Py_ssize_t i = 0;
12956 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012957
Georg Brandlceee0772007-11-27 23:48:05 +000012958 new = PyDict_New();
12959 if (!new)
12960 return NULL;
12961 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012962 int x_kind, y_kind, z_kind;
12963 void *x_data, *y_data, *z_data;
12964
Georg Brandlceee0772007-11-27 23:48:05 +000012965 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012966 if (!PyUnicode_Check(x)) {
12967 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12968 "be a string if there is a second argument");
12969 goto err;
12970 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012971 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012972 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12973 "arguments must have equal length");
12974 goto err;
12975 }
12976 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012977 x_kind = PyUnicode_KIND(x);
12978 y_kind = PyUnicode_KIND(y);
12979 x_data = PyUnicode_DATA(x);
12980 y_data = PyUnicode_DATA(y);
12981 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12982 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012983 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012984 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012985 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012986 if (!value) {
12987 Py_DECREF(key);
12988 goto err;
12989 }
Georg Brandlceee0772007-11-27 23:48:05 +000012990 res = PyDict_SetItem(new, key, value);
12991 Py_DECREF(key);
12992 Py_DECREF(value);
12993 if (res < 0)
12994 goto err;
12995 }
12996 /* create entries for deleting chars in z */
12997 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012998 z_kind = PyUnicode_KIND(z);
12999 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013000 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013001 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013002 if (!key)
13003 goto err;
13004 res = PyDict_SetItem(new, key, Py_None);
13005 Py_DECREF(key);
13006 if (res < 0)
13007 goto err;
13008 }
13009 }
13010 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013011 int kind;
13012 void *data;
13013
Georg Brandlceee0772007-11-27 23:48:05 +000013014 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013015 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013016 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13017 "to maketrans it must be a dict");
13018 goto err;
13019 }
13020 /* copy entries into the new dict, converting string keys to int keys */
13021 while (PyDict_Next(x, &i, &key, &value)) {
13022 if (PyUnicode_Check(key)) {
13023 /* convert string keys to integer keys */
13024 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013025 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013026 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13027 "table must be of length 1");
13028 goto err;
13029 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013030 kind = PyUnicode_KIND(key);
13031 data = PyUnicode_DATA(key);
13032 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013033 if (!newkey)
13034 goto err;
13035 res = PyDict_SetItem(new, newkey, value);
13036 Py_DECREF(newkey);
13037 if (res < 0)
13038 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013039 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013040 /* just keep integer keys */
13041 if (PyDict_SetItem(new, key, value) < 0)
13042 goto err;
13043 } else {
13044 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13045 "be strings or integers");
13046 goto err;
13047 }
13048 }
13049 }
13050 return new;
13051 err:
13052 Py_DECREF(new);
13053 return NULL;
13054}
13055
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013056PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013057 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013058\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013059Return a copy of the string S in which each character has been mapped\n\
13060through the given translation table. The table must implement\n\
13061lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13062mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13063this operation raises LookupError, the character is left untouched.\n\
13064Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013065
13066static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013067unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013068{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013069 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013070}
13071
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013072PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013073 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013074\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013075Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013076
13077static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013078unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013079{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013080 if (PyUnicode_READY(self) == -1)
13081 return NULL;
13082 if (PyUnicode_IS_ASCII(self))
13083 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013084 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013085}
13086
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013087PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013088 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013089\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013090Pad a numeric string S with zeros on the left, to fill a field\n\
13091of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013092
13093static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013094unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013096 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013097 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013098 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013099 int kind;
13100 void *data;
13101 Py_UCS4 chr;
13102
Martin v. Löwis18e16552006-02-15 17:27:45 +000013103 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104 return NULL;
13105
Benjamin Petersonbac79492012-01-14 13:34:47 -050013106 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013107 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108
Victor Stinnerc4b49542011-12-11 22:44:26 +010013109 if (PyUnicode_GET_LENGTH(self) >= width)
13110 return unicode_result_unchanged(self);
13111
13112 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113
13114 u = pad(self, fill, 0, '0');
13115
Walter Dörwald068325e2002-04-15 13:36:47 +000013116 if (u == NULL)
13117 return NULL;
13118
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 kind = PyUnicode_KIND(u);
13120 data = PyUnicode_DATA(u);
13121 chr = PyUnicode_READ(kind, data, fill);
13122
13123 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013124 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013125 PyUnicode_WRITE(kind, data, 0, chr);
13126 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127 }
13128
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013129 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013130 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013131}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132
13133#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013134static PyObject *
13135unicode__decimal2ascii(PyObject *self)
13136{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013137 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013138}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013139#endif
13140
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013141PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013142 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013143\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013144Return True if S starts with the specified prefix, False otherwise.\n\
13145With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013146With optional end, stop comparing S at that position.\n\
13147prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013148
13149static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013150unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013151 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013153 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013154 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013155 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013156 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013157 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158
Jesus Ceaac451502011-04-20 17:09:23 +020013159 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013160 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013161 if (PyTuple_Check(subobj)) {
13162 Py_ssize_t i;
13163 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013164 substring = PyTuple_GET_ITEM(subobj, i);
13165 if (!PyUnicode_Check(substring)) {
13166 PyErr_Format(PyExc_TypeError,
13167 "tuple for startswith must only contain str, "
13168 "not %.100s",
13169 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013170 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013171 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013172 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013173 if (result == -1)
13174 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013175 if (result) {
13176 Py_RETURN_TRUE;
13177 }
13178 }
13179 /* nothing matched */
13180 Py_RETURN_FALSE;
13181 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013182 if (!PyUnicode_Check(subobj)) {
13183 PyErr_Format(PyExc_TypeError,
13184 "startswith first arg must be str or "
13185 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013186 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013187 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013188 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013189 if (result == -1)
13190 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013191 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192}
13193
13194
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013195PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013196 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013198Return True if S ends with the specified suffix, False otherwise.\n\
13199With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013200With optional end, stop comparing S at that position.\n\
13201suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013202
13203static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013204unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013205 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013206{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013207 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013208 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013209 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013210 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013211 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212
Jesus Ceaac451502011-04-20 17:09:23 +020013213 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013214 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013215 if (PyTuple_Check(subobj)) {
13216 Py_ssize_t i;
13217 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013218 substring = PyTuple_GET_ITEM(subobj, i);
13219 if (!PyUnicode_Check(substring)) {
13220 PyErr_Format(PyExc_TypeError,
13221 "tuple for endswith must only contain str, "
13222 "not %.100s",
13223 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013224 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013225 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013226 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013227 if (result == -1)
13228 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013229 if (result) {
13230 Py_RETURN_TRUE;
13231 }
13232 }
13233 Py_RETURN_FALSE;
13234 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013235 if (!PyUnicode_Check(subobj)) {
13236 PyErr_Format(PyExc_TypeError,
13237 "endswith first arg must be str or "
13238 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013240 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013241 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013242 if (result == -1)
13243 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013244 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013245}
13246
Victor Stinner202fdca2012-05-07 12:47:02 +020013247Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013248_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013249{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013250 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13251 writer->data = PyUnicode_DATA(writer->buffer);
13252
13253 if (!writer->readonly) {
13254 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013255 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013256 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013257 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013258 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13259 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13260 writer->kind = PyUnicode_WCHAR_KIND;
13261 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13262
Victor Stinner8f674cc2013-04-17 23:02:17 +020013263 /* Copy-on-write mode: set buffer size to 0 so
13264 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13265 * next write. */
13266 writer->size = 0;
13267 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013268}
13269
Victor Stinnerd3f08822012-05-29 12:57:52 +020013270void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013271_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013272{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013273 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013274
13275 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013276 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013277
13278 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13279 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13280 writer->kind = PyUnicode_WCHAR_KIND;
13281 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013282}
13283
Victor Stinnerd3f08822012-05-29 12:57:52 +020013284int
13285_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13286 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013287{
13288 Py_ssize_t newlen;
13289 PyObject *newbuffer;
13290
Victor Stinner2740e462016-09-06 16:58:36 -070013291 assert(maxchar <= MAX_UNICODE);
13292
Victor Stinnerca9381e2015-09-22 00:58:32 +020013293 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013294 assert((maxchar > writer->maxchar && length >= 0)
13295 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013296
Victor Stinner202fdca2012-05-07 12:47:02 +020013297 if (length > PY_SSIZE_T_MAX - writer->pos) {
13298 PyErr_NoMemory();
13299 return -1;
13300 }
13301 newlen = writer->pos + length;
13302
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013303 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013304
Victor Stinnerd3f08822012-05-29 12:57:52 +020013305 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013306 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013307 if (writer->overallocate
13308 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13309 /* overallocate to limit the number of realloc() */
13310 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013311 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013312 if (newlen < writer->min_length)
13313 newlen = writer->min_length;
13314
Victor Stinnerd3f08822012-05-29 12:57:52 +020013315 writer->buffer = PyUnicode_New(newlen, maxchar);
13316 if (writer->buffer == NULL)
13317 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013318 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013319 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013320 if (writer->overallocate
13321 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13322 /* overallocate to limit the number of realloc() */
13323 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013324 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013325 if (newlen < writer->min_length)
13326 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013327
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013328 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013329 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013330 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013331 newbuffer = PyUnicode_New(newlen, maxchar);
13332 if (newbuffer == NULL)
13333 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013334 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13335 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013336 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013337 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013338 }
13339 else {
13340 newbuffer = resize_compact(writer->buffer, newlen);
13341 if (newbuffer == NULL)
13342 return -1;
13343 }
13344 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013345 }
13346 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013347 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013348 newbuffer = PyUnicode_New(writer->size, maxchar);
13349 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013350 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013351 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13352 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013353 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013354 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013355 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013356 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013357
13358#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013359}
13360
Victor Stinnerca9381e2015-09-22 00:58:32 +020013361int
13362_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13363 enum PyUnicode_Kind kind)
13364{
13365 Py_UCS4 maxchar;
13366
13367 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13368 assert(writer->kind < kind);
13369
13370 switch (kind)
13371 {
13372 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13373 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13374 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13375 default:
13376 assert(0 && "invalid kind");
13377 return -1;
13378 }
13379
13380 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13381}
13382
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013383Py_LOCAL_INLINE(int)
13384_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013385{
Victor Stinner2740e462016-09-06 16:58:36 -070013386 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013387 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13388 return -1;
13389 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13390 writer->pos++;
13391 return 0;
13392}
13393
13394int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013395_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13396{
13397 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13398}
13399
13400int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013401_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13402{
13403 Py_UCS4 maxchar;
13404 Py_ssize_t len;
13405
13406 if (PyUnicode_READY(str) == -1)
13407 return -1;
13408 len = PyUnicode_GET_LENGTH(str);
13409 if (len == 0)
13410 return 0;
13411 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13412 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013413 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013414 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013415 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013416 Py_INCREF(str);
13417 writer->buffer = str;
13418 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013419 writer->pos += len;
13420 return 0;
13421 }
13422 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13423 return -1;
13424 }
13425 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13426 str, 0, len);
13427 writer->pos += len;
13428 return 0;
13429}
13430
Victor Stinnere215d962012-10-06 23:03:36 +020013431int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013432_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13433 Py_ssize_t start, Py_ssize_t end)
13434{
13435 Py_UCS4 maxchar;
13436 Py_ssize_t len;
13437
13438 if (PyUnicode_READY(str) == -1)
13439 return -1;
13440
13441 assert(0 <= start);
13442 assert(end <= PyUnicode_GET_LENGTH(str));
13443 assert(start <= end);
13444
13445 if (end == 0)
13446 return 0;
13447
13448 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13449 return _PyUnicodeWriter_WriteStr(writer, str);
13450
13451 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13452 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13453 else
13454 maxchar = writer->maxchar;
13455 len = end - start;
13456
13457 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13458 return -1;
13459
13460 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13461 str, start, len);
13462 writer->pos += len;
13463 return 0;
13464}
13465
13466int
Victor Stinner4a587072013-11-19 12:54:53 +010013467_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13468 const char *ascii, Py_ssize_t len)
13469{
13470 if (len == -1)
13471 len = strlen(ascii);
13472
13473 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13474
13475 if (writer->buffer == NULL && !writer->overallocate) {
13476 PyObject *str;
13477
13478 str = _PyUnicode_FromASCII(ascii, len);
13479 if (str == NULL)
13480 return -1;
13481
13482 writer->readonly = 1;
13483 writer->buffer = str;
13484 _PyUnicodeWriter_Update(writer);
13485 writer->pos += len;
13486 return 0;
13487 }
13488
13489 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13490 return -1;
13491
13492 switch (writer->kind)
13493 {
13494 case PyUnicode_1BYTE_KIND:
13495 {
13496 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13497 Py_UCS1 *data = writer->data;
13498
13499 Py_MEMCPY(data + writer->pos, str, len);
13500 break;
13501 }
13502 case PyUnicode_2BYTE_KIND:
13503 {
13504 _PyUnicode_CONVERT_BYTES(
13505 Py_UCS1, Py_UCS2,
13506 ascii, ascii + len,
13507 (Py_UCS2 *)writer->data + writer->pos);
13508 break;
13509 }
13510 case PyUnicode_4BYTE_KIND:
13511 {
13512 _PyUnicode_CONVERT_BYTES(
13513 Py_UCS1, Py_UCS4,
13514 ascii, ascii + len,
13515 (Py_UCS4 *)writer->data + writer->pos);
13516 break;
13517 }
13518 default:
13519 assert(0);
13520 }
13521
13522 writer->pos += len;
13523 return 0;
13524}
13525
13526int
13527_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13528 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013529{
13530 Py_UCS4 maxchar;
13531
13532 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13533 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13534 return -1;
13535 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13536 writer->pos += len;
13537 return 0;
13538}
13539
Victor Stinnerd3f08822012-05-29 12:57:52 +020013540PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013541_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013542{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013543 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013544 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013545 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013546 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013547 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013548 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013549 str = writer->buffer;
13550 writer->buffer = NULL;
13551 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13552 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013553 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013554 if (writer->pos == 0) {
13555 Py_CLEAR(writer->buffer);
13556
13557 /* Get the empty Unicode string singleton ('') */
13558 _Py_INCREF_UNICODE_EMPTY();
13559 str = unicode_empty;
Victor Stinner202fdca2012-05-07 12:47:02 +020013560 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013561 else {
13562 str = writer->buffer;
13563 writer->buffer = NULL;
13564
13565 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13566 PyObject *str2;
13567 str2 = resize_compact(str, writer->pos);
13568 if (str2 == NULL)
13569 return NULL;
13570 str = str2;
13571 }
13572 }
13573
Victor Stinner15a0bd32013-07-08 22:29:55 +020013574 assert(_PyUnicode_CheckConsistency(str, 1));
13575 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013576}
13577
Victor Stinnerd3f08822012-05-29 12:57:52 +020013578void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013579_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013580{
13581 Py_CLEAR(writer->buffer);
13582}
13583
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013584#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013585
13586PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013587 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013588\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013589Return a formatted version of S, using substitutions from args and kwargs.\n\
13590The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013591
Eric Smith27bbca62010-11-04 17:06:58 +000013592PyDoc_STRVAR(format_map__doc__,
13593 "S.format_map(mapping) -> str\n\
13594\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013595Return a formatted version of S, using substitutions from mapping.\n\
13596The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013597
Eric Smith4a7d76d2008-05-30 18:10:19 +000013598static PyObject *
13599unicode__format__(PyObject* self, PyObject* args)
13600{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013601 PyObject *format_spec;
13602 _PyUnicodeWriter writer;
13603 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013604
13605 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13606 return NULL;
13607
Victor Stinnerd3f08822012-05-29 12:57:52 +020013608 if (PyUnicode_READY(self) == -1)
13609 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013610 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013611 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13612 self, format_spec, 0,
13613 PyUnicode_GET_LENGTH(format_spec));
13614 if (ret == -1) {
13615 _PyUnicodeWriter_Dealloc(&writer);
13616 return NULL;
13617 }
13618 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013619}
13620
Eric Smith8c663262007-08-25 02:26:07 +000013621PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013622 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013623\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013624Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013625
13626static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013627unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013628{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013629 Py_ssize_t size;
13630
13631 /* If it's a compact object, account for base structure +
13632 character data. */
13633 if (PyUnicode_IS_COMPACT_ASCII(v))
13634 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13635 else if (PyUnicode_IS_COMPACT(v))
13636 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013637 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013638 else {
13639 /* If it is a two-block object, account for base object, and
13640 for character block if present. */
13641 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013642 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013643 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013644 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013645 }
13646 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013647 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013648 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013649 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013650 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013651 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013652
13653 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013654}
13655
13656PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013657 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013658
13659static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013660unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013661{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013662 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013663 if (!copy)
13664 return NULL;
13665 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013666}
13667
Guido van Rossumd57fd912000-03-10 22:53:23 +000013668static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013669 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013670 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013671 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13672 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013673 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13674 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013675 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013676 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13677 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13678 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013679 {"expandtabs", (PyCFunction) unicode_expandtabs,
13680 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013681 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013682 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013683 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13684 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13685 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013686 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013687 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13688 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13689 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013690 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013691 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013692 {"splitlines", (PyCFunction) unicode_splitlines,
13693 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013694 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013695 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13696 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13697 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13698 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13699 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13700 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13701 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13702 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13703 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13704 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13705 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13706 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13707 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13708 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013709 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013710 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013711 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013712 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013713 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013714 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013715 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013716 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013717#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013718 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013719 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013720#endif
13721
Benjamin Peterson14339b62009-01-31 16:36:08 +000013722 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013723 {NULL, NULL}
13724};
13725
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013726static PyObject *
13727unicode_mod(PyObject *v, PyObject *w)
13728{
Brian Curtindfc80e32011-08-10 20:28:54 -050013729 if (!PyUnicode_Check(v))
13730 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013731 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013732}
13733
13734static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013735 0, /*nb_add*/
13736 0, /*nb_subtract*/
13737 0, /*nb_multiply*/
13738 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013739};
13740
Guido van Rossumd57fd912000-03-10 22:53:23 +000013741static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013742 (lenfunc) unicode_length, /* sq_length */
13743 PyUnicode_Concat, /* sq_concat */
13744 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13745 (ssizeargfunc) unicode_getitem, /* sq_item */
13746 0, /* sq_slice */
13747 0, /* sq_ass_item */
13748 0, /* sq_ass_slice */
13749 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013750};
13751
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013752static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013753unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013754{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013755 if (PyUnicode_READY(self) == -1)
13756 return NULL;
13757
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013758 if (PyIndex_Check(item)) {
13759 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013760 if (i == -1 && PyErr_Occurred())
13761 return NULL;
13762 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013763 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013764 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013765 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013766 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013767 PyObject *result;
13768 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013769 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013770 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013771
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013772 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013773 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013774 return NULL;
13775 }
13776
13777 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013778 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013779 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013780 slicelength == PyUnicode_GET_LENGTH(self)) {
13781 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013782 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013783 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013784 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013785 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013786 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013787 src_kind = PyUnicode_KIND(self);
13788 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013789 if (!PyUnicode_IS_ASCII(self)) {
13790 kind_limit = kind_maxchar_limit(src_kind);
13791 max_char = 0;
13792 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13793 ch = PyUnicode_READ(src_kind, src_data, cur);
13794 if (ch > max_char) {
13795 max_char = ch;
13796 if (max_char >= kind_limit)
13797 break;
13798 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013799 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013800 }
Victor Stinner55c99112011-10-13 01:17:06 +020013801 else
13802 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013803 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013804 if (result == NULL)
13805 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013806 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013807 dest_data = PyUnicode_DATA(result);
13808
13809 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013810 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13811 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013812 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013813 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013814 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013815 } else {
13816 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13817 return NULL;
13818 }
13819}
13820
13821static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013822 (lenfunc)unicode_length, /* mp_length */
13823 (binaryfunc)unicode_subscript, /* mp_subscript */
13824 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013825};
13826
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827
Guido van Rossumd57fd912000-03-10 22:53:23 +000013828/* Helpers for PyUnicode_Format() */
13829
Victor Stinnera47082312012-10-04 02:19:54 +020013830struct unicode_formatter_t {
13831 PyObject *args;
13832 int args_owned;
13833 Py_ssize_t arglen, argidx;
13834 PyObject *dict;
13835
13836 enum PyUnicode_Kind fmtkind;
13837 Py_ssize_t fmtcnt, fmtpos;
13838 void *fmtdata;
13839 PyObject *fmtstr;
13840
13841 _PyUnicodeWriter writer;
13842};
13843
13844struct unicode_format_arg_t {
13845 Py_UCS4 ch;
13846 int flags;
13847 Py_ssize_t width;
13848 int prec;
13849 int sign;
13850};
13851
Guido van Rossumd57fd912000-03-10 22:53:23 +000013852static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013853unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013854{
Victor Stinnera47082312012-10-04 02:19:54 +020013855 Py_ssize_t argidx = ctx->argidx;
13856
13857 if (argidx < ctx->arglen) {
13858 ctx->argidx++;
13859 if (ctx->arglen < 0)
13860 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013861 else
Victor Stinnera47082312012-10-04 02:19:54 +020013862 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013863 }
13864 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013865 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013866 return NULL;
13867}
13868
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013869/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013870
Victor Stinnera47082312012-10-04 02:19:54 +020013871/* Format a float into the writer if the writer is not NULL, or into *p_output
13872 otherwise.
13873
13874 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013875static int
Victor Stinnera47082312012-10-04 02:19:54 +020013876formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13877 PyObject **p_output,
13878 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013879{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013880 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013881 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013882 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013883 int prec;
13884 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013885
Guido van Rossumd57fd912000-03-10 22:53:23 +000013886 x = PyFloat_AsDouble(v);
13887 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013888 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013889
Victor Stinnera47082312012-10-04 02:19:54 +020013890 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013891 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013892 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013893
Victor Stinnera47082312012-10-04 02:19:54 +020013894 if (arg->flags & F_ALT)
13895 dtoa_flags = Py_DTSF_ALT;
13896 else
13897 dtoa_flags = 0;
13898 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013899 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013900 return -1;
13901 len = strlen(p);
13902 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013903 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013904 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013905 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013906 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013907 }
13908 else
13909 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013910 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013911 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013912}
13913
Victor Stinnerd0880d52012-04-27 23:40:13 +020013914/* formatlong() emulates the format codes d, u, o, x and X, and
13915 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13916 * Python's regular ints.
13917 * Return value: a new PyUnicodeObject*, or NULL if error.
13918 * The output string is of the form
13919 * "-"? ("0x" | "0X")? digit+
13920 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13921 * set in flags. The case of hex digits will be correct,
13922 * There will be at least prec digits, zero-filled on the left if
13923 * necessary to get that many.
13924 * val object to be converted
13925 * flags bitmask of format flags; only F_ALT is looked at
13926 * prec minimum number of digits; 0-fill on left if needed
13927 * type a character in [duoxX]; u acts the same as d
13928 *
13929 * CAUTION: o, x and X conversions on regular ints can never
13930 * produce a '-' sign, but can for Python's unbounded ints.
13931 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013932PyObject *
13933_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013934{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013935 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013936 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013937 Py_ssize_t i;
13938 int sign; /* 1 if '-', else 0 */
13939 int len; /* number of characters */
13940 Py_ssize_t llen;
13941 int numdigits; /* len == numnondigits + numdigits */
13942 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013943
Victor Stinnerd0880d52012-04-27 23:40:13 +020013944 /* Avoid exceeding SSIZE_T_MAX */
13945 if (prec > INT_MAX-3) {
13946 PyErr_SetString(PyExc_OverflowError,
13947 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013948 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013949 }
13950
13951 assert(PyLong_Check(val));
13952
13953 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013954 default:
13955 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013956 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013957 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013958 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013959 /* int and int subclasses should print numerically when a numeric */
13960 /* format code is used (see issue18780) */
13961 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013962 break;
13963 case 'o':
13964 numnondigits = 2;
13965 result = PyNumber_ToBase(val, 8);
13966 break;
13967 case 'x':
13968 case 'X':
13969 numnondigits = 2;
13970 result = PyNumber_ToBase(val, 16);
13971 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013972 }
13973 if (!result)
13974 return NULL;
13975
13976 assert(unicode_modifiable(result));
13977 assert(PyUnicode_IS_READY(result));
13978 assert(PyUnicode_IS_ASCII(result));
13979
13980 /* To modify the string in-place, there can only be one reference. */
13981 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013982 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013983 PyErr_BadInternalCall();
13984 return NULL;
13985 }
13986 buf = PyUnicode_DATA(result);
13987 llen = PyUnicode_GET_LENGTH(result);
13988 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013989 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013990 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080013991 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013992 return NULL;
13993 }
13994 len = (int)llen;
13995 sign = buf[0] == '-';
13996 numnondigits += sign;
13997 numdigits = len - numnondigits;
13998 assert(numdigits > 0);
13999
14000 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014001 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014002 (type == 'o' || type == 'x' || type == 'X'))) {
14003 assert(buf[sign] == '0');
14004 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14005 buf[sign+1] == 'o');
14006 numnondigits -= 2;
14007 buf += 2;
14008 len -= 2;
14009 if (sign)
14010 buf[0] = '-';
14011 assert(len == numnondigits + numdigits);
14012 assert(numdigits > 0);
14013 }
14014
14015 /* Fill with leading zeroes to meet minimum width. */
14016 if (prec > numdigits) {
14017 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14018 numnondigits + prec);
14019 char *b1;
14020 if (!r1) {
14021 Py_DECREF(result);
14022 return NULL;
14023 }
14024 b1 = PyBytes_AS_STRING(r1);
14025 for (i = 0; i < numnondigits; ++i)
14026 *b1++ = *buf++;
14027 for (i = 0; i < prec - numdigits; i++)
14028 *b1++ = '0';
14029 for (i = 0; i < numdigits; i++)
14030 *b1++ = *buf++;
14031 *b1 = '\0';
14032 Py_DECREF(result);
14033 result = r1;
14034 buf = PyBytes_AS_STRING(result);
14035 len = numnondigits + prec;
14036 }
14037
14038 /* Fix up case for hex conversions. */
14039 if (type == 'X') {
14040 /* Need to convert all lower case letters to upper case.
14041 and need to convert 0x to 0X (and -0x to -0X). */
14042 for (i = 0; i < len; i++)
14043 if (buf[i] >= 'a' && buf[i] <= 'x')
14044 buf[i] -= 'a'-'A';
14045 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014046 if (!PyUnicode_Check(result)
14047 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014048 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014049 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014050 Py_DECREF(result);
14051 result = unicode;
14052 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014053 else if (len != PyUnicode_GET_LENGTH(result)) {
14054 if (PyUnicode_Resize(&result, len) < 0)
14055 Py_CLEAR(result);
14056 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014057 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014058}
14059
Ethan Furmandf3ed242014-01-05 06:50:30 -080014060/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014061 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014062 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014063 * -1 and raise an exception on error */
14064static int
Victor Stinnera47082312012-10-04 02:19:54 +020014065mainformatlong(PyObject *v,
14066 struct unicode_format_arg_t *arg,
14067 PyObject **p_output,
14068 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014069{
14070 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014071 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014072
14073 if (!PyNumber_Check(v))
14074 goto wrongtype;
14075
Ethan Furman9ab74802014-03-21 06:38:46 -070014076 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014077 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014078 if (type == 'o' || type == 'x' || type == 'X') {
14079 iobj = PyNumber_Index(v);
14080 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014081 if (PyErr_ExceptionMatches(PyExc_TypeError))
14082 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014083 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014084 }
14085 }
14086 else {
14087 iobj = PyNumber_Long(v);
14088 if (iobj == NULL ) {
14089 if (PyErr_ExceptionMatches(PyExc_TypeError))
14090 goto wrongtype;
14091 return -1;
14092 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014093 }
14094 assert(PyLong_Check(iobj));
14095 }
14096 else {
14097 iobj = v;
14098 Py_INCREF(iobj);
14099 }
14100
14101 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014102 && arg->width == -1 && arg->prec == -1
14103 && !(arg->flags & (F_SIGN | F_BLANK))
14104 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014105 {
14106 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014107 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014108 int base;
14109
Victor Stinnera47082312012-10-04 02:19:54 +020014110 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014111 {
14112 default:
14113 assert(0 && "'type' not in [diuoxX]");
14114 case 'd':
14115 case 'i':
14116 case 'u':
14117 base = 10;
14118 break;
14119 case 'o':
14120 base = 8;
14121 break;
14122 case 'x':
14123 case 'X':
14124 base = 16;
14125 break;
14126 }
14127
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014128 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14129 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014130 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014131 }
14132 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014133 return 1;
14134 }
14135
Ethan Furmanb95b5612015-01-23 20:05:18 -080014136 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014137 Py_DECREF(iobj);
14138 if (res == NULL)
14139 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014140 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014141 return 0;
14142
14143wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014144 switch(type)
14145 {
14146 case 'o':
14147 case 'x':
14148 case 'X':
14149 PyErr_Format(PyExc_TypeError,
14150 "%%%c format: an integer is required, "
14151 "not %.200s",
14152 type, Py_TYPE(v)->tp_name);
14153 break;
14154 default:
14155 PyErr_Format(PyExc_TypeError,
14156 "%%%c format: a number is required, "
14157 "not %.200s",
14158 type, Py_TYPE(v)->tp_name);
14159 break;
14160 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014161 return -1;
14162}
14163
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014164static Py_UCS4
14165formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014166{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014167 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014168 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014169 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014170 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014171 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014172 goto onError;
14173 }
14174 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014175 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014176 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014177 /* make sure number is a type of integer */
14178 if (!PyLong_Check(v)) {
14179 iobj = PyNumber_Index(v);
14180 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014181 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014182 }
14183 v = iobj;
14184 Py_DECREF(iobj);
14185 }
14186 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014187 x = PyLong_AsLong(v);
14188 if (x == -1 && PyErr_Occurred())
14189 goto onError;
14190
Victor Stinner8faf8212011-12-08 22:14:11 +010014191 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014192 PyErr_SetString(PyExc_OverflowError,
14193 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014194 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014195 }
14196
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014197 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014198 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014199
Benjamin Peterson29060642009-01-31 22:14:21 +000014200 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014201 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014202 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014203 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014204}
14205
Victor Stinnera47082312012-10-04 02:19:54 +020014206/* Parse options of an argument: flags, width, precision.
14207 Handle also "%(name)" syntax.
14208
14209 Return 0 if the argument has been formatted into arg->str.
14210 Return 1 if the argument has been written into ctx->writer,
14211 Raise an exception and return -1 on error. */
14212static int
14213unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14214 struct unicode_format_arg_t *arg)
14215{
14216#define FORMAT_READ(ctx) \
14217 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14218
14219 PyObject *v;
14220
Victor Stinnera47082312012-10-04 02:19:54 +020014221 if (arg->ch == '(') {
14222 /* Get argument value from a dictionary. Example: "%(name)s". */
14223 Py_ssize_t keystart;
14224 Py_ssize_t keylen;
14225 PyObject *key;
14226 int pcount = 1;
14227
14228 if (ctx->dict == NULL) {
14229 PyErr_SetString(PyExc_TypeError,
14230 "format requires a mapping");
14231 return -1;
14232 }
14233 ++ctx->fmtpos;
14234 --ctx->fmtcnt;
14235 keystart = ctx->fmtpos;
14236 /* Skip over balanced parentheses */
14237 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14238 arg->ch = FORMAT_READ(ctx);
14239 if (arg->ch == ')')
14240 --pcount;
14241 else if (arg->ch == '(')
14242 ++pcount;
14243 ctx->fmtpos++;
14244 }
14245 keylen = ctx->fmtpos - keystart - 1;
14246 if (ctx->fmtcnt < 0 || pcount > 0) {
14247 PyErr_SetString(PyExc_ValueError,
14248 "incomplete format key");
14249 return -1;
14250 }
14251 key = PyUnicode_Substring(ctx->fmtstr,
14252 keystart, keystart + keylen);
14253 if (key == NULL)
14254 return -1;
14255 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014256 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014257 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014258 }
14259 ctx->args = PyObject_GetItem(ctx->dict, key);
14260 Py_DECREF(key);
14261 if (ctx->args == NULL)
14262 return -1;
14263 ctx->args_owned = 1;
14264 ctx->arglen = -1;
14265 ctx->argidx = -2;
14266 }
14267
14268 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014269 while (--ctx->fmtcnt >= 0) {
14270 arg->ch = FORMAT_READ(ctx);
14271 ctx->fmtpos++;
14272 switch (arg->ch) {
14273 case '-': arg->flags |= F_LJUST; continue;
14274 case '+': arg->flags |= F_SIGN; continue;
14275 case ' ': arg->flags |= F_BLANK; continue;
14276 case '#': arg->flags |= F_ALT; continue;
14277 case '0': arg->flags |= F_ZERO; continue;
14278 }
14279 break;
14280 }
14281
14282 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014283 if (arg->ch == '*') {
14284 v = unicode_format_getnextarg(ctx);
14285 if (v == NULL)
14286 return -1;
14287 if (!PyLong_Check(v)) {
14288 PyErr_SetString(PyExc_TypeError,
14289 "* wants int");
14290 return -1;
14291 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014292 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014293 if (arg->width == -1 && PyErr_Occurred())
14294 return -1;
14295 if (arg->width < 0) {
14296 arg->flags |= F_LJUST;
14297 arg->width = -arg->width;
14298 }
14299 if (--ctx->fmtcnt >= 0) {
14300 arg->ch = FORMAT_READ(ctx);
14301 ctx->fmtpos++;
14302 }
14303 }
14304 else if (arg->ch >= '0' && arg->ch <= '9') {
14305 arg->width = arg->ch - '0';
14306 while (--ctx->fmtcnt >= 0) {
14307 arg->ch = FORMAT_READ(ctx);
14308 ctx->fmtpos++;
14309 if (arg->ch < '0' || arg->ch > '9')
14310 break;
14311 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14312 mixing signed and unsigned comparison. Since arg->ch is between
14313 '0' and '9', casting to int is safe. */
14314 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14315 PyErr_SetString(PyExc_ValueError,
14316 "width too big");
14317 return -1;
14318 }
14319 arg->width = arg->width*10 + (arg->ch - '0');
14320 }
14321 }
14322
14323 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014324 if (arg->ch == '.') {
14325 arg->prec = 0;
14326 if (--ctx->fmtcnt >= 0) {
14327 arg->ch = FORMAT_READ(ctx);
14328 ctx->fmtpos++;
14329 }
14330 if (arg->ch == '*') {
14331 v = unicode_format_getnextarg(ctx);
14332 if (v == NULL)
14333 return -1;
14334 if (!PyLong_Check(v)) {
14335 PyErr_SetString(PyExc_TypeError,
14336 "* wants int");
14337 return -1;
14338 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014339 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014340 if (arg->prec == -1 && PyErr_Occurred())
14341 return -1;
14342 if (arg->prec < 0)
14343 arg->prec = 0;
14344 if (--ctx->fmtcnt >= 0) {
14345 arg->ch = FORMAT_READ(ctx);
14346 ctx->fmtpos++;
14347 }
14348 }
14349 else if (arg->ch >= '0' && arg->ch <= '9') {
14350 arg->prec = arg->ch - '0';
14351 while (--ctx->fmtcnt >= 0) {
14352 arg->ch = FORMAT_READ(ctx);
14353 ctx->fmtpos++;
14354 if (arg->ch < '0' || arg->ch > '9')
14355 break;
14356 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14357 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014358 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014359 return -1;
14360 }
14361 arg->prec = arg->prec*10 + (arg->ch - '0');
14362 }
14363 }
14364 }
14365
14366 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14367 if (ctx->fmtcnt >= 0) {
14368 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14369 if (--ctx->fmtcnt >= 0) {
14370 arg->ch = FORMAT_READ(ctx);
14371 ctx->fmtpos++;
14372 }
14373 }
14374 }
14375 if (ctx->fmtcnt < 0) {
14376 PyErr_SetString(PyExc_ValueError,
14377 "incomplete format");
14378 return -1;
14379 }
14380 return 0;
14381
14382#undef FORMAT_READ
14383}
14384
14385/* Format one argument. Supported conversion specifiers:
14386
14387 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014388 - "i", "d", "u": int or float
14389 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014390 - "e", "E", "f", "F", "g", "G": float
14391 - "c": int or str (1 character)
14392
Victor Stinner8dbd4212012-12-04 09:30:24 +010014393 When possible, the output is written directly into the Unicode writer
14394 (ctx->writer). A string is created when padding is required.
14395
Victor Stinnera47082312012-10-04 02:19:54 +020014396 Return 0 if the argument has been formatted into *p_str,
14397 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014398 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014399static int
14400unicode_format_arg_format(struct unicode_formatter_t *ctx,
14401 struct unicode_format_arg_t *arg,
14402 PyObject **p_str)
14403{
14404 PyObject *v;
14405 _PyUnicodeWriter *writer = &ctx->writer;
14406
14407 if (ctx->fmtcnt == 0)
14408 ctx->writer.overallocate = 0;
14409
14410 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014411 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014412 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014413 return 1;
14414 }
14415
14416 v = unicode_format_getnextarg(ctx);
14417 if (v == NULL)
14418 return -1;
14419
Victor Stinnera47082312012-10-04 02:19:54 +020014420
14421 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014422 case 's':
14423 case 'r':
14424 case 'a':
14425 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14426 /* Fast path */
14427 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14428 return -1;
14429 return 1;
14430 }
14431
14432 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14433 *p_str = v;
14434 Py_INCREF(*p_str);
14435 }
14436 else {
14437 if (arg->ch == 's')
14438 *p_str = PyObject_Str(v);
14439 else if (arg->ch == 'r')
14440 *p_str = PyObject_Repr(v);
14441 else
14442 *p_str = PyObject_ASCII(v);
14443 }
14444 break;
14445
14446 case 'i':
14447 case 'd':
14448 case 'u':
14449 case 'o':
14450 case 'x':
14451 case 'X':
14452 {
14453 int ret = mainformatlong(v, arg, p_str, writer);
14454 if (ret != 0)
14455 return ret;
14456 arg->sign = 1;
14457 break;
14458 }
14459
14460 case 'e':
14461 case 'E':
14462 case 'f':
14463 case 'F':
14464 case 'g':
14465 case 'G':
14466 if (arg->width == -1 && arg->prec == -1
14467 && !(arg->flags & (F_SIGN | F_BLANK)))
14468 {
14469 /* Fast path */
14470 if (formatfloat(v, arg, NULL, writer) == -1)
14471 return -1;
14472 return 1;
14473 }
14474
14475 arg->sign = 1;
14476 if (formatfloat(v, arg, p_str, NULL) == -1)
14477 return -1;
14478 break;
14479
14480 case 'c':
14481 {
14482 Py_UCS4 ch = formatchar(v);
14483 if (ch == (Py_UCS4) -1)
14484 return -1;
14485 if (arg->width == -1 && arg->prec == -1) {
14486 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014487 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014488 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014489 return 1;
14490 }
14491 *p_str = PyUnicode_FromOrdinal(ch);
14492 break;
14493 }
14494
14495 default:
14496 PyErr_Format(PyExc_ValueError,
14497 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014498 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014499 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14500 (int)arg->ch,
14501 ctx->fmtpos - 1);
14502 return -1;
14503 }
14504 if (*p_str == NULL)
14505 return -1;
14506 assert (PyUnicode_Check(*p_str));
14507 return 0;
14508}
14509
14510static int
14511unicode_format_arg_output(struct unicode_formatter_t *ctx,
14512 struct unicode_format_arg_t *arg,
14513 PyObject *str)
14514{
14515 Py_ssize_t len;
14516 enum PyUnicode_Kind kind;
14517 void *pbuf;
14518 Py_ssize_t pindex;
14519 Py_UCS4 signchar;
14520 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014521 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014522 Py_ssize_t sublen;
14523 _PyUnicodeWriter *writer = &ctx->writer;
14524 Py_UCS4 fill;
14525
14526 fill = ' ';
14527 if (arg->sign && arg->flags & F_ZERO)
14528 fill = '0';
14529
14530 if (PyUnicode_READY(str) == -1)
14531 return -1;
14532
14533 len = PyUnicode_GET_LENGTH(str);
14534 if ((arg->width == -1 || arg->width <= len)
14535 && (arg->prec == -1 || arg->prec >= len)
14536 && !(arg->flags & (F_SIGN | F_BLANK)))
14537 {
14538 /* Fast path */
14539 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14540 return -1;
14541 return 0;
14542 }
14543
14544 /* Truncate the string for "s", "r" and "a" formats
14545 if the precision is set */
14546 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14547 if (arg->prec >= 0 && len > arg->prec)
14548 len = arg->prec;
14549 }
14550
14551 /* Adjust sign and width */
14552 kind = PyUnicode_KIND(str);
14553 pbuf = PyUnicode_DATA(str);
14554 pindex = 0;
14555 signchar = '\0';
14556 if (arg->sign) {
14557 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14558 if (ch == '-' || ch == '+') {
14559 signchar = ch;
14560 len--;
14561 pindex++;
14562 }
14563 else if (arg->flags & F_SIGN)
14564 signchar = '+';
14565 else if (arg->flags & F_BLANK)
14566 signchar = ' ';
14567 else
14568 arg->sign = 0;
14569 }
14570 if (arg->width < len)
14571 arg->width = len;
14572
14573 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014574 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014575 if (!(arg->flags & F_LJUST)) {
14576 if (arg->sign) {
14577 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014578 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014579 }
14580 else {
14581 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014582 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014583 }
14584 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014585 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14586 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014587 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014588 }
14589
Victor Stinnera47082312012-10-04 02:19:54 +020014590 buflen = arg->width;
14591 if (arg->sign && len == arg->width)
14592 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014593 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014594 return -1;
14595
14596 /* Write the sign if needed */
14597 if (arg->sign) {
14598 if (fill != ' ') {
14599 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14600 writer->pos += 1;
14601 }
14602 if (arg->width > len)
14603 arg->width--;
14604 }
14605
14606 /* Write the numeric prefix for "x", "X" and "o" formats
14607 if the alternate form is used.
14608 For example, write "0x" for the "%#x" format. */
14609 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14610 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14611 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14612 if (fill != ' ') {
14613 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14614 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14615 writer->pos += 2;
14616 pindex += 2;
14617 }
14618 arg->width -= 2;
14619 if (arg->width < 0)
14620 arg->width = 0;
14621 len -= 2;
14622 }
14623
14624 /* Pad left with the fill character if needed */
14625 if (arg->width > len && !(arg->flags & F_LJUST)) {
14626 sublen = arg->width - len;
14627 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14628 writer->pos += sublen;
14629 arg->width = len;
14630 }
14631
14632 /* If padding with spaces: write sign if needed and/or numeric prefix if
14633 the alternate form is used */
14634 if (fill == ' ') {
14635 if (arg->sign) {
14636 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14637 writer->pos += 1;
14638 }
14639 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14640 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14641 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14642 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14643 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14644 writer->pos += 2;
14645 pindex += 2;
14646 }
14647 }
14648
14649 /* Write characters */
14650 if (len) {
14651 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14652 str, pindex, len);
14653 writer->pos += len;
14654 }
14655
14656 /* Pad right with the fill character if needed */
14657 if (arg->width > len) {
14658 sublen = arg->width - len;
14659 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14660 writer->pos += sublen;
14661 }
14662 return 0;
14663}
14664
14665/* Helper of PyUnicode_Format(): format one arg.
14666 Return 0 on success, raise an exception and return -1 on error. */
14667static int
14668unicode_format_arg(struct unicode_formatter_t *ctx)
14669{
14670 struct unicode_format_arg_t arg;
14671 PyObject *str;
14672 int ret;
14673
Victor Stinner8dbd4212012-12-04 09:30:24 +010014674 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14675 arg.flags = 0;
14676 arg.width = -1;
14677 arg.prec = -1;
14678 arg.sign = 0;
14679 str = NULL;
14680
Victor Stinnera47082312012-10-04 02:19:54 +020014681 ret = unicode_format_arg_parse(ctx, &arg);
14682 if (ret == -1)
14683 return -1;
14684
14685 ret = unicode_format_arg_format(ctx, &arg, &str);
14686 if (ret == -1)
14687 return -1;
14688
14689 if (ret != 1) {
14690 ret = unicode_format_arg_output(ctx, &arg, str);
14691 Py_DECREF(str);
14692 if (ret == -1)
14693 return -1;
14694 }
14695
14696 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14697 PyErr_SetString(PyExc_TypeError,
14698 "not all arguments converted during string formatting");
14699 return -1;
14700 }
14701 return 0;
14702}
14703
Alexander Belopolsky40018472011-02-26 01:02:56 +000014704PyObject *
14705PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014706{
Victor Stinnera47082312012-10-04 02:19:54 +020014707 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014708
Guido van Rossumd57fd912000-03-10 22:53:23 +000014709 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014710 PyErr_BadInternalCall();
14711 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014712 }
Victor Stinnera47082312012-10-04 02:19:54 +020014713
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014714 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014715 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014716
14717 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014718 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14719 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14720 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14721 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014722
Victor Stinner8f674cc2013-04-17 23:02:17 +020014723 _PyUnicodeWriter_Init(&ctx.writer);
14724 ctx.writer.min_length = ctx.fmtcnt + 100;
14725 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014726
Guido van Rossumd57fd912000-03-10 22:53:23 +000014727 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014728 ctx.arglen = PyTuple_Size(args);
14729 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014730 }
14731 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014732 ctx.arglen = -1;
14733 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014734 }
Victor Stinnera47082312012-10-04 02:19:54 +020014735 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014736 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014737 ctx.dict = args;
14738 else
14739 ctx.dict = NULL;
14740 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014741
Victor Stinnera47082312012-10-04 02:19:54 +020014742 while (--ctx.fmtcnt >= 0) {
14743 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014744 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014745
14746 nonfmtpos = ctx.fmtpos++;
14747 while (ctx.fmtcnt >= 0 &&
14748 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14749 ctx.fmtpos++;
14750 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014751 }
Victor Stinnera47082312012-10-04 02:19:54 +020014752 if (ctx.fmtcnt < 0) {
14753 ctx.fmtpos--;
14754 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014755 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014756
Victor Stinnercfc4c132013-04-03 01:48:39 +020014757 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14758 nonfmtpos, ctx.fmtpos) < 0)
14759 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014760 }
14761 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014762 ctx.fmtpos++;
14763 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014764 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014765 }
14766 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014767
Victor Stinnera47082312012-10-04 02:19:54 +020014768 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014769 PyErr_SetString(PyExc_TypeError,
14770 "not all arguments converted during string formatting");
14771 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014772 }
14773
Victor Stinnera47082312012-10-04 02:19:54 +020014774 if (ctx.args_owned) {
14775 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014776 }
Victor Stinnera47082312012-10-04 02:19:54 +020014777 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014778
Benjamin Peterson29060642009-01-31 22:14:21 +000014779 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014780 _PyUnicodeWriter_Dealloc(&ctx.writer);
14781 if (ctx.args_owned) {
14782 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014783 }
14784 return NULL;
14785}
14786
Jeremy Hylton938ace62002-07-17 16:30:39 +000014787static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014788unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14789
Tim Peters6d6c1a32001-08-02 04:15:00 +000014790static PyObject *
14791unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14792{
Benjamin Peterson29060642009-01-31 22:14:21 +000014793 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014794 static char *kwlist[] = {"object", "encoding", "errors", 0};
14795 char *encoding = NULL;
14796 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014797
Benjamin Peterson14339b62009-01-31 16:36:08 +000014798 if (type != &PyUnicode_Type)
14799 return unicode_subtype_new(type, args, kwds);
14800 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014801 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014802 return NULL;
14803 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014804 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014805 if (encoding == NULL && errors == NULL)
14806 return PyObject_Str(x);
14807 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014808 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014809}
14810
Guido van Rossume023fe02001-08-30 03:12:59 +000014811static PyObject *
14812unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14813{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014814 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014815 Py_ssize_t length, char_size;
14816 int share_wstr, share_utf8;
14817 unsigned int kind;
14818 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014819
Benjamin Peterson14339b62009-01-31 16:36:08 +000014820 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014821
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014822 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014823 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014824 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014825 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014826 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014827 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014828 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014829 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014830
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014831 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014832 if (self == NULL) {
14833 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014834 return NULL;
14835 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014836 kind = PyUnicode_KIND(unicode);
14837 length = PyUnicode_GET_LENGTH(unicode);
14838
14839 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014840#ifdef Py_DEBUG
14841 _PyUnicode_HASH(self) = -1;
14842#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014843 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014844#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014845 _PyUnicode_STATE(self).interned = 0;
14846 _PyUnicode_STATE(self).kind = kind;
14847 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014848 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014849 _PyUnicode_STATE(self).ready = 1;
14850 _PyUnicode_WSTR(self) = NULL;
14851 _PyUnicode_UTF8_LENGTH(self) = 0;
14852 _PyUnicode_UTF8(self) = NULL;
14853 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014854 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014855
14856 share_utf8 = 0;
14857 share_wstr = 0;
14858 if (kind == PyUnicode_1BYTE_KIND) {
14859 char_size = 1;
14860 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14861 share_utf8 = 1;
14862 }
14863 else if (kind == PyUnicode_2BYTE_KIND) {
14864 char_size = 2;
14865 if (sizeof(wchar_t) == 2)
14866 share_wstr = 1;
14867 }
14868 else {
14869 assert(kind == PyUnicode_4BYTE_KIND);
14870 char_size = 4;
14871 if (sizeof(wchar_t) == 4)
14872 share_wstr = 1;
14873 }
14874
14875 /* Ensure we won't overflow the length. */
14876 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14877 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014878 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014879 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014880 data = PyObject_MALLOC((length + 1) * char_size);
14881 if (data == NULL) {
14882 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014883 goto onError;
14884 }
14885
Victor Stinnerc3c74152011-10-02 20:39:55 +020014886 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014887 if (share_utf8) {
14888 _PyUnicode_UTF8_LENGTH(self) = length;
14889 _PyUnicode_UTF8(self) = data;
14890 }
14891 if (share_wstr) {
14892 _PyUnicode_WSTR_LENGTH(self) = length;
14893 _PyUnicode_WSTR(self) = (wchar_t *)data;
14894 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014895
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014896 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014897 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014898 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014899#ifdef Py_DEBUG
14900 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14901#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014902 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014903 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014904
14905onError:
14906 Py_DECREF(unicode);
14907 Py_DECREF(self);
14908 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014909}
14910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014911PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014912"str(object='') -> str\n\
14913str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014914\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014915Create a new string object from the given object. If encoding or\n\
14916errors is specified, then the object must expose a data buffer\n\
14917that will be decoded using the given encoding and error handler.\n\
14918Otherwise, returns the result of object.__str__() (if defined)\n\
14919or repr(object).\n\
14920encoding defaults to sys.getdefaultencoding().\n\
14921errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014922
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014923static PyObject *unicode_iter(PyObject *seq);
14924
Guido van Rossumd57fd912000-03-10 22:53:23 +000014925PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014926 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014927 "str", /* tp_name */
14928 sizeof(PyUnicodeObject), /* tp_size */
14929 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014930 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014931 (destructor)unicode_dealloc, /* tp_dealloc */
14932 0, /* tp_print */
14933 0, /* tp_getattr */
14934 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014935 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014936 unicode_repr, /* tp_repr */
14937 &unicode_as_number, /* tp_as_number */
14938 &unicode_as_sequence, /* tp_as_sequence */
14939 &unicode_as_mapping, /* tp_as_mapping */
14940 (hashfunc) unicode_hash, /* tp_hash*/
14941 0, /* tp_call*/
14942 (reprfunc) unicode_str, /* tp_str */
14943 PyObject_GenericGetAttr, /* tp_getattro */
14944 0, /* tp_setattro */
14945 0, /* tp_as_buffer */
14946 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014947 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014948 unicode_doc, /* tp_doc */
14949 0, /* tp_traverse */
14950 0, /* tp_clear */
14951 PyUnicode_RichCompare, /* tp_richcompare */
14952 0, /* tp_weaklistoffset */
14953 unicode_iter, /* tp_iter */
14954 0, /* tp_iternext */
14955 unicode_methods, /* tp_methods */
14956 0, /* tp_members */
14957 0, /* tp_getset */
14958 &PyBaseObject_Type, /* tp_base */
14959 0, /* tp_dict */
14960 0, /* tp_descr_get */
14961 0, /* tp_descr_set */
14962 0, /* tp_dictoffset */
14963 0, /* tp_init */
14964 0, /* tp_alloc */
14965 unicode_new, /* tp_new */
14966 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014967};
14968
14969/* Initialize the Unicode implementation */
14970
Victor Stinner3a50e702011-10-18 21:21:00 +020014971int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014972{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014973 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014974 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014975 0x000A, /* LINE FEED */
14976 0x000D, /* CARRIAGE RETURN */
14977 0x001C, /* FILE SEPARATOR */
14978 0x001D, /* GROUP SEPARATOR */
14979 0x001E, /* RECORD SEPARATOR */
14980 0x0085, /* NEXT LINE */
14981 0x2028, /* LINE SEPARATOR */
14982 0x2029, /* PARAGRAPH SEPARATOR */
14983 };
14984
Fred Drakee4315f52000-05-09 19:53:39 +000014985 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014986 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014987 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014988 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014989 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014990
Guido van Rossumcacfc072002-05-24 19:01:59 +000014991 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014992 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014993
14994 /* initialize the linebreak bloom filter */
14995 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014996 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014997 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014998
Christian Heimes26532f72013-07-20 14:57:16 +020014999 if (PyType_Ready(&EncodingMapType) < 0)
15000 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015001
Benjamin Petersonc4311282012-10-30 23:21:10 -040015002 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15003 Py_FatalError("Can't initialize field name iterator type");
15004
15005 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15006 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015007
Victor Stinner3a50e702011-10-18 21:21:00 +020015008 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015009}
15010
15011/* Finalize the Unicode implementation */
15012
Christian Heimesa156e092008-02-16 07:38:31 +000015013int
15014PyUnicode_ClearFreeList(void)
15015{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015016 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015017}
15018
Guido van Rossumd57fd912000-03-10 22:53:23 +000015019void
Thomas Wouters78890102000-07-22 19:25:51 +000015020_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015021{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015022 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015023
Serhiy Storchaka05997252013-01-26 12:14:02 +020015024 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015025
Serhiy Storchaka05997252013-01-26 12:14:02 +020015026 for (i = 0; i < 256; i++)
15027 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015028 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015029 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015030}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015031
Walter Dörwald16807132007-05-25 13:52:07 +000015032void
15033PyUnicode_InternInPlace(PyObject **p)
15034{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015035 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015036 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015037#ifdef Py_DEBUG
15038 assert(s != NULL);
15039 assert(_PyUnicode_CHECK(s));
15040#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015041 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015042 return;
15043#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015044 /* If it's a subclass, we don't really know what putting
15045 it in the interned dict might do. */
15046 if (!PyUnicode_CheckExact(s))
15047 return;
15048 if (PyUnicode_CHECK_INTERNED(s))
15049 return;
15050 if (interned == NULL) {
15051 interned = PyDict_New();
15052 if (interned == NULL) {
15053 PyErr_Clear(); /* Don't leave an exception */
15054 return;
15055 }
15056 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015057 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015058 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015059 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015060 if (t == NULL) {
15061 PyErr_Clear();
15062 return;
15063 }
15064 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015065 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015066 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015067 return;
15068 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015069 /* The two references in interned are not counted by refcnt.
15070 The deallocator will take care of this */
15071 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015072 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015073}
15074
15075void
15076PyUnicode_InternImmortal(PyObject **p)
15077{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015078 PyUnicode_InternInPlace(p);
15079 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015080 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015081 Py_INCREF(*p);
15082 }
Walter Dörwald16807132007-05-25 13:52:07 +000015083}
15084
15085PyObject *
15086PyUnicode_InternFromString(const char *cp)
15087{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015088 PyObject *s = PyUnicode_FromString(cp);
15089 if (s == NULL)
15090 return NULL;
15091 PyUnicode_InternInPlace(&s);
15092 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015093}
15094
Alexander Belopolsky40018472011-02-26 01:02:56 +000015095void
15096_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015097{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015098 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015099 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015100 Py_ssize_t i, n;
15101 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015102
Benjamin Peterson14339b62009-01-31 16:36:08 +000015103 if (interned == NULL || !PyDict_Check(interned))
15104 return;
15105 keys = PyDict_Keys(interned);
15106 if (keys == NULL || !PyList_Check(keys)) {
15107 PyErr_Clear();
15108 return;
15109 }
Walter Dörwald16807132007-05-25 13:52:07 +000015110
Benjamin Peterson14339b62009-01-31 16:36:08 +000015111 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15112 detector, interned unicode strings are not forcibly deallocated;
15113 rather, we give them their stolen references back, and then clear
15114 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015115
Benjamin Peterson14339b62009-01-31 16:36:08 +000015116 n = PyList_GET_SIZE(keys);
15117 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015118 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015119 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015120 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015121 if (PyUnicode_READY(s) == -1) {
15122 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015123 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015124 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015125 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015126 case SSTATE_NOT_INTERNED:
15127 /* XXX Shouldn't happen */
15128 break;
15129 case SSTATE_INTERNED_IMMORTAL:
15130 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015131 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015132 break;
15133 case SSTATE_INTERNED_MORTAL:
15134 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015135 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015136 break;
15137 default:
15138 Py_FatalError("Inconsistent interned string state.");
15139 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015140 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015141 }
15142 fprintf(stderr, "total size of all interned strings: "
15143 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15144 "mortal/immortal\n", mortal_size, immortal_size);
15145 Py_DECREF(keys);
15146 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015147 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015148}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015149
15150
15151/********************* Unicode Iterator **************************/
15152
15153typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015154 PyObject_HEAD
15155 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015156 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015157} unicodeiterobject;
15158
15159static void
15160unicodeiter_dealloc(unicodeiterobject *it)
15161{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015162 _PyObject_GC_UNTRACK(it);
15163 Py_XDECREF(it->it_seq);
15164 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015165}
15166
15167static int
15168unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15169{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015170 Py_VISIT(it->it_seq);
15171 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015172}
15173
15174static PyObject *
15175unicodeiter_next(unicodeiterobject *it)
15176{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015177 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015178
Benjamin Peterson14339b62009-01-31 16:36:08 +000015179 assert(it != NULL);
15180 seq = it->it_seq;
15181 if (seq == NULL)
15182 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015183 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015184
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015185 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15186 int kind = PyUnicode_KIND(seq);
15187 void *data = PyUnicode_DATA(seq);
15188 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15189 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015190 if (item != NULL)
15191 ++it->it_index;
15192 return item;
15193 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015194
Benjamin Peterson14339b62009-01-31 16:36:08 +000015195 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015196 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015197 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015198}
15199
15200static PyObject *
15201unicodeiter_len(unicodeiterobject *it)
15202{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015203 Py_ssize_t len = 0;
15204 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015205 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015206 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015207}
15208
15209PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15210
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015211static PyObject *
15212unicodeiter_reduce(unicodeiterobject *it)
15213{
15214 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015215 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015216 it->it_seq, it->it_index);
15217 } else {
15218 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15219 if (u == NULL)
15220 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015221 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015222 }
15223}
15224
15225PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15226
15227static PyObject *
15228unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15229{
15230 Py_ssize_t index = PyLong_AsSsize_t(state);
15231 if (index == -1 && PyErr_Occurred())
15232 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015233 if (it->it_seq != NULL) {
15234 if (index < 0)
15235 index = 0;
15236 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15237 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15238 it->it_index = index;
15239 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015240 Py_RETURN_NONE;
15241}
15242
15243PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15244
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015245static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015246 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015247 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015248 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15249 reduce_doc},
15250 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15251 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015252 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015253};
15254
15255PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015256 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15257 "str_iterator", /* tp_name */
15258 sizeof(unicodeiterobject), /* tp_basicsize */
15259 0, /* tp_itemsize */
15260 /* methods */
15261 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15262 0, /* tp_print */
15263 0, /* tp_getattr */
15264 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015265 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015266 0, /* tp_repr */
15267 0, /* tp_as_number */
15268 0, /* tp_as_sequence */
15269 0, /* tp_as_mapping */
15270 0, /* tp_hash */
15271 0, /* tp_call */
15272 0, /* tp_str */
15273 PyObject_GenericGetAttr, /* tp_getattro */
15274 0, /* tp_setattro */
15275 0, /* tp_as_buffer */
15276 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15277 0, /* tp_doc */
15278 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15279 0, /* tp_clear */
15280 0, /* tp_richcompare */
15281 0, /* tp_weaklistoffset */
15282 PyObject_SelfIter, /* tp_iter */
15283 (iternextfunc)unicodeiter_next, /* tp_iternext */
15284 unicodeiter_methods, /* tp_methods */
15285 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015286};
15287
15288static PyObject *
15289unicode_iter(PyObject *seq)
15290{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015291 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015292
Benjamin Peterson14339b62009-01-31 16:36:08 +000015293 if (!PyUnicode_Check(seq)) {
15294 PyErr_BadInternalCall();
15295 return NULL;
15296 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015297 if (PyUnicode_READY(seq) == -1)
15298 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015299 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15300 if (it == NULL)
15301 return NULL;
15302 it->it_index = 0;
15303 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015304 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015305 _PyObject_GC_TRACK(it);
15306 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015307}
15308
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015309
15310size_t
15311Py_UNICODE_strlen(const Py_UNICODE *u)
15312{
15313 int res = 0;
15314 while(*u++)
15315 res++;
15316 return res;
15317}
15318
15319Py_UNICODE*
15320Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15321{
15322 Py_UNICODE *u = s1;
15323 while ((*u++ = *s2++));
15324 return s1;
15325}
15326
15327Py_UNICODE*
15328Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15329{
15330 Py_UNICODE *u = s1;
15331 while ((*u++ = *s2++))
15332 if (n-- == 0)
15333 break;
15334 return s1;
15335}
15336
15337Py_UNICODE*
15338Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15339{
15340 Py_UNICODE *u1 = s1;
15341 u1 += Py_UNICODE_strlen(u1);
15342 Py_UNICODE_strcpy(u1, s2);
15343 return s1;
15344}
15345
15346int
15347Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15348{
15349 while (*s1 && *s2 && *s1 == *s2)
15350 s1++, s2++;
15351 if (*s1 && *s2)
15352 return (*s1 < *s2) ? -1 : +1;
15353 if (*s1)
15354 return 1;
15355 if (*s2)
15356 return -1;
15357 return 0;
15358}
15359
15360int
15361Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15362{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015363 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015364 for (; n != 0; n--) {
15365 u1 = *s1;
15366 u2 = *s2;
15367 if (u1 != u2)
15368 return (u1 < u2) ? -1 : +1;
15369 if (u1 == '\0')
15370 return 0;
15371 s1++;
15372 s2++;
15373 }
15374 return 0;
15375}
15376
15377Py_UNICODE*
15378Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15379{
15380 const Py_UNICODE *p;
15381 for (p = s; *p; p++)
15382 if (*p == c)
15383 return (Py_UNICODE*)p;
15384 return NULL;
15385}
15386
15387Py_UNICODE*
15388Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15389{
15390 const Py_UNICODE *p;
15391 p = s + Py_UNICODE_strlen(s);
15392 while (p != s) {
15393 p--;
15394 if (*p == c)
15395 return (Py_UNICODE*)p;
15396 }
15397 return NULL;
15398}
Victor Stinner331ea922010-08-10 16:37:20 +000015399
Victor Stinner71133ff2010-09-01 23:43:53 +000015400Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015401PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015402{
Victor Stinner577db2c2011-10-11 22:12:48 +020015403 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015404 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015406 if (!PyUnicode_Check(unicode)) {
15407 PyErr_BadArgument();
15408 return NULL;
15409 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015410 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015411 if (u == NULL)
15412 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015413 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015414 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015415 PyErr_NoMemory();
15416 return NULL;
15417 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015418 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015419 size *= sizeof(Py_UNICODE);
15420 copy = PyMem_Malloc(size);
15421 if (copy == NULL) {
15422 PyErr_NoMemory();
15423 return NULL;
15424 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015425 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015426 return copy;
15427}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015428
Georg Brandl66c221e2010-10-14 07:04:07 +000015429/* A _string module, to export formatter_parser and formatter_field_name_split
15430 to the string.Formatter class implemented in Python. */
15431
15432static PyMethodDef _string_methods[] = {
15433 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15434 METH_O, PyDoc_STR("split the argument as a field name")},
15435 {"formatter_parser", (PyCFunction) formatter_parser,
15436 METH_O, PyDoc_STR("parse the argument as a format string")},
15437 {NULL, NULL}
15438};
15439
15440static struct PyModuleDef _string_module = {
15441 PyModuleDef_HEAD_INIT,
15442 "_string",
15443 PyDoc_STR("string helper module"),
15444 0,
15445 _string_methods,
15446 NULL,
15447 NULL,
15448 NULL,
15449 NULL
15450};
15451
15452PyMODINIT_FUNC
15453PyInit__string(void)
15454{
15455 return PyModule_Create(&_string_module);
15456}
15457
15458
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015459#ifdef __cplusplus
15460}
15461#endif