blob: 6ab691ff25a5a3cc03f402e5d51c7d34f64ab848 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070045#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000046
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000047#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000048#include <windows.h>
49#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000050
Larry Hastings61272b72014-01-07 12:41:53 -080051/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080052class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080053[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080054/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080055
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000056/* --- Globals ------------------------------------------------------------
57
Serhiy Storchaka05997252013-01-26 12:14:02 +020058NOTE: In the interpreter's initialization phase, some globals are currently
59 initialized dynamically as needed. In the process Unicode objects may
60 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061
62*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064
65#ifdef __cplusplus
66extern "C" {
67#endif
68
Victor Stinner8faf8212011-12-08 22:14:11 +010069/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
70#define MAX_UNICODE 0x10ffff
71
Victor Stinner910337b2011-10-03 03:20:16 +020072#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020073# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020074#else
75# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
76#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020077
Victor Stinnere90fe6a2011-10-01 16:48:13 +020078#define _PyUnicode_UTF8(op) \
79 (((PyCompactUnicodeObject*)(op))->utf8)
80#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020081 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020082 assert(PyUnicode_IS_READY(op)), \
83 PyUnicode_IS_COMPACT_ASCII(op) ? \
84 ((char*)((PyASCIIObject*)(op) + 1)) : \
85 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020086#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020087 (((PyCompactUnicodeObject*)(op))->utf8_length)
88#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020089 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020090 assert(PyUnicode_IS_READY(op)), \
91 PyUnicode_IS_COMPACT_ASCII(op) ? \
92 ((PyASCIIObject*)(op))->length : \
93 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020094#define _PyUnicode_WSTR(op) \
95 (((PyASCIIObject*)(op))->wstr)
96#define _PyUnicode_WSTR_LENGTH(op) \
97 (((PyCompactUnicodeObject*)(op))->wstr_length)
98#define _PyUnicode_LENGTH(op) \
99 (((PyASCIIObject *)(op))->length)
100#define _PyUnicode_STATE(op) \
101 (((PyASCIIObject *)(op))->state)
102#define _PyUnicode_HASH(op) \
103 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200104#define _PyUnicode_KIND(op) \
105 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200106 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200107#define _PyUnicode_GET_LENGTH(op) \
108 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200109 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200110#define _PyUnicode_DATA_ANY(op) \
111 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200112
Victor Stinner910337b2011-10-03 03:20:16 +0200113#undef PyUnicode_READY
114#define PyUnicode_READY(op) \
115 (assert(_PyUnicode_CHECK(op)), \
116 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200117 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100118 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200119
Victor Stinnerc379ead2011-10-03 12:52:27 +0200120#define _PyUnicode_SHARE_UTF8(op) \
121 (assert(_PyUnicode_CHECK(op)), \
122 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
123 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
124#define _PyUnicode_SHARE_WSTR(op) \
125 (assert(_PyUnicode_CHECK(op)), \
126 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
127
Victor Stinner829c0ad2011-10-03 01:08:02 +0200128/* true if the Unicode object has an allocated UTF-8 memory block
129 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200130#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200131 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200132 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200133 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
134
Victor Stinner03490912011-10-03 23:45:12 +0200135/* true if the Unicode object has an allocated wstr memory block
136 (not shared with other data) */
137#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200138 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200139 (!PyUnicode_IS_READY(op) || \
140 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
141
Victor Stinner910337b2011-10-03 03:20:16 +0200142/* Generic helper macro to convert characters of different types.
143 from_type and to_type have to be valid type names, begin and end
144 are pointers to the source characters which should be of type
145 "from_type *". to is a pointer of type "to_type *" and points to the
146 buffer where the result characters are written to. */
147#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
148 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100149 to_type *_to = (to_type *)(to); \
150 const from_type *_iter = (from_type *)(begin); \
151 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200152 Py_ssize_t n = (_end) - (_iter); \
153 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200154 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200155 while (_iter < (_unrolled_end)) { \
156 _to[0] = (to_type) _iter[0]; \
157 _to[1] = (to_type) _iter[1]; \
158 _to[2] = (to_type) _iter[2]; \
159 _to[3] = (to_type) _iter[3]; \
160 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200161 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200162 while (_iter < (_end)) \
163 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200164 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200165
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200166#ifdef MS_WINDOWS
167 /* On Windows, overallocate by 50% is the best factor */
168# define OVERALLOCATE_FACTOR 2
169#else
170 /* On Linux, overallocate by 25% is the best factor */
171# define OVERALLOCATE_FACTOR 4
172#endif
173
Walter Dörwald16807132007-05-25 13:52:07 +0000174/* This dictionary holds all interned unicode strings. Note that references
175 to strings in this dictionary are *not* counted in the string's ob_refcnt.
176 When the interned string reaches a refcnt of 0 the string deallocation
177 function will delete the reference from this dictionary.
178
179 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000180 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000181*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200182static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200185static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200186
Serhiy Storchaka678db842013-01-26 12:16:36 +0200187#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 do { \
189 if (unicode_empty != NULL) \
190 Py_INCREF(unicode_empty); \
191 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200192 unicode_empty = PyUnicode_New(0, 0); \
193 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200194 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200195 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
196 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200198 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200#define _Py_RETURN_UNICODE_EMPTY() \
201 do { \
202 _Py_INCREF_UNICODE_EMPTY(); \
203 return unicode_empty; \
204 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000205
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200206/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700207static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200208_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
209
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200210/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200211static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200212
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000213/* Single character Unicode strings in the Latin-1 range are being
214 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000216
Christian Heimes190d79e2008-01-30 11:58:22 +0000217/* Fast detection of the most frequent whitespace characters */
218const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000219 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000220/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000221/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000222/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x000C: * FORM FEED */
224/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000225 0, 1, 1, 1, 1, 1, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000227/* case 0x001C: * FILE SEPARATOR */
228/* case 0x001D: * GROUP SEPARATOR */
229/* case 0x001E: * RECORD SEPARATOR */
230/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000231 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000232/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000233 1, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000237
Benjamin Peterson14339b62009-01-31 16:36:08 +0000238 0, 0, 0, 0, 0, 0, 0, 0,
239 0, 0, 0, 0, 0, 0, 0, 0,
240 0, 0, 0, 0, 0, 0, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
242 0, 0, 0, 0, 0, 0, 0, 0,
243 0, 0, 0, 0, 0, 0, 0, 0,
244 0, 0, 0, 0, 0, 0, 0, 0,
245 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000246};
247
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200248/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200249static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200250static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100251static int unicode_modifiable(PyObject *unicode);
252
Victor Stinnerfe226c02011-10-03 03:52:20 +0200253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100255_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200256static PyObject *
257_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
258static PyObject *
259_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
260
261static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000262unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000263 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100264 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000265 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
266
Alexander Belopolsky40018472011-02-26 01:02:56 +0000267static void
268raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300269 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100270 PyObject *unicode,
271 Py_ssize_t startpos, Py_ssize_t endpos,
272 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000273
Christian Heimes190d79e2008-01-30 11:58:22 +0000274/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200275static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000276 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000277/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000278/* 0x000B, * LINE TABULATION */
279/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000280/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000281 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000282 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000283/* 0x001C, * FILE SEPARATOR */
284/* 0x001D, * GROUP SEPARATOR */
285/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 0, 0, 0, 0, 1, 1, 1, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000291
Benjamin Peterson14339b62009-01-31 16:36:08 +0000292 0, 0, 0, 0, 0, 0, 0, 0,
293 0, 0, 0, 0, 0, 0, 0, 0,
294 0, 0, 0, 0, 0, 0, 0, 0,
295 0, 0, 0, 0, 0, 0, 0, 0,
296 0, 0, 0, 0, 0, 0, 0, 0,
297 0, 0, 0, 0, 0, 0, 0, 0,
298 0, 0, 0, 0, 0, 0, 0, 0,
299 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000300};
301
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300302#include "clinic/unicodeobject.c.h"
303
Victor Stinner50149202015-09-22 00:26:54 +0200304typedef enum {
305 _Py_ERROR_UNKNOWN=0,
306 _Py_ERROR_STRICT,
307 _Py_ERROR_SURROGATEESCAPE,
308 _Py_ERROR_REPLACE,
309 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200310 _Py_ERROR_BACKSLASHREPLACE,
311 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200312 _Py_ERROR_XMLCHARREFREPLACE,
313 _Py_ERROR_OTHER
314} _Py_error_handler;
315
316static _Py_error_handler
317get_error_handler(const char *errors)
318{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200319 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200320 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200321 }
322 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200323 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200324 }
325 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200326 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200327 }
328 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200329 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200330 }
331 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200332 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200333 }
334 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200335 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200336 }
337 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200338 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200339 }
Victor Stinner50149202015-09-22 00:26:54 +0200340 return _Py_ERROR_OTHER;
341}
342
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300343/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
344 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000345Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000346PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000347{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000348#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000349 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000350#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000351 /* This is actually an illegal character, so it should
352 not be passed to unichr. */
353 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000354#endif
355}
356
Victor Stinner910337b2011-10-03 03:20:16 +0200357#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200358int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100359_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200360{
361 PyASCIIObject *ascii;
362 unsigned int kind;
363
364 assert(PyUnicode_Check(op));
365
366 ascii = (PyASCIIObject *)op;
367 kind = ascii->state.kind;
368
Victor Stinnera3b334d2011-10-03 13:53:37 +0200369 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200370 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200371 assert(ascii->state.ready == 1);
372 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200373 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200374 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200375 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200376
Victor Stinnera41463c2011-10-04 01:05:08 +0200377 if (ascii->state.compact == 1) {
378 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200379 assert(kind == PyUnicode_1BYTE_KIND
380 || kind == PyUnicode_2BYTE_KIND
381 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200382 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200383 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200384 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100385 }
386 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200387 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
388
389 data = unicode->data.any;
390 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100391 assert(ascii->length == 0);
392 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200393 assert(ascii->state.compact == 0);
394 assert(ascii->state.ascii == 0);
395 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100396 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200397 assert(ascii->wstr != NULL);
398 assert(data == NULL);
399 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200400 }
401 else {
402 assert(kind == PyUnicode_1BYTE_KIND
403 || kind == PyUnicode_2BYTE_KIND
404 || kind == PyUnicode_4BYTE_KIND);
405 assert(ascii->state.compact == 0);
406 assert(ascii->state.ready == 1);
407 assert(data != NULL);
408 if (ascii->state.ascii) {
409 assert (compact->utf8 == data);
410 assert (compact->utf8_length == ascii->length);
411 }
412 else
413 assert (compact->utf8 != data);
414 }
415 }
416 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200417 if (
418#if SIZEOF_WCHAR_T == 2
419 kind == PyUnicode_2BYTE_KIND
420#else
421 kind == PyUnicode_4BYTE_KIND
422#endif
423 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200424 {
425 assert(ascii->wstr == data);
426 assert(compact->wstr_length == ascii->length);
427 } else
428 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200429 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200430
431 if (compact->utf8 == NULL)
432 assert(compact->utf8_length == 0);
433 if (ascii->wstr == NULL)
434 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200435 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200436 /* check that the best kind is used */
437 if (check_content && kind != PyUnicode_WCHAR_KIND)
438 {
439 Py_ssize_t i;
440 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200441 void *data;
442 Py_UCS4 ch;
443
444 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200445 for (i=0; i < ascii->length; i++)
446 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200447 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200448 if (ch > maxchar)
449 maxchar = ch;
450 }
451 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100452 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100454 assert(maxchar <= 255);
455 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200456 else
457 assert(maxchar < 128);
458 }
Victor Stinner77faf692011-11-20 18:56:05 +0100459 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200460 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100461 assert(maxchar <= 0xFFFF);
462 }
463 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200464 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100465 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100466 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200467 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200468 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400469 return 1;
470}
Victor Stinner910337b2011-10-03 03:20:16 +0200471#endif
472
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100473static PyObject*
474unicode_result_wchar(PyObject *unicode)
475{
476#ifndef Py_DEBUG
477 Py_ssize_t len;
478
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100479 len = _PyUnicode_WSTR_LENGTH(unicode);
480 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100481 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200482 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100483 }
484
485 if (len == 1) {
486 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100487 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100488 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
489 Py_DECREF(unicode);
490 return latin1_char;
491 }
492 }
493
494 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200495 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100496 return NULL;
497 }
498#else
Victor Stinneraa771272012-10-04 02:32:58 +0200499 assert(Py_REFCNT(unicode) == 1);
500
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100501 /* don't make the result ready in debug mode to ensure that the caller
502 makes the string ready before using it */
503 assert(_PyUnicode_CheckConsistency(unicode, 1));
504#endif
505 return unicode;
506}
507
508static PyObject*
509unicode_result_ready(PyObject *unicode)
510{
511 Py_ssize_t length;
512
513 length = PyUnicode_GET_LENGTH(unicode);
514 if (length == 0) {
515 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100516 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200517 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100518 }
519 return unicode_empty;
520 }
521
522 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200523 void *data = PyUnicode_DATA(unicode);
524 int kind = PyUnicode_KIND(unicode);
525 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100526 if (ch < 256) {
527 PyObject *latin1_char = unicode_latin1[ch];
528 if (latin1_char != NULL) {
529 if (unicode != latin1_char) {
530 Py_INCREF(latin1_char);
531 Py_DECREF(unicode);
532 }
533 return latin1_char;
534 }
535 else {
536 assert(_PyUnicode_CheckConsistency(unicode, 1));
537 Py_INCREF(unicode);
538 unicode_latin1[ch] = unicode;
539 return unicode;
540 }
541 }
542 }
543
544 assert(_PyUnicode_CheckConsistency(unicode, 1));
545 return unicode;
546}
547
548static PyObject*
549unicode_result(PyObject *unicode)
550{
551 assert(_PyUnicode_CHECK(unicode));
552 if (PyUnicode_IS_READY(unicode))
553 return unicode_result_ready(unicode);
554 else
555 return unicode_result_wchar(unicode);
556}
557
Victor Stinnerc4b49542011-12-11 22:44:26 +0100558static PyObject*
559unicode_result_unchanged(PyObject *unicode)
560{
561 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500562 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100563 return NULL;
564 Py_INCREF(unicode);
565 return unicode;
566 }
567 else
568 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100569 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100570}
571
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200572/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
573 ASCII, Latin1, UTF-8, etc. */
574static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200575backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200576 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
577{
Victor Stinnerad771582015-10-09 12:38:53 +0200578 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200579 Py_UCS4 ch;
580 enum PyUnicode_Kind kind;
581 void *data;
582
583 assert(PyUnicode_IS_READY(unicode));
584 kind = PyUnicode_KIND(unicode);
585 data = PyUnicode_DATA(unicode);
586
587 size = 0;
588 /* determine replacement size */
589 for (i = collstart; i < collend; ++i) {
590 Py_ssize_t incr;
591
592 ch = PyUnicode_READ(kind, data, i);
593 if (ch < 0x100)
594 incr = 2+2;
595 else if (ch < 0x10000)
596 incr = 2+4;
597 else {
598 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200599 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200600 }
601 if (size > PY_SSIZE_T_MAX - incr) {
602 PyErr_SetString(PyExc_OverflowError,
603 "encoded result is too long for a Python string");
604 return NULL;
605 }
606 size += incr;
607 }
608
Victor Stinnerad771582015-10-09 12:38:53 +0200609 str = _PyBytesWriter_Prepare(writer, str, size);
610 if (str == NULL)
611 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200612
613 /* generate replacement */
614 for (i = collstart; i < collend; ++i) {
615 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200616 *str++ = '\\';
617 if (ch >= 0x00010000) {
618 *str++ = 'U';
619 *str++ = Py_hexdigits[(ch>>28)&0xf];
620 *str++ = Py_hexdigits[(ch>>24)&0xf];
621 *str++ = Py_hexdigits[(ch>>20)&0xf];
622 *str++ = Py_hexdigits[(ch>>16)&0xf];
623 *str++ = Py_hexdigits[(ch>>12)&0xf];
624 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200625 }
Victor Stinner797485e2015-10-09 03:17:30 +0200626 else if (ch >= 0x100) {
627 *str++ = 'u';
628 *str++ = Py_hexdigits[(ch>>12)&0xf];
629 *str++ = Py_hexdigits[(ch>>8)&0xf];
630 }
631 else
632 *str++ = 'x';
633 *str++ = Py_hexdigits[(ch>>4)&0xf];
634 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200635 }
636 return str;
637}
638
639/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
640 ASCII, Latin1, UTF-8, etc. */
641static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200642xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200643 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
644{
Victor Stinnerad771582015-10-09 12:38:53 +0200645 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200646 Py_UCS4 ch;
647 enum PyUnicode_Kind kind;
648 void *data;
649
650 assert(PyUnicode_IS_READY(unicode));
651 kind = PyUnicode_KIND(unicode);
652 data = PyUnicode_DATA(unicode);
653
654 size = 0;
655 /* determine replacement size */
656 for (i = collstart; i < collend; ++i) {
657 Py_ssize_t incr;
658
659 ch = PyUnicode_READ(kind, data, i);
660 if (ch < 10)
661 incr = 2+1+1;
662 else if (ch < 100)
663 incr = 2+2+1;
664 else if (ch < 1000)
665 incr = 2+3+1;
666 else if (ch < 10000)
667 incr = 2+4+1;
668 else if (ch < 100000)
669 incr = 2+5+1;
670 else if (ch < 1000000)
671 incr = 2+6+1;
672 else {
673 assert(ch <= MAX_UNICODE);
674 incr = 2+7+1;
675 }
676 if (size > PY_SSIZE_T_MAX - incr) {
677 PyErr_SetString(PyExc_OverflowError,
678 "encoded result is too long for a Python string");
679 return NULL;
680 }
681 size += incr;
682 }
683
Victor Stinnerad771582015-10-09 12:38:53 +0200684 str = _PyBytesWriter_Prepare(writer, str, size);
685 if (str == NULL)
686 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200687
688 /* generate replacement */
689 for (i = collstart; i < collend; ++i) {
690 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
691 }
692 return str;
693}
694
Thomas Wouters477c8d52006-05-27 19:21:47 +0000695/* --- Bloom Filters ----------------------------------------------------- */
696
697/* stuff to implement simple "bloom filters" for Unicode characters.
698 to keep things simple, we use a single bitmask, using the least 5
699 bits from each unicode characters as the bit index. */
700
701/* the linebreak mask is set up by Unicode_Init below */
702
Antoine Pitrouf068f942010-01-13 14:19:12 +0000703#if LONG_BIT >= 128
704#define BLOOM_WIDTH 128
705#elif LONG_BIT >= 64
706#define BLOOM_WIDTH 64
707#elif LONG_BIT >= 32
708#define BLOOM_WIDTH 32
709#else
710#error "LONG_BIT is smaller than 32"
711#endif
712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713#define BLOOM_MASK unsigned long
714
Serhiy Storchaka05997252013-01-26 12:14:02 +0200715static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716
Antoine Pitrouf068f942010-01-13 14:19:12 +0000717#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718
Benjamin Peterson29060642009-01-31 22:14:21 +0000719#define BLOOM_LINEBREAK(ch) \
720 ((ch) < 128U ? ascii_linebreak[(ch)] : \
721 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000722
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700723static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200724make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000725{
Victor Stinnera85af502013-04-09 21:53:54 +0200726#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
727 do { \
728 TYPE *data = (TYPE *)PTR; \
729 TYPE *end = data + LEN; \
730 Py_UCS4 ch; \
731 for (; data != end; data++) { \
732 ch = *data; \
733 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
734 } \
735 break; \
736 } while (0)
737
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738 /* calculate simple bloom-style bitmask for a given unicode string */
739
Antoine Pitrouf068f942010-01-13 14:19:12 +0000740 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741
742 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200743 switch (kind) {
744 case PyUnicode_1BYTE_KIND:
745 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
746 break;
747 case PyUnicode_2BYTE_KIND:
748 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
749 break;
750 case PyUnicode_4BYTE_KIND:
751 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
752 break;
753 default:
754 assert(0);
755 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000756 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200757
758#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000759}
760
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300761static int
762ensure_unicode(PyObject *obj)
763{
764 if (!PyUnicode_Check(obj)) {
765 PyErr_Format(PyExc_TypeError,
766 "must be str, not %.100s",
767 Py_TYPE(obj)->tp_name);
768 return -1;
769 }
770 return PyUnicode_READY(obj);
771}
772
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200773/* Compilation of templated routines */
774
775#include "stringlib/asciilib.h"
776#include "stringlib/fastsearch.h"
777#include "stringlib/partition.h"
778#include "stringlib/split.h"
779#include "stringlib/count.h"
780#include "stringlib/find.h"
781#include "stringlib/find_max_char.h"
782#include "stringlib/localeutil.h"
783#include "stringlib/undef.h"
784
785#include "stringlib/ucs1lib.h"
786#include "stringlib/fastsearch.h"
787#include "stringlib/partition.h"
788#include "stringlib/split.h"
789#include "stringlib/count.h"
790#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300791#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200792#include "stringlib/find_max_char.h"
793#include "stringlib/localeutil.h"
794#include "stringlib/undef.h"
795
796#include "stringlib/ucs2lib.h"
797#include "stringlib/fastsearch.h"
798#include "stringlib/partition.h"
799#include "stringlib/split.h"
800#include "stringlib/count.h"
801#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300802#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200803#include "stringlib/find_max_char.h"
804#include "stringlib/localeutil.h"
805#include "stringlib/undef.h"
806
807#include "stringlib/ucs4lib.h"
808#include "stringlib/fastsearch.h"
809#include "stringlib/partition.h"
810#include "stringlib/split.h"
811#include "stringlib/count.h"
812#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300813#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200814#include "stringlib/find_max_char.h"
815#include "stringlib/localeutil.h"
816#include "stringlib/undef.h"
817
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200818#include "stringlib/unicodedefs.h"
819#include "stringlib/fastsearch.h"
820#include "stringlib/count.h"
821#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100822#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200823
Guido van Rossumd57fd912000-03-10 22:53:23 +0000824/* --- Unicode Object ----------------------------------------------------- */
825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200826static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200827fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200828
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700829static inline Py_ssize_t
830findchar(const void *s, int kind,
831 Py_ssize_t size, Py_UCS4 ch,
832 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200833{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200834 switch (kind) {
835 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200836 if ((Py_UCS1) ch != ch)
837 return -1;
838 if (direction > 0)
839 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
840 else
841 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200842 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200843 if ((Py_UCS2) ch != ch)
844 return -1;
845 if (direction > 0)
846 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
847 else
848 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200849 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200850 if (direction > 0)
851 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
852 else
853 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200854 default:
855 assert(0);
856 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200857 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200858}
859
Victor Stinnerafffce42012-10-03 23:03:17 +0200860#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000861/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200862 earlier.
863
864 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
865 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
866 invalid character in Unicode 6.0. */
867static void
868unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
869{
870 int kind = PyUnicode_KIND(unicode);
871 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
872 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
873 if (length <= old_length)
874 return;
875 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
876}
877#endif
878
Victor Stinnerfe226c02011-10-03 03:52:20 +0200879static PyObject*
880resize_compact(PyObject *unicode, Py_ssize_t length)
881{
882 Py_ssize_t char_size;
883 Py_ssize_t struct_size;
884 Py_ssize_t new_size;
885 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100886 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200887#ifdef Py_DEBUG
888 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
889#endif
890
Victor Stinner79891572012-05-03 13:43:07 +0200891 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200892 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100893 assert(PyUnicode_IS_COMPACT(unicode));
894
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200895 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100896 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200897 struct_size = sizeof(PyASCIIObject);
898 else
899 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200900 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200901
Victor Stinnerfe226c02011-10-03 03:52:20 +0200902 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
903 PyErr_NoMemory();
904 return NULL;
905 }
906 new_size = (struct_size + (length + 1) * char_size);
907
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200908 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
909 PyObject_DEL(_PyUnicode_UTF8(unicode));
910 _PyUnicode_UTF8(unicode) = NULL;
911 _PyUnicode_UTF8_LENGTH(unicode) = 0;
912 }
Victor Stinner84def372011-12-11 20:04:56 +0100913 _Py_DEC_REFTOTAL;
914 _Py_ForgetReference(unicode);
915
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300916 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100917 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100918 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200919 PyErr_NoMemory();
920 return NULL;
921 }
Victor Stinner84def372011-12-11 20:04:56 +0100922 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200923 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100924
Victor Stinnerfe226c02011-10-03 03:52:20 +0200925 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200926 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200927 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100928 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200929 _PyUnicode_WSTR_LENGTH(unicode) = length;
930 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100931 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
932 PyObject_DEL(_PyUnicode_WSTR(unicode));
933 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100934 if (!PyUnicode_IS_ASCII(unicode))
935 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100936 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200937#ifdef Py_DEBUG
938 unicode_fill_invalid(unicode, old_length);
939#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
941 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200942 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200943 return unicode;
944}
945
Alexander Belopolsky40018472011-02-26 01:02:56 +0000946static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200947resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000948{
Victor Stinner95663112011-10-04 01:03:50 +0200949 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100950 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200951 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200952 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000953
Victor Stinnerfe226c02011-10-03 03:52:20 +0200954 if (PyUnicode_IS_READY(unicode)) {
955 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200956 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200957 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200958#ifdef Py_DEBUG
959 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
960#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200961
962 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200963 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200964 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
965 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200966
967 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
968 PyErr_NoMemory();
969 return -1;
970 }
971 new_size = (length + 1) * char_size;
972
Victor Stinner7a9105a2011-12-12 00:13:42 +0100973 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
974 {
975 PyObject_DEL(_PyUnicode_UTF8(unicode));
976 _PyUnicode_UTF8(unicode) = NULL;
977 _PyUnicode_UTF8_LENGTH(unicode) = 0;
978 }
979
Victor Stinnerfe226c02011-10-03 03:52:20 +0200980 data = (PyObject *)PyObject_REALLOC(data, new_size);
981 if (data == NULL) {
982 PyErr_NoMemory();
983 return -1;
984 }
985 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200986 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200987 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200988 _PyUnicode_WSTR_LENGTH(unicode) = length;
989 }
990 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200991 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200992 _PyUnicode_UTF8_LENGTH(unicode) = length;
993 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200994 _PyUnicode_LENGTH(unicode) = length;
995 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200996#ifdef Py_DEBUG
997 unicode_fill_invalid(unicode, old_length);
998#endif
Victor Stinner95663112011-10-04 01:03:50 +0200999 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001000 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001001 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001002 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001003 }
Victor Stinner95663112011-10-04 01:03:50 +02001004 assert(_PyUnicode_WSTR(unicode) != NULL);
1005
1006 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001007 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001008 PyErr_NoMemory();
1009 return -1;
1010 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001011 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001012 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001013 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001014 if (!wstr) {
1015 PyErr_NoMemory();
1016 return -1;
1017 }
1018 _PyUnicode_WSTR(unicode) = wstr;
1019 _PyUnicode_WSTR(unicode)[length] = 0;
1020 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001021 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001022 return 0;
1023}
1024
Victor Stinnerfe226c02011-10-03 03:52:20 +02001025static PyObject*
1026resize_copy(PyObject *unicode, Py_ssize_t length)
1027{
1028 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001029 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001030 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001031
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001032 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001033
1034 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1035 if (copy == NULL)
1036 return NULL;
1037
1038 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001039 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001040 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001041 }
1042 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001043 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001044
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001045 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046 if (w == NULL)
1047 return NULL;
1048 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1049 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001050 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001051 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001052 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001053 }
1054}
1055
Guido van Rossumd57fd912000-03-10 22:53:23 +00001056/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001057 Ux0000 terminated; some code (e.g. new_identifier)
1058 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001059
1060 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001061 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001062
1063*/
1064
Alexander Belopolsky40018472011-02-26 01:02:56 +00001065static PyUnicodeObject *
1066_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001067{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001068 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001069 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001070
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001072 if (length == 0 && unicode_empty != NULL) {
1073 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001074 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001075 }
1076
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001077 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001078 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001079 return (PyUnicodeObject *)PyErr_NoMemory();
1080 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081 if (length < 0) {
1082 PyErr_SetString(PyExc_SystemError,
1083 "Negative size passed to _PyUnicode_New");
1084 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001085 }
1086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1088 if (unicode == NULL)
1089 return NULL;
1090 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001091
1092 _PyUnicode_WSTR_LENGTH(unicode) = length;
1093 _PyUnicode_HASH(unicode) = -1;
1094 _PyUnicode_STATE(unicode).interned = 0;
1095 _PyUnicode_STATE(unicode).kind = 0;
1096 _PyUnicode_STATE(unicode).compact = 0;
1097 _PyUnicode_STATE(unicode).ready = 0;
1098 _PyUnicode_STATE(unicode).ascii = 0;
1099 _PyUnicode_DATA_ANY(unicode) = NULL;
1100 _PyUnicode_LENGTH(unicode) = 0;
1101 _PyUnicode_UTF8(unicode) = NULL;
1102 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001104 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1105 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001106 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001107 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001108 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001109 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110
Jeremy Hyltond8082792003-09-16 19:41:39 +00001111 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001112 * the caller fails before initializing str -- unicode_resize()
1113 * reads str[0], and the Keep-Alive optimization can keep memory
1114 * allocated for str alive across a call to unicode_dealloc(unicode).
1115 * We don't want unicode_resize to read uninitialized memory in
1116 * that case.
1117 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001118 _PyUnicode_WSTR(unicode)[0] = 0;
1119 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001120
Victor Stinner7931d9a2011-11-04 00:22:48 +01001121 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001122 return unicode;
1123}
1124
Victor Stinnerf42dc442011-10-02 23:33:16 +02001125static const char*
1126unicode_kind_name(PyObject *unicode)
1127{
Victor Stinner42dfd712011-10-03 14:41:45 +02001128 /* don't check consistency: unicode_kind_name() is called from
1129 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001130 if (!PyUnicode_IS_COMPACT(unicode))
1131 {
1132 if (!PyUnicode_IS_READY(unicode))
1133 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001134 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001135 {
1136 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001137 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001138 return "legacy ascii";
1139 else
1140 return "legacy latin1";
1141 case PyUnicode_2BYTE_KIND:
1142 return "legacy UCS2";
1143 case PyUnicode_4BYTE_KIND:
1144 return "legacy UCS4";
1145 default:
1146 return "<legacy invalid kind>";
1147 }
1148 }
1149 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001150 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001152 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001153 return "ascii";
1154 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001155 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001156 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001157 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001158 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001159 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001160 default:
1161 return "<invalid compact kind>";
1162 }
1163}
1164
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001165#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166/* Functions wrapping macros for use in debugger */
1167char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001168 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001169}
1170
1171void *_PyUnicode_compact_data(void *unicode) {
1172 return _PyUnicode_COMPACT_DATA(unicode);
1173}
1174void *_PyUnicode_data(void *unicode){
1175 printf("obj %p\n", unicode);
1176 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1177 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1178 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1179 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1180 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1181 return PyUnicode_DATA(unicode);
1182}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001183
1184void
1185_PyUnicode_Dump(PyObject *op)
1186{
1187 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001188 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1189 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1190 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001191
Victor Stinnera849a4b2011-10-03 12:12:11 +02001192 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001193 {
1194 if (ascii->state.ascii)
1195 data = (ascii + 1);
1196 else
1197 data = (compact + 1);
1198 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001199 else
1200 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001201 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1202 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001203
Victor Stinnera849a4b2011-10-03 12:12:11 +02001204 if (ascii->wstr == data)
1205 printf("shared ");
1206 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001207
Victor Stinnera3b334d2011-10-03 13:53:37 +02001208 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001209 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001210 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1211 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001212 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1213 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001214 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001215 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001216}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001217#endif
1218
1219PyObject *
1220PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1221{
1222 PyObject *obj;
1223 PyCompactUnicodeObject *unicode;
1224 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001225 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001226 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001227 Py_ssize_t char_size;
1228 Py_ssize_t struct_size;
1229
1230 /* Optimization for empty strings */
1231 if (size == 0 && unicode_empty != NULL) {
1232 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001233 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001234 }
1235
Victor Stinner9e9d6892011-10-04 01:02:02 +02001236 is_ascii = 0;
1237 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001238 struct_size = sizeof(PyCompactUnicodeObject);
1239 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001240 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001241 char_size = 1;
1242 is_ascii = 1;
1243 struct_size = sizeof(PyASCIIObject);
1244 }
1245 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001246 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001247 char_size = 1;
1248 }
1249 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001250 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 char_size = 2;
1252 if (sizeof(wchar_t) == 2)
1253 is_sharing = 1;
1254 }
1255 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001256 if (maxchar > MAX_UNICODE) {
1257 PyErr_SetString(PyExc_SystemError,
1258 "invalid maximum character passed to PyUnicode_New");
1259 return NULL;
1260 }
Victor Stinner8f825062012-04-27 13:55:39 +02001261 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001262 char_size = 4;
1263 if (sizeof(wchar_t) == 4)
1264 is_sharing = 1;
1265 }
1266
1267 /* Ensure we won't overflow the size. */
1268 if (size < 0) {
1269 PyErr_SetString(PyExc_SystemError,
1270 "Negative size passed to PyUnicode_New");
1271 return NULL;
1272 }
1273 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1274 return PyErr_NoMemory();
1275
1276 /* Duplicated allocation code from _PyObject_New() instead of a call to
1277 * PyObject_New() so we are able to allocate space for the object and
1278 * it's data buffer.
1279 */
1280 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1281 if (obj == NULL)
1282 return PyErr_NoMemory();
1283 obj = PyObject_INIT(obj, &PyUnicode_Type);
1284 if (obj == NULL)
1285 return NULL;
1286
1287 unicode = (PyCompactUnicodeObject *)obj;
1288 if (is_ascii)
1289 data = ((PyASCIIObject*)obj) + 1;
1290 else
1291 data = unicode + 1;
1292 _PyUnicode_LENGTH(unicode) = size;
1293 _PyUnicode_HASH(unicode) = -1;
1294 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001295 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001296 _PyUnicode_STATE(unicode).compact = 1;
1297 _PyUnicode_STATE(unicode).ready = 1;
1298 _PyUnicode_STATE(unicode).ascii = is_ascii;
1299 if (is_ascii) {
1300 ((char*)data)[size] = 0;
1301 _PyUnicode_WSTR(unicode) = NULL;
1302 }
Victor Stinner8f825062012-04-27 13:55:39 +02001303 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 ((char*)data)[size] = 0;
1305 _PyUnicode_WSTR(unicode) = NULL;
1306 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001308 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310 else {
1311 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001312 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001313 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001315 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 ((Py_UCS4*)data)[size] = 0;
1317 if (is_sharing) {
1318 _PyUnicode_WSTR_LENGTH(unicode) = size;
1319 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1320 }
1321 else {
1322 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1323 _PyUnicode_WSTR(unicode) = NULL;
1324 }
1325 }
Victor Stinner8f825062012-04-27 13:55:39 +02001326#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001327 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001328#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001329 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330 return obj;
1331}
1332
1333#if SIZEOF_WCHAR_T == 2
1334/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1335 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001336 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337
1338 This function assumes that unicode can hold one more code point than wstr
1339 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001340static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001341unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001342 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343{
1344 const wchar_t *iter;
1345 Py_UCS4 *ucs4_out;
1346
Victor Stinner910337b2011-10-03 03:20:16 +02001347 assert(unicode != NULL);
1348 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1350 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1351
1352 for (iter = begin; iter < end; ) {
1353 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1354 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001355 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1356 && (iter+1) < end
1357 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001358 {
Victor Stinner551ac952011-11-29 22:58:13 +01001359 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001360 iter += 2;
1361 }
1362 else {
1363 *ucs4_out++ = *iter;
1364 iter++;
1365 }
1366 }
1367 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1368 _PyUnicode_GET_LENGTH(unicode)));
1369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001370}
1371#endif
1372
Victor Stinnercd9950f2011-10-02 00:34:53 +02001373static int
Victor Stinner488fa492011-12-12 00:01:39 +01001374unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001375{
Victor Stinner488fa492011-12-12 00:01:39 +01001376 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001377 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001378 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001379 return -1;
1380 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001381 return 0;
1382}
1383
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001384static int
1385_copy_characters(PyObject *to, Py_ssize_t to_start,
1386 PyObject *from, Py_ssize_t from_start,
1387 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001388{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001389 unsigned int from_kind, to_kind;
1390 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001391
Victor Stinneree4544c2012-05-09 22:24:08 +02001392 assert(0 <= how_many);
1393 assert(0 <= from_start);
1394 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001395 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001396 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001397 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001398
Victor Stinnerd3f08822012-05-29 12:57:52 +02001399 assert(PyUnicode_Check(to));
1400 assert(PyUnicode_IS_READY(to));
1401 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1402
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001403 if (how_many == 0)
1404 return 0;
1405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001407 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001409 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410
Victor Stinnerf1852262012-06-16 16:38:26 +02001411#ifdef Py_DEBUG
1412 if (!check_maxchar
1413 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1414 {
1415 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1416 Py_UCS4 ch;
1417 Py_ssize_t i;
1418 for (i=0; i < how_many; i++) {
1419 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1420 assert(ch <= to_maxchar);
1421 }
1422 }
1423#endif
1424
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001425 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001426 if (check_maxchar
1427 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1428 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001429 /* Writing Latin-1 characters into an ASCII string requires to
1430 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001431 Py_UCS4 max_char;
1432 max_char = ucs1lib_find_max_char(from_data,
1433 (Py_UCS1*)from_data + how_many);
1434 if (max_char >= 128)
1435 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001436 }
Christian Heimesf051e432016-09-13 20:22:02 +02001437 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001438 (char*)from_data + from_kind * from_start,
1439 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001441 else if (from_kind == PyUnicode_1BYTE_KIND
1442 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001443 {
1444 _PyUnicode_CONVERT_BYTES(
1445 Py_UCS1, Py_UCS2,
1446 PyUnicode_1BYTE_DATA(from) + from_start,
1447 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1448 PyUnicode_2BYTE_DATA(to) + to_start
1449 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001450 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001451 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001452 && to_kind == PyUnicode_4BYTE_KIND)
1453 {
1454 _PyUnicode_CONVERT_BYTES(
1455 Py_UCS1, Py_UCS4,
1456 PyUnicode_1BYTE_DATA(from) + from_start,
1457 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1458 PyUnicode_4BYTE_DATA(to) + to_start
1459 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001460 }
1461 else if (from_kind == PyUnicode_2BYTE_KIND
1462 && to_kind == PyUnicode_4BYTE_KIND)
1463 {
1464 _PyUnicode_CONVERT_BYTES(
1465 Py_UCS2, Py_UCS4,
1466 PyUnicode_2BYTE_DATA(from) + from_start,
1467 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1468 PyUnicode_4BYTE_DATA(to) + to_start
1469 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001470 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001471 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001472 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1473
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001474 if (!check_maxchar) {
1475 if (from_kind == PyUnicode_2BYTE_KIND
1476 && to_kind == PyUnicode_1BYTE_KIND)
1477 {
1478 _PyUnicode_CONVERT_BYTES(
1479 Py_UCS2, Py_UCS1,
1480 PyUnicode_2BYTE_DATA(from) + from_start,
1481 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1482 PyUnicode_1BYTE_DATA(to) + to_start
1483 );
1484 }
1485 else if (from_kind == PyUnicode_4BYTE_KIND
1486 && to_kind == PyUnicode_1BYTE_KIND)
1487 {
1488 _PyUnicode_CONVERT_BYTES(
1489 Py_UCS4, Py_UCS1,
1490 PyUnicode_4BYTE_DATA(from) + from_start,
1491 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1492 PyUnicode_1BYTE_DATA(to) + to_start
1493 );
1494 }
1495 else if (from_kind == PyUnicode_4BYTE_KIND
1496 && to_kind == PyUnicode_2BYTE_KIND)
1497 {
1498 _PyUnicode_CONVERT_BYTES(
1499 Py_UCS4, Py_UCS2,
1500 PyUnicode_4BYTE_DATA(from) + from_start,
1501 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1502 PyUnicode_2BYTE_DATA(to) + to_start
1503 );
1504 }
1505 else {
1506 assert(0);
1507 return -1;
1508 }
1509 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001510 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001511 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001512 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001513 Py_ssize_t i;
1514
Victor Stinnera0702ab2011-09-29 14:14:38 +02001515 for (i=0; i < how_many; i++) {
1516 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001517 if (ch > to_maxchar)
1518 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001519 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1520 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001521 }
1522 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001523 return 0;
1524}
1525
Victor Stinnerd3f08822012-05-29 12:57:52 +02001526void
1527_PyUnicode_FastCopyCharacters(
1528 PyObject *to, Py_ssize_t to_start,
1529 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001530{
1531 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1532}
1533
1534Py_ssize_t
1535PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1536 PyObject *from, Py_ssize_t from_start,
1537 Py_ssize_t how_many)
1538{
1539 int err;
1540
1541 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1542 PyErr_BadInternalCall();
1543 return -1;
1544 }
1545
Benjamin Petersonbac79492012-01-14 13:34:47 -05001546 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001547 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001548 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001549 return -1;
1550
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001551 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001552 PyErr_SetString(PyExc_IndexError, "string index out of range");
1553 return -1;
1554 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001555 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001556 PyErr_SetString(PyExc_IndexError, "string index out of range");
1557 return -1;
1558 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001559 if (how_many < 0) {
1560 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1561 return -1;
1562 }
1563 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001564 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1565 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001566 "Cannot write %zi characters at %zi "
1567 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001568 how_many, to_start, PyUnicode_GET_LENGTH(to));
1569 return -1;
1570 }
1571
1572 if (how_many == 0)
1573 return 0;
1574
Victor Stinner488fa492011-12-12 00:01:39 +01001575 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001576 return -1;
1577
1578 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1579 if (err) {
1580 PyErr_Format(PyExc_SystemError,
1581 "Cannot copy %s characters "
1582 "into a string of %s characters",
1583 unicode_kind_name(from),
1584 unicode_kind_name(to));
1585 return -1;
1586 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001587 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588}
1589
Victor Stinner17222162011-09-28 22:15:37 +02001590/* Find the maximum code point and count the number of surrogate pairs so a
1591 correct string length can be computed before converting a string to UCS4.
1592 This function counts single surrogates as a character and not as a pair.
1593
1594 Return 0 on success, or -1 on error. */
1595static int
1596find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1597 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598{
1599 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001600 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001601
Victor Stinnerc53be962011-10-02 21:33:54 +02001602 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001603 *num_surrogates = 0;
1604 *maxchar = 0;
1605
1606 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001607#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001608 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1609 && (iter+1) < end
1610 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1611 {
1612 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1613 ++(*num_surrogates);
1614 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 }
1616 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001618 {
1619 ch = *iter;
1620 iter++;
1621 }
1622 if (ch > *maxchar) {
1623 *maxchar = ch;
1624 if (*maxchar > MAX_UNICODE) {
1625 PyErr_Format(PyExc_ValueError,
1626 "character U+%x is not in range [U+0000; U+10ffff]",
1627 ch);
1628 return -1;
1629 }
1630 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001631 }
1632 return 0;
1633}
1634
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001635int
1636_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001637{
1638 wchar_t *end;
1639 Py_UCS4 maxchar = 0;
1640 Py_ssize_t num_surrogates;
1641#if SIZEOF_WCHAR_T == 2
1642 Py_ssize_t length_wo_surrogates;
1643#endif
1644
Georg Brandl7597add2011-10-05 16:36:47 +02001645 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001646 strings were created using _PyObject_New() and where no canonical
1647 representation (the str field) has been set yet aka strings
1648 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001649 assert(_PyUnicode_CHECK(unicode));
1650 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001651 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001652 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001653 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001654 /* Actually, it should neither be interned nor be anything else: */
1655 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001656
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001658 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001659 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001660 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661
1662 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001663 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1664 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001665 PyErr_NoMemory();
1666 return -1;
1667 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001668 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 _PyUnicode_WSTR(unicode), end,
1670 PyUnicode_1BYTE_DATA(unicode));
1671 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1672 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1673 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1674 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001675 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001676 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001677 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001678 }
1679 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001680 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001681 _PyUnicode_UTF8(unicode) = NULL;
1682 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001683 }
1684 PyObject_FREE(_PyUnicode_WSTR(unicode));
1685 _PyUnicode_WSTR(unicode) = NULL;
1686 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1687 }
1688 /* In this case we might have to convert down from 4-byte native
1689 wchar_t to 2-byte unicode. */
1690 else if (maxchar < 65536) {
1691 assert(num_surrogates == 0 &&
1692 "FindMaxCharAndNumSurrogatePairs() messed up");
1693
Victor Stinner506f5922011-09-28 22:34:18 +02001694#if SIZEOF_WCHAR_T == 2
1695 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001696 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001697 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1698 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1699 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001700 _PyUnicode_UTF8(unicode) = NULL;
1701 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001702#else
1703 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001704 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001705 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001706 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001707 PyErr_NoMemory();
1708 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001709 }
Victor Stinner506f5922011-09-28 22:34:18 +02001710 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1711 _PyUnicode_WSTR(unicode), end,
1712 PyUnicode_2BYTE_DATA(unicode));
1713 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1714 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1715 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001716 _PyUnicode_UTF8(unicode) = NULL;
1717 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001718 PyObject_FREE(_PyUnicode_WSTR(unicode));
1719 _PyUnicode_WSTR(unicode) = NULL;
1720 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1721#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001722 }
1723 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1724 else {
1725#if SIZEOF_WCHAR_T == 2
1726 /* in case the native representation is 2-bytes, we need to allocate a
1727 new normalized 4-byte version. */
1728 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001729 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1730 PyErr_NoMemory();
1731 return -1;
1732 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001733 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1734 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001735 PyErr_NoMemory();
1736 return -1;
1737 }
1738 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1739 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001740 _PyUnicode_UTF8(unicode) = NULL;
1741 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001742 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1743 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001744 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001745 PyObject_FREE(_PyUnicode_WSTR(unicode));
1746 _PyUnicode_WSTR(unicode) = NULL;
1747 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1748#else
1749 assert(num_surrogates == 0);
1750
Victor Stinnerc3c74152011-10-02 20:39:55 +02001751 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001753 _PyUnicode_UTF8(unicode) = NULL;
1754 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001755 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1756#endif
1757 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1758 }
1759 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001760 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001761 return 0;
1762}
1763
Alexander Belopolsky40018472011-02-26 01:02:56 +00001764static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001765unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001766{
Walter Dörwald16807132007-05-25 13:52:07 +00001767 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001768 case SSTATE_NOT_INTERNED:
1769 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001770
Benjamin Peterson29060642009-01-31 22:14:21 +00001771 case SSTATE_INTERNED_MORTAL:
1772 /* revive dead object temporarily for DelItem */
1773 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001774 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001775 Py_FatalError(
1776 "deletion of interned string failed");
1777 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001778
Benjamin Peterson29060642009-01-31 22:14:21 +00001779 case SSTATE_INTERNED_IMMORTAL:
1780 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001781
Benjamin Peterson29060642009-01-31 22:14:21 +00001782 default:
1783 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001784 }
1785
Victor Stinner03490912011-10-03 23:45:12 +02001786 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001788 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001789 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001790 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1791 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001792
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001793 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001794}
1795
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001796#ifdef Py_DEBUG
1797static int
1798unicode_is_singleton(PyObject *unicode)
1799{
1800 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1801 if (unicode == unicode_empty)
1802 return 1;
1803 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1804 {
1805 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1806 if (ch < 256 && unicode_latin1[ch] == unicode)
1807 return 1;
1808 }
1809 return 0;
1810}
1811#endif
1812
Alexander Belopolsky40018472011-02-26 01:02:56 +00001813static int
Victor Stinner488fa492011-12-12 00:01:39 +01001814unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001815{
Victor Stinner488fa492011-12-12 00:01:39 +01001816 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001817 if (Py_REFCNT(unicode) != 1)
1818 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001819 if (_PyUnicode_HASH(unicode) != -1)
1820 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001821 if (PyUnicode_CHECK_INTERNED(unicode))
1822 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001823 if (!PyUnicode_CheckExact(unicode))
1824 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001825#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001826 /* singleton refcount is greater than 1 */
1827 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001828#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001829 return 1;
1830}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001831
Victor Stinnerfe226c02011-10-03 03:52:20 +02001832static int
1833unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1834{
1835 PyObject *unicode;
1836 Py_ssize_t old_length;
1837
1838 assert(p_unicode != NULL);
1839 unicode = *p_unicode;
1840
1841 assert(unicode != NULL);
1842 assert(PyUnicode_Check(unicode));
1843 assert(0 <= length);
1844
Victor Stinner910337b2011-10-03 03:20:16 +02001845 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001846 old_length = PyUnicode_WSTR_LENGTH(unicode);
1847 else
1848 old_length = PyUnicode_GET_LENGTH(unicode);
1849 if (old_length == length)
1850 return 0;
1851
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001852 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001853 _Py_INCREF_UNICODE_EMPTY();
1854 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001855 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001856 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001857 return 0;
1858 }
1859
Victor Stinner488fa492011-12-12 00:01:39 +01001860 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001861 PyObject *copy = resize_copy(unicode, length);
1862 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001863 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001864 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001865 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001866 }
1867
Victor Stinnerfe226c02011-10-03 03:52:20 +02001868 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001869 PyObject *new_unicode = resize_compact(unicode, length);
1870 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001871 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001872 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001873 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001874 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001875 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001876}
1877
Alexander Belopolsky40018472011-02-26 01:02:56 +00001878int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001879PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001880{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001881 PyObject *unicode;
1882 if (p_unicode == NULL) {
1883 PyErr_BadInternalCall();
1884 return -1;
1885 }
1886 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001887 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001888 {
1889 PyErr_BadInternalCall();
1890 return -1;
1891 }
1892 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001893}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001894
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001895/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001896
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001897 WARNING: The function doesn't copy the terminating null character and
1898 doesn't check the maximum character (may write a latin1 character in an
1899 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001900static void
1901unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1902 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001903{
1904 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1905 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001906 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001907
1908 switch (kind) {
1909 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001910 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001911#ifdef Py_DEBUG
1912 if (PyUnicode_IS_ASCII(unicode)) {
1913 Py_UCS4 maxchar = ucs1lib_find_max_char(
1914 (const Py_UCS1*)str,
1915 (const Py_UCS1*)str + len);
1916 assert(maxchar < 128);
1917 }
1918#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001919 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001920 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001921 }
1922 case PyUnicode_2BYTE_KIND: {
1923 Py_UCS2 *start = (Py_UCS2 *)data + index;
1924 Py_UCS2 *ucs2 = start;
1925 assert(index <= PyUnicode_GET_LENGTH(unicode));
1926
Victor Stinner184252a2012-06-16 02:57:41 +02001927 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001928 *ucs2 = (Py_UCS2)*str;
1929
1930 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001931 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001932 }
1933 default: {
1934 Py_UCS4 *start = (Py_UCS4 *)data + index;
1935 Py_UCS4 *ucs4 = start;
1936 assert(kind == PyUnicode_4BYTE_KIND);
1937 assert(index <= PyUnicode_GET_LENGTH(unicode));
1938
Victor Stinner184252a2012-06-16 02:57:41 +02001939 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001940 *ucs4 = (Py_UCS4)*str;
1941
1942 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001943 }
1944 }
1945}
1946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001947static PyObject*
1948get_latin1_char(unsigned char ch)
1949{
Victor Stinnera464fc12011-10-02 20:39:30 +02001950 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001951 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001952 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 if (!unicode)
1954 return NULL;
1955 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001956 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001957 unicode_latin1[ch] = unicode;
1958 }
1959 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001960 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001961}
1962
Victor Stinner985a82a2014-01-03 12:53:47 +01001963static PyObject*
1964unicode_char(Py_UCS4 ch)
1965{
1966 PyObject *unicode;
1967
1968 assert(ch <= MAX_UNICODE);
1969
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001970 if (ch < 256)
1971 return get_latin1_char(ch);
1972
Victor Stinner985a82a2014-01-03 12:53:47 +01001973 unicode = PyUnicode_New(1, ch);
1974 if (unicode == NULL)
1975 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001976
1977 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1978 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01001979 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001980 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01001981 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1982 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1983 }
1984 assert(_PyUnicode_CheckConsistency(unicode, 1));
1985 return unicode;
1986}
1987
Alexander Belopolsky40018472011-02-26 01:02:56 +00001988PyObject *
1989PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001990{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001991 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992 Py_UCS4 maxchar = 0;
1993 Py_ssize_t num_surrogates;
1994
1995 if (u == NULL)
1996 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001997
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001998 /* If the Unicode data is known at construction time, we can apply
1999 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002001 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002002 if (size == 0)
2003 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002005 /* Single character Unicode objects in the Latin-1 range are
2006 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002007 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 return get_latin1_char((unsigned char)*u);
2009
2010 /* If not empty and not single character, copy the Unicode data
2011 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002012 if (find_maxchar_surrogates(u, u + size,
2013 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014 return NULL;
2015
Victor Stinner8faf8212011-12-08 22:14:11 +01002016 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002017 if (!unicode)
2018 return NULL;
2019
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002020 switch (PyUnicode_KIND(unicode)) {
2021 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002022 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002023 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2024 break;
2025 case PyUnicode_2BYTE_KIND:
2026#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002027 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002028#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002029 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002030 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2031#endif
2032 break;
2033 case PyUnicode_4BYTE_KIND:
2034#if SIZEOF_WCHAR_T == 2
2035 /* This is the only case which has to process surrogates, thus
2036 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002037 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002038#else
2039 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002040 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041#endif
2042 break;
2043 default:
2044 assert(0 && "Impossible state");
2045 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002046
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002047 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002048}
2049
Alexander Belopolsky40018472011-02-26 01:02:56 +00002050PyObject *
2051PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002052{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002053 if (size < 0) {
2054 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002055 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002056 return NULL;
2057 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002058 if (u != NULL)
2059 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2060 else
2061 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002062}
2063
Alexander Belopolsky40018472011-02-26 01:02:56 +00002064PyObject *
2065PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002066{
2067 size_t size = strlen(u);
2068 if (size > PY_SSIZE_T_MAX) {
2069 PyErr_SetString(PyExc_OverflowError, "input too long");
2070 return NULL;
2071 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002072 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002073}
2074
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002075PyObject *
2076_PyUnicode_FromId(_Py_Identifier *id)
2077{
2078 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002079 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2080 strlen(id->string),
2081 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002082 if (!id->object)
2083 return NULL;
2084 PyUnicode_InternInPlace(&id->object);
2085 assert(!id->next);
2086 id->next = static_strings;
2087 static_strings = id;
2088 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002089 return id->object;
2090}
2091
2092void
2093_PyUnicode_ClearStaticStrings()
2094{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002095 _Py_Identifier *tmp, *s = static_strings;
2096 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002097 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002098 tmp = s->next;
2099 s->next = NULL;
2100 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002101 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002102 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002103}
2104
Benjamin Peterson0df54292012-03-26 14:50:32 -04002105/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002106
Victor Stinnerd3f08822012-05-29 12:57:52 +02002107PyObject*
2108_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002109{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002110 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002111 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002112 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002113#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002114 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002115#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002116 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002117 }
Victor Stinner785938e2011-12-11 20:09:03 +01002118 unicode = PyUnicode_New(size, 127);
2119 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002120 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002121 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2122 assert(_PyUnicode_CheckConsistency(unicode, 1));
2123 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002124}
2125
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002126static Py_UCS4
2127kind_maxchar_limit(unsigned int kind)
2128{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002129 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002130 case PyUnicode_1BYTE_KIND:
2131 return 0x80;
2132 case PyUnicode_2BYTE_KIND:
2133 return 0x100;
2134 case PyUnicode_4BYTE_KIND:
2135 return 0x10000;
2136 default:
2137 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002138 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002139 }
2140}
2141
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -07002142static inline Py_UCS4
Victor Stinnere6abb482012-05-02 01:15:40 +02002143align_maxchar(Py_UCS4 maxchar)
2144{
2145 if (maxchar <= 127)
2146 return 127;
2147 else if (maxchar <= 255)
2148 return 255;
2149 else if (maxchar <= 65535)
2150 return 65535;
2151 else
2152 return MAX_UNICODE;
2153}
2154
Victor Stinner702c7342011-10-05 13:50:52 +02002155static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002156_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002157{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002158 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002159 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002160
Serhiy Storchaka678db842013-01-26 12:16:36 +02002161 if (size == 0)
2162 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002163 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002164 if (size == 1)
2165 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002166
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002167 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002168 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002169 if (!res)
2170 return NULL;
2171 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002172 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002174}
2175
Victor Stinnere57b1c02011-09-28 22:20:48 +02002176static PyObject*
2177_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002178{
2179 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002180 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002181
Serhiy Storchaka678db842013-01-26 12:16:36 +02002182 if (size == 0)
2183 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002184 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002185 if (size == 1)
2186 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002187
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002188 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002189 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002190 if (!res)
2191 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002192 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002193 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002194 else {
2195 _PyUnicode_CONVERT_BYTES(
2196 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2197 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002198 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002199 return res;
2200}
2201
Victor Stinnere57b1c02011-09-28 22:20:48 +02002202static PyObject*
2203_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002204{
2205 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002206 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002207
Serhiy Storchaka678db842013-01-26 12:16:36 +02002208 if (size == 0)
2209 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002210 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002211 if (size == 1)
2212 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002213
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002214 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002215 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 if (!res)
2217 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002218 if (max_char < 256)
2219 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2220 PyUnicode_1BYTE_DATA(res));
2221 else if (max_char < 0x10000)
2222 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2223 PyUnicode_2BYTE_DATA(res));
2224 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002225 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002226 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002227 return res;
2228}
2229
2230PyObject*
2231PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2232{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002233 if (size < 0) {
2234 PyErr_SetString(PyExc_ValueError, "size must be positive");
2235 return NULL;
2236 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002237 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002238 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002239 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002241 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002242 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002243 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002244 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002245 PyErr_SetString(PyExc_SystemError, "invalid kind");
2246 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002248}
2249
Victor Stinnerece58de2012-04-23 23:36:38 +02002250Py_UCS4
2251_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2252{
2253 enum PyUnicode_Kind kind;
2254 void *startptr, *endptr;
2255
2256 assert(PyUnicode_IS_READY(unicode));
2257 assert(0 <= start);
2258 assert(end <= PyUnicode_GET_LENGTH(unicode));
2259 assert(start <= end);
2260
2261 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2262 return PyUnicode_MAX_CHAR_VALUE(unicode);
2263
2264 if (start == end)
2265 return 127;
2266
Victor Stinner94d558b2012-04-27 22:26:58 +02002267 if (PyUnicode_IS_ASCII(unicode))
2268 return 127;
2269
Victor Stinnerece58de2012-04-23 23:36:38 +02002270 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002271 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002272 endptr = (char *)startptr + end * kind;
2273 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002274 switch(kind) {
2275 case PyUnicode_1BYTE_KIND:
2276 return ucs1lib_find_max_char(startptr, endptr);
2277 case PyUnicode_2BYTE_KIND:
2278 return ucs2lib_find_max_char(startptr, endptr);
2279 case PyUnicode_4BYTE_KIND:
2280 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002281 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002282 assert(0);
2283 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002284 }
2285}
2286
Victor Stinner25a4b292011-10-06 12:31:55 +02002287/* Ensure that a string uses the most efficient storage, if it is not the
2288 case: create a new string with of the right kind. Write NULL into *p_unicode
2289 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002290static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002291unicode_adjust_maxchar(PyObject **p_unicode)
2292{
2293 PyObject *unicode, *copy;
2294 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002295 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002296 unsigned int kind;
2297
2298 assert(p_unicode != NULL);
2299 unicode = *p_unicode;
2300 assert(PyUnicode_IS_READY(unicode));
2301 if (PyUnicode_IS_ASCII(unicode))
2302 return;
2303
2304 len = PyUnicode_GET_LENGTH(unicode);
2305 kind = PyUnicode_KIND(unicode);
2306 if (kind == PyUnicode_1BYTE_KIND) {
2307 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002308 max_char = ucs1lib_find_max_char(u, u + len);
2309 if (max_char >= 128)
2310 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002311 }
2312 else if (kind == PyUnicode_2BYTE_KIND) {
2313 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002314 max_char = ucs2lib_find_max_char(u, u + len);
2315 if (max_char >= 256)
2316 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002317 }
2318 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002319 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002320 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002321 max_char = ucs4lib_find_max_char(u, u + len);
2322 if (max_char >= 0x10000)
2323 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002324 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002325 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002326 if (copy != NULL)
2327 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002328 Py_DECREF(unicode);
2329 *p_unicode = copy;
2330}
2331
Victor Stinner034f6cf2011-09-30 02:26:44 +02002332PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002333_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002334{
Victor Stinner87af4f22011-11-21 23:03:47 +01002335 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002336 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002337
Victor Stinner034f6cf2011-09-30 02:26:44 +02002338 if (!PyUnicode_Check(unicode)) {
2339 PyErr_BadInternalCall();
2340 return NULL;
2341 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002342 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002343 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002344
Victor Stinner87af4f22011-11-21 23:03:47 +01002345 length = PyUnicode_GET_LENGTH(unicode);
2346 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002347 if (!copy)
2348 return NULL;
2349 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2350
Christian Heimesf051e432016-09-13 20:22:02 +02002351 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002352 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002353 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002354 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002355}
2356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002357
Victor Stinnerbc603d12011-10-02 01:00:40 +02002358/* Widen Unicode objects to larger buffers. Don't write terminating null
2359 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002360
2361void*
2362_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2363{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002364 Py_ssize_t len;
2365 void *result;
2366 unsigned int skind;
2367
Benjamin Petersonbac79492012-01-14 13:34:47 -05002368 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002369 return NULL;
2370
2371 len = PyUnicode_GET_LENGTH(s);
2372 skind = PyUnicode_KIND(s);
2373 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002374 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375 return NULL;
2376 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002377 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002378 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002379 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002380 if (!result)
2381 return PyErr_NoMemory();
2382 assert(skind == PyUnicode_1BYTE_KIND);
2383 _PyUnicode_CONVERT_BYTES(
2384 Py_UCS1, Py_UCS2,
2385 PyUnicode_1BYTE_DATA(s),
2386 PyUnicode_1BYTE_DATA(s) + len,
2387 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002388 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002389 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002390 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002391 if (!result)
2392 return PyErr_NoMemory();
2393 if (skind == PyUnicode_2BYTE_KIND) {
2394 _PyUnicode_CONVERT_BYTES(
2395 Py_UCS2, Py_UCS4,
2396 PyUnicode_2BYTE_DATA(s),
2397 PyUnicode_2BYTE_DATA(s) + len,
2398 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002400 else {
2401 assert(skind == PyUnicode_1BYTE_KIND);
2402 _PyUnicode_CONVERT_BYTES(
2403 Py_UCS1, Py_UCS4,
2404 PyUnicode_1BYTE_DATA(s),
2405 PyUnicode_1BYTE_DATA(s) + len,
2406 result);
2407 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002408 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002409 default:
2410 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002411 }
Victor Stinner01698042011-10-04 00:04:26 +02002412 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 return NULL;
2414}
2415
2416static Py_UCS4*
2417as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2418 int copy_null)
2419{
2420 int kind;
2421 void *data;
2422 Py_ssize_t len, targetlen;
2423 if (PyUnicode_READY(string) == -1)
2424 return NULL;
2425 kind = PyUnicode_KIND(string);
2426 data = PyUnicode_DATA(string);
2427 len = PyUnicode_GET_LENGTH(string);
2428 targetlen = len;
2429 if (copy_null)
2430 targetlen++;
2431 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002432 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 if (!target) {
2434 PyErr_NoMemory();
2435 return NULL;
2436 }
2437 }
2438 else {
2439 if (targetsize < targetlen) {
2440 PyErr_Format(PyExc_SystemError,
2441 "string is longer than the buffer");
2442 if (copy_null && 0 < targetsize)
2443 target[0] = 0;
2444 return NULL;
2445 }
2446 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002447 if (kind == PyUnicode_1BYTE_KIND) {
2448 Py_UCS1 *start = (Py_UCS1 *) data;
2449 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002450 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002451 else if (kind == PyUnicode_2BYTE_KIND) {
2452 Py_UCS2 *start = (Py_UCS2 *) data;
2453 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2454 }
2455 else {
2456 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002457 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002458 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 if (copy_null)
2460 target[len] = 0;
2461 return target;
2462}
2463
2464Py_UCS4*
2465PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2466 int copy_null)
2467{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002468 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002469 PyErr_BadInternalCall();
2470 return NULL;
2471 }
2472 return as_ucs4(string, target, targetsize, copy_null);
2473}
2474
2475Py_UCS4*
2476PyUnicode_AsUCS4Copy(PyObject *string)
2477{
2478 return as_ucs4(string, NULL, 0, 1);
2479}
2480
2481#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002482
Alexander Belopolsky40018472011-02-26 01:02:56 +00002483PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002484PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002485{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002486 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002487 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002488 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002489 PyErr_BadInternalCall();
2490 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002491 }
2492
Martin v. Löwis790465f2008-04-05 20:41:37 +00002493 if (size == -1) {
2494 size = wcslen(w);
2495 }
2496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002497 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002498}
2499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002501
Victor Stinner15a11362012-10-06 23:48:20 +02002502/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002503 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2504 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2505#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002506
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002507static int
2508unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2509 Py_ssize_t width, Py_ssize_t precision)
2510{
2511 Py_ssize_t length, fill, arglen;
2512 Py_UCS4 maxchar;
2513
2514 if (PyUnicode_READY(str) == -1)
2515 return -1;
2516
2517 length = PyUnicode_GET_LENGTH(str);
2518 if ((precision == -1 || precision >= length)
2519 && width <= length)
2520 return _PyUnicodeWriter_WriteStr(writer, str);
2521
2522 if (precision != -1)
2523 length = Py_MIN(precision, length);
2524
2525 arglen = Py_MAX(length, width);
2526 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2527 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2528 else
2529 maxchar = writer->maxchar;
2530
2531 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2532 return -1;
2533
2534 if (width > length) {
2535 fill = width - length;
2536 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2537 return -1;
2538 writer->pos += fill;
2539 }
2540
2541 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2542 str, 0, length);
2543 writer->pos += length;
2544 return 0;
2545}
2546
2547static int
2548unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2549 Py_ssize_t width, Py_ssize_t precision)
2550{
2551 /* UTF-8 */
2552 Py_ssize_t length;
2553 PyObject *unicode;
2554 int res;
2555
2556 length = strlen(str);
2557 if (precision != -1)
2558 length = Py_MIN(length, precision);
2559 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2560 if (unicode == NULL)
2561 return -1;
2562
2563 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2564 Py_DECREF(unicode);
2565 return res;
2566}
2567
Victor Stinner96865452011-03-01 23:44:09 +00002568static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002569unicode_fromformat_arg(_PyUnicodeWriter *writer,
2570 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002571{
Victor Stinnere215d962012-10-06 23:03:36 +02002572 const char *p;
2573 Py_ssize_t len;
2574 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002575 Py_ssize_t width;
2576 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002577 int longflag;
2578 int longlongflag;
2579 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002580 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002581
2582 p = f;
2583 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002584 zeropad = 0;
2585 if (*f == '0') {
2586 zeropad = 1;
2587 f++;
2588 }
Victor Stinner96865452011-03-01 23:44:09 +00002589
2590 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002591 width = -1;
2592 if (Py_ISDIGIT((unsigned)*f)) {
2593 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002594 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002595 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002596 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002597 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002598 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002599 return NULL;
2600 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002601 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002602 f++;
2603 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002604 }
2605 precision = -1;
2606 if (*f == '.') {
2607 f++;
2608 if (Py_ISDIGIT((unsigned)*f)) {
2609 precision = (*f - '0');
2610 f++;
2611 while (Py_ISDIGIT((unsigned)*f)) {
2612 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2613 PyErr_SetString(PyExc_ValueError,
2614 "precision too big");
2615 return NULL;
2616 }
2617 precision = (precision * 10) + (*f - '0');
2618 f++;
2619 }
2620 }
Victor Stinner96865452011-03-01 23:44:09 +00002621 if (*f == '%') {
2622 /* "%.3%s" => f points to "3" */
2623 f--;
2624 }
2625 }
2626 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002627 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002628 f--;
2629 }
Victor Stinner96865452011-03-01 23:44:09 +00002630
2631 /* Handle %ld, %lu, %lld and %llu. */
2632 longflag = 0;
2633 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002634 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002635 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002636 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002637 longflag = 1;
2638 ++f;
2639 }
Victor Stinner96865452011-03-01 23:44:09 +00002640 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002641 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002642 longlongflag = 1;
2643 f += 2;
2644 }
Victor Stinner96865452011-03-01 23:44:09 +00002645 }
2646 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002647 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002648 size_tflag = 1;
2649 ++f;
2650 }
Victor Stinnere215d962012-10-06 23:03:36 +02002651
2652 if (f[1] == '\0')
2653 writer->overallocate = 0;
2654
2655 switch (*f) {
2656 case 'c':
2657 {
2658 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002659 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002660 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002661 "character argument not in range(0x110000)");
2662 return NULL;
2663 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002664 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002665 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002666 break;
2667 }
2668
2669 case 'i':
2670 case 'd':
2671 case 'u':
2672 case 'x':
2673 {
2674 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002675 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002676 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002677
2678 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002679 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002680 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002681 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002682 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002683 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002684 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002685 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002686 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002687 va_arg(*vargs, size_t));
2688 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002689 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002690 va_arg(*vargs, unsigned int));
2691 }
2692 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002693 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002694 }
2695 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002696 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002697 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002698 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002699 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002700 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002701 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002702 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002703 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002704 va_arg(*vargs, Py_ssize_t));
2705 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002706 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002707 va_arg(*vargs, int));
2708 }
2709 assert(len >= 0);
2710
Victor Stinnere215d962012-10-06 23:03:36 +02002711 if (precision < len)
2712 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002713
2714 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002715 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2716 return NULL;
2717
Victor Stinnere215d962012-10-06 23:03:36 +02002718 if (width > precision) {
2719 Py_UCS4 fillchar;
2720 fill = width - precision;
2721 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002722 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2723 return NULL;
2724 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002725 }
Victor Stinner15a11362012-10-06 23:48:20 +02002726 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002727 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002728 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2729 return NULL;
2730 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002731 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002732
Victor Stinner4a587072013-11-19 12:54:53 +01002733 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2734 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002735 break;
2736 }
2737
2738 case 'p':
2739 {
2740 char number[MAX_LONG_LONG_CHARS];
2741
2742 len = sprintf(number, "%p", va_arg(*vargs, void*));
2743 assert(len >= 0);
2744
2745 /* %p is ill-defined: ensure leading 0x. */
2746 if (number[1] == 'X')
2747 number[1] = 'x';
2748 else if (number[1] != 'x') {
2749 memmove(number + 2, number,
2750 strlen(number) + 1);
2751 number[0] = '0';
2752 number[1] = 'x';
2753 len += 2;
2754 }
2755
Victor Stinner4a587072013-11-19 12:54:53 +01002756 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002757 return NULL;
2758 break;
2759 }
2760
2761 case 's':
2762 {
2763 /* UTF-8 */
2764 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002765 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002766 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002767 break;
2768 }
2769
2770 case 'U':
2771 {
2772 PyObject *obj = va_arg(*vargs, PyObject *);
2773 assert(obj && _PyUnicode_CHECK(obj));
2774
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002775 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002776 return NULL;
2777 break;
2778 }
2779
2780 case 'V':
2781 {
2782 PyObject *obj = va_arg(*vargs, PyObject *);
2783 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002784 if (obj) {
2785 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002786 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002787 return NULL;
2788 }
2789 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002790 assert(str != NULL);
2791 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002792 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002793 }
2794 break;
2795 }
2796
2797 case 'S':
2798 {
2799 PyObject *obj = va_arg(*vargs, PyObject *);
2800 PyObject *str;
2801 assert(obj);
2802 str = PyObject_Str(obj);
2803 if (!str)
2804 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002805 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002806 Py_DECREF(str);
2807 return NULL;
2808 }
2809 Py_DECREF(str);
2810 break;
2811 }
2812
2813 case 'R':
2814 {
2815 PyObject *obj = va_arg(*vargs, PyObject *);
2816 PyObject *repr;
2817 assert(obj);
2818 repr = PyObject_Repr(obj);
2819 if (!repr)
2820 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002821 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002822 Py_DECREF(repr);
2823 return NULL;
2824 }
2825 Py_DECREF(repr);
2826 break;
2827 }
2828
2829 case 'A':
2830 {
2831 PyObject *obj = va_arg(*vargs, PyObject *);
2832 PyObject *ascii;
2833 assert(obj);
2834 ascii = PyObject_ASCII(obj);
2835 if (!ascii)
2836 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002837 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002838 Py_DECREF(ascii);
2839 return NULL;
2840 }
2841 Py_DECREF(ascii);
2842 break;
2843 }
2844
2845 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002846 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002847 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002848 break;
2849
2850 default:
2851 /* if we stumble upon an unknown formatting code, copy the rest
2852 of the format string to the output string. (we cannot just
2853 skip the code, since there's no way to know what's in the
2854 argument list) */
2855 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002856 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002857 return NULL;
2858 f = p+len;
2859 return f;
2860 }
2861
2862 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002863 return f;
2864}
2865
Walter Dörwaldd2034312007-05-18 16:29:38 +00002866PyObject *
2867PyUnicode_FromFormatV(const char *format, va_list vargs)
2868{
Victor Stinnere215d962012-10-06 23:03:36 +02002869 va_list vargs2;
2870 const char *f;
2871 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002872
Victor Stinner8f674cc2013-04-17 23:02:17 +02002873 _PyUnicodeWriter_Init(&writer);
2874 writer.min_length = strlen(format) + 100;
2875 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002876
Benjamin Peterson0c212142016-09-20 20:39:33 -07002877 // Copy varags to be able to pass a reference to a subfunction.
2878 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002879
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);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002898 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002899 }
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 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002914 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002915 return _PyUnicodeWriter_Finish(&writer);
2916
2917 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002918 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002919 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002920 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002921}
2922
Walter Dörwaldd2034312007-05-18 16:29:38 +00002923PyObject *
2924PyUnicode_FromFormat(const char *format, ...)
2925{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002926 PyObject* ret;
2927 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002928
2929#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002930 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002931#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002932 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002933#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002934 ret = PyUnicode_FromFormatV(format, vargs);
2935 va_end(vargs);
2936 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002937}
2938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002939#ifdef HAVE_WCHAR_H
2940
Victor Stinner5593d8a2010-10-02 11:11:27 +00002941/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2942 convert a Unicode object to a wide character string.
2943
Victor Stinnerd88d9832011-09-06 02:00:05 +02002944 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002945 character) required to convert the unicode object. Ignore size argument.
2946
Victor Stinnerd88d9832011-09-06 02:00:05 +02002947 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002948 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002949 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002950static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002951unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002952 wchar_t *w,
2953 Py_ssize_t size)
2954{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002955 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002956 const wchar_t *wstr;
2957
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002958 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002959 if (wstr == NULL)
2960 return -1;
2961
Victor Stinner5593d8a2010-10-02 11:11:27 +00002962 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002963 if (size > res)
2964 size = res + 1;
2965 else
2966 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002967 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002968 return res;
2969 }
2970 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002971 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002972}
2973
2974Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002975PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002976 wchar_t *w,
2977 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002978{
2979 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002980 PyErr_BadInternalCall();
2981 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002982 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002983 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002984}
2985
Victor Stinner137c34c2010-09-29 10:25:54 +00002986wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002987PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002988 Py_ssize_t *size)
2989{
2990 wchar_t* buffer;
2991 Py_ssize_t buflen;
2992
2993 if (unicode == NULL) {
2994 PyErr_BadInternalCall();
2995 return NULL;
2996 }
2997
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002998 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002999 if (buflen == -1)
3000 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003001 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00003002 if (buffer == NULL) {
3003 PyErr_NoMemory();
3004 return NULL;
3005 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003006 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02003007 if (buflen == -1) {
3008 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003009 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02003010 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00003011 if (size != NULL)
3012 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003013 return buffer;
3014}
3015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003016#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003017
Alexander Belopolsky40018472011-02-26 01:02:56 +00003018PyObject *
3019PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003020{
Victor Stinner8faf8212011-12-08 22:14:11 +01003021 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003022 PyErr_SetString(PyExc_ValueError,
3023 "chr() arg not in range(0x110000)");
3024 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003025 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003026
Victor Stinner985a82a2014-01-03 12:53:47 +01003027 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003028}
3029
Alexander Belopolsky40018472011-02-26 01:02:56 +00003030PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003031PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003032{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003033 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003035 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003036 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003037 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003038 Py_INCREF(obj);
3039 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003040 }
3041 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003042 /* For a Unicode subtype that's not a Unicode object,
3043 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003044 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003045 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003046 PyErr_Format(PyExc_TypeError,
3047 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003048 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003049 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003050}
3051
Alexander Belopolsky40018472011-02-26 01:02:56 +00003052PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003053PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003054 const char *encoding,
3055 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003056{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003057 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003058 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003059
Guido van Rossumd57fd912000-03-10 22:53:23 +00003060 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003061 PyErr_BadInternalCall();
3062 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003063 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003064
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003065 /* Decoding bytes objects is the most common case and should be fast */
3066 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003067 if (PyBytes_GET_SIZE(obj) == 0)
3068 _Py_RETURN_UNICODE_EMPTY();
3069 v = PyUnicode_Decode(
3070 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3071 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003072 return v;
3073 }
3074
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003075 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003076 PyErr_SetString(PyExc_TypeError,
3077 "decoding str is not supported");
3078 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003079 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003080
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003081 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3082 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3083 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003084 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003085 Py_TYPE(obj)->tp_name);
3086 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003087 }
Tim Petersced69f82003-09-16 20:30:58 +00003088
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003089 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003090 PyBuffer_Release(&buffer);
3091 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003092 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003093
Serhiy Storchaka05997252013-01-26 12:14:02 +02003094 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003095 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003096 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003097}
3098
Victor Stinnerebe17e02016-10-12 13:57:45 +02003099/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3100 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3101 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003102int
3103_Py_normalize_encoding(const char *encoding,
3104 char *lower,
3105 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003106{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003107 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003108 char *l;
3109 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003110 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003111
Victor Stinner942889a2016-09-05 15:40:10 -07003112 assert(encoding != NULL);
3113
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003114 e = encoding;
3115 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003116 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003117 punct = 0;
3118 while (1) {
3119 char c = *e;
3120 if (c == 0) {
3121 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003122 }
Victor Stinner942889a2016-09-05 15:40:10 -07003123
3124 if (Py_ISALNUM(c) || c == '.') {
3125 if (punct && l != lower) {
3126 if (l == l_end) {
3127 return 0;
3128 }
3129 *l++ = '_';
3130 }
3131 punct = 0;
3132
3133 if (l == l_end) {
3134 return 0;
3135 }
3136 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003137 }
3138 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003139 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003140 }
Victor Stinner942889a2016-09-05 15:40:10 -07003141
3142 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003143 }
3144 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003145 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003146}
3147
Alexander Belopolsky40018472011-02-26 01:02:56 +00003148PyObject *
3149PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003150 Py_ssize_t size,
3151 const char *encoding,
3152 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003153{
3154 PyObject *buffer = NULL, *unicode;
3155 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003156 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3157
3158 if (encoding == NULL) {
3159 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3160 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003161
Fred Drakee4315f52000-05-09 19:53:39 +00003162 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003163 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3164 char *lower = buflower;
3165
3166 /* Fast paths */
3167 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3168 lower += 3;
3169 if (*lower == '_') {
3170 /* Match "utf8" and "utf_8" */
3171 lower++;
3172 }
3173
3174 if (lower[0] == '8' && lower[1] == 0) {
3175 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3176 }
3177 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3178 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3179 }
3180 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3181 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3182 }
3183 }
3184 else {
3185 if (strcmp(lower, "ascii") == 0
3186 || strcmp(lower, "us_ascii") == 0) {
3187 return PyUnicode_DecodeASCII(s, size, errors);
3188 }
Steve Dowercc16be82016-09-08 10:35:16 -07003189 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003190 else if (strcmp(lower, "mbcs") == 0) {
3191 return PyUnicode_DecodeMBCS(s, size, errors);
3192 }
3193 #endif
3194 else if (strcmp(lower, "latin1") == 0
3195 || strcmp(lower, "latin_1") == 0
3196 || strcmp(lower, "iso_8859_1") == 0
3197 || strcmp(lower, "iso8859_1") == 0) {
3198 return PyUnicode_DecodeLatin1(s, size, errors);
3199 }
3200 }
Victor Stinner37296e82010-06-10 13:36:23 +00003201 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003202
3203 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003204 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003205 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003206 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003207 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003208 if (buffer == NULL)
3209 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003210 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003211 if (unicode == NULL)
3212 goto onError;
3213 if (!PyUnicode_Check(unicode)) {
3214 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003215 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3216 "use codecs.decode() to decode to arbitrary types",
3217 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003218 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003219 Py_DECREF(unicode);
3220 goto onError;
3221 }
3222 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003223 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003224
Benjamin Peterson29060642009-01-31 22:14:21 +00003225 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003226 Py_XDECREF(buffer);
3227 return NULL;
3228}
3229
Alexander Belopolsky40018472011-02-26 01:02:56 +00003230PyObject *
3231PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003232 const char *encoding,
3233 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003234{
3235 PyObject *v;
3236
3237 if (!PyUnicode_Check(unicode)) {
3238 PyErr_BadArgument();
3239 goto onError;
3240 }
3241
3242 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003243 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003244
3245 /* Decode via the codec registry */
3246 v = PyCodec_Decode(unicode, encoding, errors);
3247 if (v == NULL)
3248 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003249 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003250
Benjamin Peterson29060642009-01-31 22:14:21 +00003251 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003252 return NULL;
3253}
3254
Alexander Belopolsky40018472011-02-26 01:02:56 +00003255PyObject *
3256PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003257 const char *encoding,
3258 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003259{
3260 PyObject *v;
3261
3262 if (!PyUnicode_Check(unicode)) {
3263 PyErr_BadArgument();
3264 goto onError;
3265 }
3266
3267 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003268 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003269
3270 /* Decode via the codec registry */
3271 v = PyCodec_Decode(unicode, encoding, errors);
3272 if (v == NULL)
3273 goto onError;
3274 if (!PyUnicode_Check(v)) {
3275 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003276 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3277 "use codecs.decode() to decode to arbitrary types",
3278 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003279 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003280 Py_DECREF(v);
3281 goto onError;
3282 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003283 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003284
Benjamin Peterson29060642009-01-31 22:14:21 +00003285 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003286 return NULL;
3287}
3288
Alexander Belopolsky40018472011-02-26 01:02:56 +00003289PyObject *
3290PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003291 Py_ssize_t size,
3292 const char *encoding,
3293 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003294{
3295 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003296
Guido van Rossumd57fd912000-03-10 22:53:23 +00003297 unicode = PyUnicode_FromUnicode(s, size);
3298 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003299 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003300 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3301 Py_DECREF(unicode);
3302 return v;
3303}
3304
Alexander Belopolsky40018472011-02-26 01:02:56 +00003305PyObject *
3306PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003307 const char *encoding,
3308 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003309{
3310 PyObject *v;
3311
3312 if (!PyUnicode_Check(unicode)) {
3313 PyErr_BadArgument();
3314 goto onError;
3315 }
3316
3317 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003318 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003319
3320 /* Encode via the codec registry */
3321 v = PyCodec_Encode(unicode, encoding, errors);
3322 if (v == NULL)
3323 goto onError;
3324 return v;
3325
Benjamin Peterson29060642009-01-31 22:14:21 +00003326 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003327 return NULL;
3328}
3329
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003330static size_t
3331wcstombs_errorpos(const wchar_t *wstr)
3332{
3333 size_t len;
3334#if SIZEOF_WCHAR_T == 2
3335 wchar_t buf[3];
3336#else
3337 wchar_t buf[2];
3338#endif
3339 char outbuf[MB_LEN_MAX];
3340 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003341
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003342#if SIZEOF_WCHAR_T == 2
3343 buf[2] = 0;
3344#else
3345 buf[1] = 0;
3346#endif
3347 start = wstr;
3348 while (*wstr != L'\0')
3349 {
3350 previous = wstr;
3351#if SIZEOF_WCHAR_T == 2
3352 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3353 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3354 {
3355 buf[0] = wstr[0];
3356 buf[1] = wstr[1];
3357 wstr += 2;
3358 }
3359 else {
3360 buf[0] = *wstr;
3361 buf[1] = 0;
3362 wstr++;
3363 }
3364#else
3365 buf[0] = *wstr;
3366 wstr++;
3367#endif
3368 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003369 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003370 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003371 }
3372
3373 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003374 return 0;
3375}
3376
Victor Stinner1b579672011-12-17 05:47:23 +01003377static int
3378locale_error_handler(const char *errors, int *surrogateescape)
3379{
Victor Stinner50149202015-09-22 00:26:54 +02003380 _Py_error_handler error_handler = get_error_handler(errors);
3381 switch (error_handler)
3382 {
3383 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003384 *surrogateescape = 0;
3385 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003386 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003387 *surrogateescape = 1;
3388 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003389 default:
3390 PyErr_Format(PyExc_ValueError,
3391 "only 'strict' and 'surrogateescape' error handlers "
3392 "are supported, not '%s'",
3393 errors);
3394 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003395 }
Victor Stinner1b579672011-12-17 05:47:23 +01003396}
3397
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003399PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003400{
3401 Py_ssize_t wlen, wlen2;
3402 wchar_t *wstr;
3403 PyObject *bytes = NULL;
3404 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003405 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003406 PyObject *exc;
3407 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003408 int surrogateescape;
3409
3410 if (locale_error_handler(errors, &surrogateescape) < 0)
3411 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003412
3413 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3414 if (wstr == NULL)
3415 return NULL;
3416
3417 wlen2 = wcslen(wstr);
3418 if (wlen2 != wlen) {
3419 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003420 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003421 return NULL;
3422 }
3423
3424 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003425 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003426 char *str;
3427
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003428 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003429 if (str == NULL) {
3430 if (error_pos == (size_t)-1) {
3431 PyErr_NoMemory();
3432 PyMem_Free(wstr);
3433 return NULL;
3434 }
3435 else {
3436 goto encode_error;
3437 }
3438 }
3439 PyMem_Free(wstr);
3440
3441 bytes = PyBytes_FromString(str);
3442 PyMem_Free(str);
3443 }
3444 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003445 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003446 size_t len, len2;
3447
3448 len = wcstombs(NULL, wstr, 0);
3449 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003450 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003451 goto encode_error;
3452 }
3453
3454 bytes = PyBytes_FromStringAndSize(NULL, len);
3455 if (bytes == NULL) {
3456 PyMem_Free(wstr);
3457 return NULL;
3458 }
3459
3460 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3461 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003462 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003463 goto encode_error;
3464 }
3465 PyMem_Free(wstr);
3466 }
3467 return bytes;
3468
3469encode_error:
3470 errmsg = strerror(errno);
3471 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003472
3473 if (error_pos == (size_t)-1)
3474 error_pos = wcstombs_errorpos(wstr);
3475
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003476 PyMem_Free(wstr);
3477 Py_XDECREF(bytes);
3478
Victor Stinner2f197072011-12-17 07:08:30 +01003479 if (errmsg != NULL) {
3480 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003481 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003482 if (wstr != NULL) {
3483 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003484 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003485 } else
3486 errmsg = NULL;
3487 }
3488 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003489 reason = PyUnicode_FromString(
3490 "wcstombs() encountered an unencodable "
3491 "wide character");
3492 if (reason == NULL)
3493 return NULL;
3494
3495 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3496 "locale", unicode,
3497 (Py_ssize_t)error_pos,
3498 (Py_ssize_t)(error_pos+1),
3499 reason);
3500 Py_DECREF(reason);
3501 if (exc != NULL) {
3502 PyCodec_StrictErrors(exc);
3503 Py_XDECREF(exc);
3504 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003505 return NULL;
3506}
3507
Victor Stinnerad158722010-10-27 00:25:46 +00003508PyObject *
3509PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003510{
Steve Dowercc16be82016-09-08 10:35:16 -07003511#if defined(__APPLE__)
3512 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
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,
Steve Dowercc16be82016-09-08 10:35:16 -07003527 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003528 }
3529 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003530 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
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 }
Steve Dowercc16be82016-09-08 10:35:16 -07003579#ifdef MS_WINDOWS
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,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003625 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,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003654 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{
Steve Dowercc16be82016-09-08 10:35:16 -07003815#if defined(__APPLE__)
3816 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003817#else
Victor Stinner793b5312011-04-27 00:24:21 +02003818 PyInterpreterState *interp = PyThreadState_GET()->interp;
3819 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3820 cannot use it to encode and decode filenames before it is loaded. Load
3821 the Python codec requires to encode at least its own filename. Use the C
3822 version of the locale codec until the codec registry is initialized and
3823 the Python codec is loaded.
3824
3825 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3826 cannot only rely on it: check also interp->fscodec_initialized for
3827 subinterpreters. */
3828 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dowercc16be82016-09-08 10:35:16 -07003829 PyObject *res = PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003830 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003831 Py_FileSystemDefaultEncodeErrors);
3832#ifdef MS_WINDOWS
3833 if (!res && PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
Serhiy Storchaka467ab192016-10-21 17:09:17 +03003834 _PyErr_FormatFromCause(PyExc_RuntimeError,
3835 "filesystem path bytes were not correctly encoded with '%s'. "
Steve Dowercc16be82016-09-08 10:35:16 -07003836 "Please report this at http://bugs.python.org/issue27781",
3837 Py_FileSystemDefaultEncoding);
Steve Dowercc16be82016-09-08 10:35:16 -07003838 }
3839#endif
3840 return res;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003841 }
3842 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003843 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003844 }
Victor Stinnerad158722010-10-27 00:25:46 +00003845#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003846}
3847
Martin v. Löwis011e8422009-05-05 04:43:17 +00003848
3849int
3850PyUnicode_FSConverter(PyObject* arg, void* addr)
3851{
Brett Cannonec6ce872016-09-06 15:50:29 -07003852 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003853 PyObject *output = NULL;
3854 Py_ssize_t size;
3855 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003856 if (arg == NULL) {
3857 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003858 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003859 return 1;
3860 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003861 path = PyOS_FSPath(arg);
3862 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003863 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003864 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003865 if (PyBytes_Check(path)) {
3866 output = path;
3867 }
3868 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3869 output = PyUnicode_EncodeFSDefault(path);
3870 Py_DECREF(path);
3871 if (!output) {
3872 return 0;
3873 }
3874 assert(PyBytes_Check(output));
3875 }
3876
Victor Stinner0ea2a462010-04-30 00:22:08 +00003877 size = PyBytes_GET_SIZE(output);
3878 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003879 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003880 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003881 Py_DECREF(output);
3882 return 0;
3883 }
3884 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003885 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003886}
3887
3888
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003889int
3890PyUnicode_FSDecoder(PyObject* arg, void* addr)
3891{
Brett Cannona5711202016-09-06 19:36:01 -07003892 int is_buffer = 0;
3893 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003894 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003895 if (arg == NULL) {
3896 Py_DECREF(*(PyObject**)addr);
3897 return 1;
3898 }
Brett Cannona5711202016-09-06 19:36:01 -07003899
3900 is_buffer = PyObject_CheckBuffer(arg);
3901 if (!is_buffer) {
3902 path = PyOS_FSPath(arg);
3903 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003904 return 0;
3905 }
Brett Cannona5711202016-09-06 19:36:01 -07003906 }
3907 else {
3908 path = arg;
3909 Py_INCREF(arg);
3910 }
3911
3912 if (PyUnicode_Check(path)) {
3913 if (PyUnicode_READY(path) == -1) {
3914 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003915 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003916 }
3917 output = path;
3918 }
3919 else if (PyBytes_Check(path) || is_buffer) {
3920 PyObject *path_bytes = NULL;
3921
3922 if (!PyBytes_Check(path) &&
3923 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3924 "path should be string, bytes, or os.PathLike, not %.200s",
3925 Py_TYPE(arg)->tp_name)) {
3926 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003927 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003928 }
3929 path_bytes = PyBytes_FromObject(path);
3930 Py_DECREF(path);
3931 if (!path_bytes) {
3932 return 0;
3933 }
3934 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3935 PyBytes_GET_SIZE(path_bytes));
3936 Py_DECREF(path_bytes);
3937 if (!output) {
3938 return 0;
3939 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003940 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003941 else {
3942 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003943 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003944 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003945 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003946 return 0;
3947 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003948 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003949 Py_DECREF(output);
3950 return 0;
3951 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003952 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003953 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003954 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003955 Py_DECREF(output);
3956 return 0;
3957 }
3958 *(PyObject**)addr = output;
3959 return Py_CLEANUP_SUPPORTED;
3960}
3961
3962
Martin v. Löwis5b222132007-06-10 09:51:05 +00003963char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003964PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003965{
Christian Heimesf3863112007-11-22 07:46:41 +00003966 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003967
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003968 if (!PyUnicode_Check(unicode)) {
3969 PyErr_BadArgument();
3970 return NULL;
3971 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003972 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003973 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003975 if (PyUnicode_UTF8(unicode) == NULL) {
3976 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003977 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003978 if (bytes == NULL)
3979 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003980 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3981 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003982 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003983 Py_DECREF(bytes);
3984 return NULL;
3985 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003986 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003987 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003988 PyBytes_AS_STRING(bytes),
3989 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003990 Py_DECREF(bytes);
3991 }
3992
3993 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003994 *psize = PyUnicode_UTF8_LENGTH(unicode);
3995 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003996}
3997
3998char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003999PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004000{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004001 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4002}
4003
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004Py_UNICODE *
4005PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4006{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004007 const unsigned char *one_byte;
4008#if SIZEOF_WCHAR_T == 4
4009 const Py_UCS2 *two_bytes;
4010#else
4011 const Py_UCS4 *four_bytes;
4012 const Py_UCS4 *ucs4_end;
4013 Py_ssize_t num_surrogates;
4014#endif
4015 wchar_t *w;
4016 wchar_t *wchar_end;
4017
4018 if (!PyUnicode_Check(unicode)) {
4019 PyErr_BadArgument();
4020 return NULL;
4021 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004022 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004023 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004024 assert(_PyUnicode_KIND(unicode) != 0);
4025 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004026
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004027 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004028#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004029 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4030 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004031 num_surrogates = 0;
4032
4033 for (; four_bytes < ucs4_end; ++four_bytes) {
4034 if (*four_bytes > 0xFFFF)
4035 ++num_surrogates;
4036 }
4037
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004038 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4039 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4040 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004041 PyErr_NoMemory();
4042 return NULL;
4043 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004044 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004045
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004046 w = _PyUnicode_WSTR(unicode);
4047 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4048 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004049 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4050 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004051 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004052 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004053 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4054 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004055 }
4056 else
4057 *w = *four_bytes;
4058
4059 if (w > wchar_end) {
4060 assert(0 && "Miscalculated string end");
4061 }
4062 }
4063 *w = 0;
4064#else
4065 /* sizeof(wchar_t) == 4 */
4066 Py_FatalError("Impossible unicode object state, wstr and str "
4067 "should share memory already.");
4068 return NULL;
4069#endif
4070 }
4071 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004072 if ((size_t)_PyUnicode_LENGTH(unicode) >
4073 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4074 PyErr_NoMemory();
4075 return NULL;
4076 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004077 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4078 (_PyUnicode_LENGTH(unicode) + 1));
4079 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004080 PyErr_NoMemory();
4081 return NULL;
4082 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004083 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4084 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4085 w = _PyUnicode_WSTR(unicode);
4086 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004087
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004088 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4089 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004090 for (; w < wchar_end; ++one_byte, ++w)
4091 *w = *one_byte;
4092 /* null-terminate the wstr */
4093 *w = 0;
4094 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004095 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004096#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004097 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004098 for (; w < wchar_end; ++two_bytes, ++w)
4099 *w = *two_bytes;
4100 /* null-terminate the wstr */
4101 *w = 0;
4102#else
4103 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004104 PyObject_FREE(_PyUnicode_WSTR(unicode));
4105 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004106 Py_FatalError("Impossible unicode object state, wstr "
4107 "and str should share memory already.");
4108 return NULL;
4109#endif
4110 }
4111 else {
4112 assert(0 && "This should never happen.");
4113 }
4114 }
4115 }
4116 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004117 *size = PyUnicode_WSTR_LENGTH(unicode);
4118 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004119}
4120
Alexander Belopolsky40018472011-02-26 01:02:56 +00004121Py_UNICODE *
4122PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004123{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004124 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004125}
4126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004127
Alexander Belopolsky40018472011-02-26 01:02:56 +00004128Py_ssize_t
4129PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004130{
4131 if (!PyUnicode_Check(unicode)) {
4132 PyErr_BadArgument();
4133 goto onError;
4134 }
4135 return PyUnicode_GET_SIZE(unicode);
4136
Benjamin Peterson29060642009-01-31 22:14:21 +00004137 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004138 return -1;
4139}
4140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004141Py_ssize_t
4142PyUnicode_GetLength(PyObject *unicode)
4143{
Victor Stinner07621332012-06-16 04:53:46 +02004144 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004145 PyErr_BadArgument();
4146 return -1;
4147 }
Victor Stinner07621332012-06-16 04:53:46 +02004148 if (PyUnicode_READY(unicode) == -1)
4149 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004150 return PyUnicode_GET_LENGTH(unicode);
4151}
4152
4153Py_UCS4
4154PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4155{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004156 void *data;
4157 int kind;
4158
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004159 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4160 PyErr_BadArgument();
4161 return (Py_UCS4)-1;
4162 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004163 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004164 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004165 return (Py_UCS4)-1;
4166 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004167 data = PyUnicode_DATA(unicode);
4168 kind = PyUnicode_KIND(unicode);
4169 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004170}
4171
4172int
4173PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4174{
4175 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004176 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004177 return -1;
4178 }
Victor Stinner488fa492011-12-12 00:01:39 +01004179 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004180 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004181 PyErr_SetString(PyExc_IndexError, "string index out of range");
4182 return -1;
4183 }
Victor Stinner488fa492011-12-12 00:01:39 +01004184 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004185 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004186 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4187 PyErr_SetString(PyExc_ValueError, "character out of range");
4188 return -1;
4189 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004190 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4191 index, ch);
4192 return 0;
4193}
4194
Alexander Belopolsky40018472011-02-26 01:02:56 +00004195const char *
4196PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004197{
Victor Stinner42cb4622010-09-01 19:39:01 +00004198 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004199}
4200
Victor Stinner554f3f02010-06-16 23:33:54 +00004201/* create or adjust a UnicodeDecodeError */
4202static void
4203make_decode_exception(PyObject **exceptionObject,
4204 const char *encoding,
4205 const char *input, Py_ssize_t length,
4206 Py_ssize_t startpos, Py_ssize_t endpos,
4207 const char *reason)
4208{
4209 if (*exceptionObject == NULL) {
4210 *exceptionObject = PyUnicodeDecodeError_Create(
4211 encoding, input, length, startpos, endpos, reason);
4212 }
4213 else {
4214 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4215 goto onError;
4216 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4217 goto onError;
4218 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4219 goto onError;
4220 }
4221 return;
4222
4223onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004224 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004225}
4226
Steve Dowercc16be82016-09-08 10:35:16 -07004227#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004228/* error handling callback helper:
4229 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004230 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004231 and adjust various state variables.
4232 return 0 on success, -1 on error
4233*/
4234
Alexander Belopolsky40018472011-02-26 01:02:56 +00004235static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004236unicode_decode_call_errorhandler_wchar(
4237 const char *errors, PyObject **errorHandler,
4238 const char *encoding, const char *reason,
4239 const char **input, const char **inend, Py_ssize_t *startinpos,
4240 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4241 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004242{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004243 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004244
4245 PyObject *restuple = NULL;
4246 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004247 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004248 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004249 Py_ssize_t requiredsize;
4250 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004251 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004252 wchar_t *repwstr;
4253 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004254
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004255 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4256 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004257
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004258 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004259 *errorHandler = PyCodec_LookupError(errors);
4260 if (*errorHandler == NULL)
4261 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004262 }
4263
Victor Stinner554f3f02010-06-16 23:33:54 +00004264 make_decode_exception(exceptionObject,
4265 encoding,
4266 *input, *inend - *input,
4267 *startinpos, *endinpos,
4268 reason);
4269 if (*exceptionObject == NULL)
4270 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004271
4272 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4273 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004274 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004275 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004276 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004277 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004278 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004279 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004280 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004281
4282 /* Copy back the bytes variables, which might have been modified by the
4283 callback */
4284 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4285 if (!inputobj)
4286 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004287 *input = PyBytes_AS_STRING(inputobj);
4288 insize = PyBytes_GET_SIZE(inputobj);
4289 *inend = *input + insize;
4290 /* we can DECREF safely, as the exception has another reference,
4291 so the object won't go away. */
4292 Py_DECREF(inputobj);
4293
4294 if (newpos<0)
4295 newpos = insize+newpos;
4296 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004297 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004298 goto onError;
4299 }
4300
4301 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4302 if (repwstr == NULL)
4303 goto onError;
4304 /* need more space? (at least enough for what we
4305 have+the replacement+the rest of the string (starting
4306 at the new input position), so we won't have to check space
4307 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004308 requiredsize = *outpos;
4309 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4310 goto overflow;
4311 requiredsize += repwlen;
4312 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4313 goto overflow;
4314 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004315 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004316 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004317 requiredsize = 2*outsize;
4318 if (unicode_resize(output, requiredsize) < 0)
4319 goto onError;
4320 }
4321 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4322 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004323 *endinpos = newpos;
4324 *inptr = *input + newpos;
4325
4326 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004327 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004328 return 0;
4329
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004330 overflow:
4331 PyErr_SetString(PyExc_OverflowError,
4332 "decoded result is too long for a Python string");
4333
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004334 onError:
4335 Py_XDECREF(restuple);
4336 return -1;
4337}
Steve Dowercc16be82016-09-08 10:35:16 -07004338#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004339
4340static int
4341unicode_decode_call_errorhandler_writer(
4342 const char *errors, PyObject **errorHandler,
4343 const char *encoding, const char *reason,
4344 const char **input, const char **inend, Py_ssize_t *startinpos,
4345 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4346 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4347{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004348 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004349
4350 PyObject *restuple = NULL;
4351 PyObject *repunicode = NULL;
4352 Py_ssize_t insize;
4353 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004354 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004355 PyObject *inputobj = NULL;
4356
4357 if (*errorHandler == NULL) {
4358 *errorHandler = PyCodec_LookupError(errors);
4359 if (*errorHandler == NULL)
4360 goto onError;
4361 }
4362
4363 make_decode_exception(exceptionObject,
4364 encoding,
4365 *input, *inend - *input,
4366 *startinpos, *endinpos,
4367 reason);
4368 if (*exceptionObject == NULL)
4369 goto onError;
4370
4371 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4372 if (restuple == NULL)
4373 goto onError;
4374 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004375 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004376 goto onError;
4377 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004378 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004379 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004380
4381 /* Copy back the bytes variables, which might have been modified by the
4382 callback */
4383 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4384 if (!inputobj)
4385 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004386 *input = PyBytes_AS_STRING(inputobj);
4387 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004388 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004389 /* we can DECREF safely, as the exception has another reference,
4390 so the object won't go away. */
4391 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004392
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004393 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004394 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004395 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004396 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004397 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004398 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004399
Victor Stinner170ca6f2013-04-18 00:25:28 +02004400 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004401 if (replen > 1) {
4402 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004403 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004404 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4405 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4406 goto onError;
4407 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004408 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004409 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004410
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004411 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004412 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004413
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004414 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004415 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004416 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004417
Benjamin Peterson29060642009-01-31 22:14:21 +00004418 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004419 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004420 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004421}
4422
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004423/* --- UTF-7 Codec -------------------------------------------------------- */
4424
Antoine Pitrou244651a2009-05-04 18:56:13 +00004425/* See RFC2152 for details. We encode conservatively and decode liberally. */
4426
4427/* Three simple macros defining base-64. */
4428
4429/* Is c a base-64 character? */
4430
4431#define IS_BASE64(c) \
4432 (((c) >= 'A' && (c) <= 'Z') || \
4433 ((c) >= 'a' && (c) <= 'z') || \
4434 ((c) >= '0' && (c) <= '9') || \
4435 (c) == '+' || (c) == '/')
4436
4437/* given that c is a base-64 character, what is its base-64 value? */
4438
4439#define FROM_BASE64(c) \
4440 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4441 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4442 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4443 (c) == '+' ? 62 : 63)
4444
4445/* What is the base-64 character of the bottom 6 bits of n? */
4446
4447#define TO_BASE64(n) \
4448 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4449
4450/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4451 * decoded as itself. We are permissive on decoding; the only ASCII
4452 * byte not decoding to itself is the + which begins a base64
4453 * string. */
4454
4455#define DECODE_DIRECT(c) \
4456 ((c) <= 127 && (c) != '+')
4457
4458/* The UTF-7 encoder treats ASCII characters differently according to
4459 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4460 * the above). See RFC2152. This array identifies these different
4461 * sets:
4462 * 0 : "Set D"
4463 * alphanumeric and '(),-./:?
4464 * 1 : "Set O"
4465 * !"#$%&*;<=>@[]^_`{|}
4466 * 2 : "whitespace"
4467 * ht nl cr sp
4468 * 3 : special (must be base64 encoded)
4469 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4470 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471
Tim Petersced69f82003-09-16 20:30:58 +00004472static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004473char utf7_category[128] = {
4474/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4475 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4476/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4477 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4478/* sp ! " # $ % & ' ( ) * + , - . / */
4479 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4480/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4481 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4482/* @ A B C D E F G H I J K L M N O */
4483 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4484/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4485 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4486/* ` a b c d e f g h i j k l m n o */
4487 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4488/* p q r s t u v w x y z { | } ~ del */
4489 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490};
4491
Antoine Pitrou244651a2009-05-04 18:56:13 +00004492/* ENCODE_DIRECT: this character should be encoded as itself. The
4493 * answer depends on whether we are encoding set O as itself, and also
4494 * on whether we are encoding whitespace as itself. RFC2152 makes it
4495 * clear that the answers to these questions vary between
4496 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004497
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498#define ENCODE_DIRECT(c, directO, directWS) \
4499 ((c) < 128 && (c) > 0 && \
4500 ((utf7_category[(c)] == 0) || \
4501 (directWS && (utf7_category[(c)] == 2)) || \
4502 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004503
Alexander Belopolsky40018472011-02-26 01:02:56 +00004504PyObject *
4505PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004506 Py_ssize_t size,
4507 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004508{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004509 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4510}
4511
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512/* The decoder. The only state we preserve is our read position,
4513 * i.e. how many characters we have consumed. So if we end in the
4514 * middle of a shift sequence we have to back off the read position
4515 * and the output to the beginning of the sequence, otherwise we lose
4516 * all the shift state (seen bits, number of bits seen, high
4517 * surrogate). */
4518
Alexander Belopolsky40018472011-02-26 01:02:56 +00004519PyObject *
4520PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004521 Py_ssize_t size,
4522 const char *errors,
4523 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004524{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004525 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004526 Py_ssize_t startinpos;
4527 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004528 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004529 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004530 const char *errmsg = "";
4531 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004532 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004533 unsigned int base64bits = 0;
4534 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004535 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004536 PyObject *errorHandler = NULL;
4537 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004539 if (size == 0) {
4540 if (consumed)
4541 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004542 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004543 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004545 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004546 _PyUnicodeWriter_Init(&writer);
4547 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004548
4549 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550 e = s + size;
4551
4552 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004553 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004554 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004555 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004556
Antoine Pitrou244651a2009-05-04 18:56:13 +00004557 if (inShift) { /* in a base-64 section */
4558 if (IS_BASE64(ch)) { /* consume a base-64 character */
4559 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4560 base64bits += 6;
4561 s++;
4562 if (base64bits >= 16) {
4563 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004564 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004565 base64bits -= 16;
4566 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004567 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004568 if (surrogate) {
4569 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004570 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4571 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004572 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004573 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004575 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004576 }
4577 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004578 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004579 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 }
4582 }
Victor Stinner551ac952011-11-29 22:58:13 +01004583 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 /* first surrogate */
4585 surrogate = outCh;
4586 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004587 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004588 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004589 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004590 }
4591 }
4592 }
4593 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004594 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004595 if (base64bits > 0) { /* left-over bits */
4596 if (base64bits >= 6) {
4597 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004598 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004599 errmsg = "partial character in shift sequence";
4600 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004601 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602 else {
4603 /* Some bits remain; they should be zero */
4604 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004605 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004606 errmsg = "non-zero padding bits in shift sequence";
4607 goto utf7Error;
4608 }
4609 }
4610 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004611 if (surrogate && DECODE_DIRECT(ch)) {
4612 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4613 goto onError;
4614 }
4615 surrogate = 0;
4616 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004617 /* '-' is absorbed; other terminating
4618 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004619 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004620 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004621 }
4622 }
4623 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004624 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004625 s++; /* consume '+' */
4626 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004627 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004628 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004629 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004630 }
4631 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004632 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004633 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004634 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004635 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004636 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004637 }
4638 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004639 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004640 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004641 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004642 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004643 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004644 else {
4645 startinpos = s-starts;
4646 s++;
4647 errmsg = "unexpected special character";
4648 goto utf7Error;
4649 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004650 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004651utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004652 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004653 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004654 errors, &errorHandler,
4655 "utf7", errmsg,
4656 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004657 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004658 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004659 }
4660
Antoine Pitrou244651a2009-05-04 18:56:13 +00004661 /* end of string */
4662
4663 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4664 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004665 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004666 if (surrogate ||
4667 (base64bits >= 6) ||
4668 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004669 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004670 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004671 errors, &errorHandler,
4672 "utf7", "unterminated shift sequence",
4673 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004674 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004675 goto onError;
4676 if (s < e)
4677 goto restart;
4678 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004679 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004680
4681 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004682 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004683 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004684 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004685 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004686 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004687 writer.kind, writer.data, shiftOutStart);
4688 Py_XDECREF(errorHandler);
4689 Py_XDECREF(exc);
4690 _PyUnicodeWriter_Dealloc(&writer);
4691 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004692 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004693 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004694 }
4695 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004696 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004697 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004698 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004699
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004700 Py_XDECREF(errorHandler);
4701 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004702 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004703
Benjamin Peterson29060642009-01-31 22:14:21 +00004704 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004705 Py_XDECREF(errorHandler);
4706 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004707 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004708 return NULL;
4709}
4710
4711
Alexander Belopolsky40018472011-02-26 01:02:56 +00004712PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004713_PyUnicode_EncodeUTF7(PyObject *str,
4714 int base64SetO,
4715 int base64WhiteSpace,
4716 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004717{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004718 int kind;
4719 void *data;
4720 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004721 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004722 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004723 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004724 unsigned int base64bits = 0;
4725 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004726 char * out;
4727 char * start;
4728
Benjamin Petersonbac79492012-01-14 13:34:47 -05004729 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004730 return NULL;
4731 kind = PyUnicode_KIND(str);
4732 data = PyUnicode_DATA(str);
4733 len = PyUnicode_GET_LENGTH(str);
4734
4735 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004736 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004737
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004738 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004739 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004740 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004741 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004742 if (v == NULL)
4743 return NULL;
4744
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004745 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004746 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004747 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004748
Antoine Pitrou244651a2009-05-04 18:56:13 +00004749 if (inShift) {
4750 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4751 /* shifting out */
4752 if (base64bits) { /* output remaining bits */
4753 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4754 base64buffer = 0;
4755 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004756 }
4757 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004758 /* Characters not in the BASE64 set implicitly unshift the sequence
4759 so no '-' is required, except if the character is itself a '-' */
4760 if (IS_BASE64(ch) || ch == '-') {
4761 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004762 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004763 *out++ = (char) ch;
4764 }
4765 else {
4766 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004767 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004768 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004769 else { /* not in a shift sequence */
4770 if (ch == '+') {
4771 *out++ = '+';
4772 *out++ = '-';
4773 }
4774 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4775 *out++ = (char) ch;
4776 }
4777 else {
4778 *out++ = '+';
4779 inShift = 1;
4780 goto encode_char;
4781 }
4782 }
4783 continue;
4784encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004785 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004786 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004787
Antoine Pitrou244651a2009-05-04 18:56:13 +00004788 /* code first surrogate */
4789 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004790 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004791 while (base64bits >= 6) {
4792 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4793 base64bits -= 6;
4794 }
4795 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004796 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004797 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004798 base64bits += 16;
4799 base64buffer = (base64buffer << 16) | ch;
4800 while (base64bits >= 6) {
4801 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4802 base64bits -= 6;
4803 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004804 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004805 if (base64bits)
4806 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4807 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004808 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004809 if (_PyBytes_Resize(&v, out - start) < 0)
4810 return NULL;
4811 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004812}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004813PyObject *
4814PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4815 Py_ssize_t size,
4816 int base64SetO,
4817 int base64WhiteSpace,
4818 const char *errors)
4819{
4820 PyObject *result;
4821 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4822 if (tmp == NULL)
4823 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004824 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004825 base64WhiteSpace, errors);
4826 Py_DECREF(tmp);
4827 return result;
4828}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004829
Antoine Pitrou244651a2009-05-04 18:56:13 +00004830#undef IS_BASE64
4831#undef FROM_BASE64
4832#undef TO_BASE64
4833#undef DECODE_DIRECT
4834#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004835
Guido van Rossumd57fd912000-03-10 22:53:23 +00004836/* --- UTF-8 Codec -------------------------------------------------------- */
4837
Alexander Belopolsky40018472011-02-26 01:02:56 +00004838PyObject *
4839PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004840 Py_ssize_t size,
4841 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004842{
Walter Dörwald69652032004-09-07 20:24:22 +00004843 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4844}
4845
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004846#include "stringlib/asciilib.h"
4847#include "stringlib/codecs.h"
4848#include "stringlib/undef.h"
4849
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004850#include "stringlib/ucs1lib.h"
4851#include "stringlib/codecs.h"
4852#include "stringlib/undef.h"
4853
4854#include "stringlib/ucs2lib.h"
4855#include "stringlib/codecs.h"
4856#include "stringlib/undef.h"
4857
4858#include "stringlib/ucs4lib.h"
4859#include "stringlib/codecs.h"
4860#include "stringlib/undef.h"
4861
Antoine Pitrouab868312009-01-10 15:40:25 +00004862/* Mask to quickly check whether a C 'long' contains a
4863 non-ASCII, UTF8-encoded char. */
4864#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004865# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004866#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004867# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004868#else
4869# error C 'long' size should be either 4 or 8!
4870#endif
4871
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004872static Py_ssize_t
4873ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004874{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004875 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004876 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004877
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004878 /*
4879 * Issue #17237: m68k is a bit different from most architectures in
4880 * that objects do not use "natural alignment" - for example, int and
4881 * long are only aligned at 2-byte boundaries. Therefore the assert()
4882 * won't work; also, tests have shown that skipping the "optimised
4883 * version" will even speed up m68k.
4884 */
4885#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004886#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004887 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4888 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004889 /* Fast path, see in STRINGLIB(utf8_decode) for
4890 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004891 /* Help allocation */
4892 const char *_p = p;
4893 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004894 while (_p < aligned_end) {
4895 unsigned long value = *(const unsigned long *) _p;
4896 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004897 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004898 *((unsigned long *)q) = value;
4899 _p += SIZEOF_LONG;
4900 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004901 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004902 p = _p;
4903 while (p < end) {
4904 if ((unsigned char)*p & 0x80)
4905 break;
4906 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004907 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004908 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004909 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004910#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004911#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004912 while (p < end) {
4913 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4914 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004915 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004916 /* Help allocation */
4917 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004918 while (_p < aligned_end) {
4919 unsigned long value = *(unsigned long *) _p;
4920 if (value & ASCII_CHAR_MASK)
4921 break;
4922 _p += SIZEOF_LONG;
4923 }
4924 p = _p;
4925 if (_p == end)
4926 break;
4927 }
4928 if ((unsigned char)*p & 0x80)
4929 break;
4930 ++p;
4931 }
4932 memcpy(dest, start, p - start);
4933 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004934}
Antoine Pitrouab868312009-01-10 15:40:25 +00004935
Victor Stinner785938e2011-12-11 20:09:03 +01004936PyObject *
4937PyUnicode_DecodeUTF8Stateful(const char *s,
4938 Py_ssize_t size,
4939 const char *errors,
4940 Py_ssize_t *consumed)
4941{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004942 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004943 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004944 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004945
4946 Py_ssize_t startinpos;
4947 Py_ssize_t endinpos;
4948 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004949 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004950 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004951 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004952
4953 if (size == 0) {
4954 if (consumed)
4955 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004956 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004957 }
4958
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004959 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4960 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004961 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004962 *consumed = 1;
4963 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004964 }
4965
Victor Stinner8f674cc2013-04-17 23:02:17 +02004966 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004967 writer.min_length = size;
4968 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004969 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004970
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004971 writer.pos = ascii_decode(s, end, writer.data);
4972 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004973 while (s < end) {
4974 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004975 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004976
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004977 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004978 if (PyUnicode_IS_ASCII(writer.buffer))
4979 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004980 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004981 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004982 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004983 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004984 } else {
4985 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004986 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004987 }
4988
4989 switch (ch) {
4990 case 0:
4991 if (s == end || consumed)
4992 goto End;
4993 errmsg = "unexpected end of data";
4994 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004995 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004996 break;
4997 case 1:
4998 errmsg = "invalid start byte";
4999 startinpos = s - starts;
5000 endinpos = startinpos + 1;
5001 break;
5002 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005003 case 3:
5004 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005005 errmsg = "invalid continuation byte";
5006 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005007 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005008 break;
5009 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005010 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005011 goto onError;
5012 continue;
5013 }
5014
Victor Stinner1d65d912015-10-05 13:43:50 +02005015 if (error_handler == _Py_ERROR_UNKNOWN)
5016 error_handler = get_error_handler(errors);
5017
5018 switch (error_handler) {
5019 case _Py_ERROR_IGNORE:
5020 s += (endinpos - startinpos);
5021 break;
5022
5023 case _Py_ERROR_REPLACE:
5024 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5025 goto onError;
5026 s += (endinpos - startinpos);
5027 break;
5028
5029 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005030 {
5031 Py_ssize_t i;
5032
Victor Stinner1d65d912015-10-05 13:43:50 +02005033 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5034 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005035 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005036 ch = (Py_UCS4)(unsigned char)(starts[i]);
5037 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5038 ch + 0xdc00);
5039 writer.pos++;
5040 }
5041 s += (endinpos - startinpos);
5042 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005043 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005044
5045 default:
5046 if (unicode_decode_call_errorhandler_writer(
5047 errors, &error_handler_obj,
5048 "utf-8", errmsg,
5049 &starts, &end, &startinpos, &endinpos, &exc, &s,
5050 &writer))
5051 goto onError;
5052 }
Victor Stinner785938e2011-12-11 20:09:03 +01005053 }
5054
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005055End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005056 if (consumed)
5057 *consumed = s - starts;
5058
Victor Stinner1d65d912015-10-05 13:43:50 +02005059 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005060 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005061 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005062
5063onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005064 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005065 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005066 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005067 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005068}
5069
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005070#ifdef __APPLE__
5071
5072/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005073 used to decode the command line arguments on Mac OS X.
5074
5075 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005076 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005077
5078wchar_t*
5079_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5080{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005081 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005082 wchar_t *unicode;
5083 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005084
5085 /* Note: size will always be longer than the resulting Unicode
5086 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005087 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005088 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005089 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005090 if (!unicode)
5091 return NULL;
5092
5093 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005094 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005095 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005096 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005097 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005098#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005099 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005100#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005101 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005102#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005103 if (ch > 0xFF) {
5104#if SIZEOF_WCHAR_T == 4
5105 assert(0);
5106#else
5107 assert(Py_UNICODE_IS_SURROGATE(ch));
5108 /* compute and append the two surrogates: */
5109 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5110 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5111#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005112 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005113 else {
5114 if (!ch && s == e)
5115 break;
5116 /* surrogateescape */
5117 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5118 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005119 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005120 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005121 return unicode;
5122}
5123
5124#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005126/* Primary internal function which creates utf8 encoded bytes objects.
5127
5128 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005129 and allocate exactly as much space needed at the end. Else allocate the
5130 maximum possible needed (4 result bytes per Unicode character), and return
5131 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005132*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005133PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005134_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005135{
Victor Stinner6099a032011-12-18 14:22:26 +01005136 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005137 void *data;
5138 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005140 if (!PyUnicode_Check(unicode)) {
5141 PyErr_BadArgument();
5142 return NULL;
5143 }
5144
5145 if (PyUnicode_READY(unicode) == -1)
5146 return NULL;
5147
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005148 if (PyUnicode_UTF8(unicode))
5149 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5150 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005151
5152 kind = PyUnicode_KIND(unicode);
5153 data = PyUnicode_DATA(unicode);
5154 size = PyUnicode_GET_LENGTH(unicode);
5155
Benjamin Petersonead6b532011-12-20 17:23:42 -06005156 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005157 default:
5158 assert(0);
5159 case PyUnicode_1BYTE_KIND:
5160 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5161 assert(!PyUnicode_IS_ASCII(unicode));
5162 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5163 case PyUnicode_2BYTE_KIND:
5164 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5165 case PyUnicode_4BYTE_KIND:
5166 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005167 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005168}
5169
Alexander Belopolsky40018472011-02-26 01:02:56 +00005170PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005171PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5172 Py_ssize_t size,
5173 const char *errors)
5174{
5175 PyObject *v, *unicode;
5176
5177 unicode = PyUnicode_FromUnicode(s, size);
5178 if (unicode == NULL)
5179 return NULL;
5180 v = _PyUnicode_AsUTF8String(unicode, errors);
5181 Py_DECREF(unicode);
5182 return v;
5183}
5184
5185PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005186PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005187{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005188 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005189}
5190
Walter Dörwald41980ca2007-08-16 21:55:45 +00005191/* --- UTF-32 Codec ------------------------------------------------------- */
5192
5193PyObject *
5194PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005195 Py_ssize_t size,
5196 const char *errors,
5197 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005198{
5199 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5200}
5201
5202PyObject *
5203PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005204 Py_ssize_t size,
5205 const char *errors,
5206 int *byteorder,
5207 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005208{
5209 const char *starts = s;
5210 Py_ssize_t startinpos;
5211 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005212 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005213 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005214 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005215 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005216 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005217 PyObject *errorHandler = NULL;
5218 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005219
Walter Dörwald41980ca2007-08-16 21:55:45 +00005220 q = (unsigned char *)s;
5221 e = q + size;
5222
5223 if (byteorder)
5224 bo = *byteorder;
5225
5226 /* Check for BOM marks (U+FEFF) in the input and adjust current
5227 byte order setting accordingly. In native mode, the leading BOM
5228 mark is skipped, in all other modes, it is copied to the output
5229 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005230 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005231 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005232 if (bom == 0x0000FEFF) {
5233 bo = -1;
5234 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005235 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005236 else if (bom == 0xFFFE0000) {
5237 bo = 1;
5238 q += 4;
5239 }
5240 if (byteorder)
5241 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005242 }
5243
Victor Stinnere64322e2012-10-30 23:12:47 +01005244 if (q == e) {
5245 if (consumed)
5246 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005247 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005248 }
5249
Victor Stinnere64322e2012-10-30 23:12:47 +01005250#ifdef WORDS_BIGENDIAN
5251 le = bo < 0;
5252#else
5253 le = bo <= 0;
5254#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005255 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005256
Victor Stinner8f674cc2013-04-17 23:02:17 +02005257 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005258 writer.min_length = (e - q + 3) / 4;
5259 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005260 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005261
Victor Stinnere64322e2012-10-30 23:12:47 +01005262 while (1) {
5263 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005264 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005265
Victor Stinnere64322e2012-10-30 23:12:47 +01005266 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005267 enum PyUnicode_Kind kind = writer.kind;
5268 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005269 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005270 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005271 if (le) {
5272 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005273 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005274 if (ch > maxch)
5275 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005276 if (kind != PyUnicode_1BYTE_KIND &&
5277 Py_UNICODE_IS_SURROGATE(ch))
5278 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005279 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005280 q += 4;
5281 } while (q <= last);
5282 }
5283 else {
5284 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005285 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005286 if (ch > maxch)
5287 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005288 if (kind != PyUnicode_1BYTE_KIND &&
5289 Py_UNICODE_IS_SURROGATE(ch))
5290 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005291 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005292 q += 4;
5293 } while (q <= last);
5294 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005295 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005296 }
5297
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005298 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005299 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005300 startinpos = ((const char *)q) - starts;
5301 endinpos = startinpos + 4;
5302 }
5303 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005304 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005305 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005306 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005307 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005308 startinpos = ((const char *)q) - starts;
5309 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005310 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005311 else {
5312 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005313 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005314 goto onError;
5315 q += 4;
5316 continue;
5317 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005318 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005319 startinpos = ((const char *)q) - starts;
5320 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005321 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005322
5323 /* The remaining input chars are ignored if the callback
5324 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005325 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005326 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005327 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005328 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005329 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005330 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005331 }
5332
Walter Dörwald41980ca2007-08-16 21:55:45 +00005333 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005334 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005335
Walter Dörwald41980ca2007-08-16 21:55:45 +00005336 Py_XDECREF(errorHandler);
5337 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005338 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005339
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005341 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005342 Py_XDECREF(errorHandler);
5343 Py_XDECREF(exc);
5344 return NULL;
5345}
5346
5347PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005348_PyUnicode_EncodeUTF32(PyObject *str,
5349 const char *errors,
5350 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005351{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005352 enum PyUnicode_Kind kind;
5353 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005354 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005355 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005356 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005357#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005358 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005359#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005360 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005361#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005362 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005363 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005364 PyObject *errorHandler = NULL;
5365 PyObject *exc = NULL;
5366 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005367
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005368 if (!PyUnicode_Check(str)) {
5369 PyErr_BadArgument();
5370 return NULL;
5371 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005372 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005373 return NULL;
5374 kind = PyUnicode_KIND(str);
5375 data = PyUnicode_DATA(str);
5376 len = PyUnicode_GET_LENGTH(str);
5377
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005378 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005379 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005380 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005381 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005382 if (v == NULL)
5383 return NULL;
5384
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005385 /* output buffer is 4-bytes aligned */
5386 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005387 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005388 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005389 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005390 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005391 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005392
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005393 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005394 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005395 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005396 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005397 else
5398 encoding = "utf-32";
5399
5400 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005401 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5402 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005403 }
5404
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005405 pos = 0;
5406 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005407 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005408
5409 if (kind == PyUnicode_2BYTE_KIND) {
5410 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5411 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005412 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005413 else {
5414 assert(kind == PyUnicode_4BYTE_KIND);
5415 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5416 &out, native_ordering);
5417 }
5418 if (pos == len)
5419 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005420
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005421 rep = unicode_encode_call_errorhandler(
5422 errors, &errorHandler,
5423 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005424 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005425 if (!rep)
5426 goto error;
5427
5428 if (PyBytes_Check(rep)) {
5429 repsize = PyBytes_GET_SIZE(rep);
5430 if (repsize & 3) {
5431 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005432 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005433 "surrogates not allowed");
5434 goto error;
5435 }
5436 moreunits = repsize / 4;
5437 }
5438 else {
5439 assert(PyUnicode_Check(rep));
5440 if (PyUnicode_READY(rep) < 0)
5441 goto error;
5442 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5443 if (!PyUnicode_IS_ASCII(rep)) {
5444 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005445 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005446 "surrogates not allowed");
5447 goto error;
5448 }
5449 }
5450
5451 /* four bytes are reserved for each surrogate */
5452 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005453 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005454 Py_ssize_t morebytes = 4 * (moreunits - 1);
5455 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5456 /* integer overflow */
5457 PyErr_NoMemory();
5458 goto error;
5459 }
5460 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5461 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005462 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005463 }
5464
5465 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005466 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005467 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005468 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005470 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5471 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005472 }
5473
5474 Py_CLEAR(rep);
5475 }
5476
5477 /* Cut back to size actually needed. This is necessary for, for example,
5478 encoding of a string containing isolated surrogates and the 'ignore'
5479 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005480 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005481 if (nsize != PyBytes_GET_SIZE(v))
5482 _PyBytes_Resize(&v, nsize);
5483 Py_XDECREF(errorHandler);
5484 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005485 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005486 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005487 error:
5488 Py_XDECREF(rep);
5489 Py_XDECREF(errorHandler);
5490 Py_XDECREF(exc);
5491 Py_XDECREF(v);
5492 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005493}
5494
Alexander Belopolsky40018472011-02-26 01:02:56 +00005495PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005496PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5497 Py_ssize_t size,
5498 const char *errors,
5499 int byteorder)
5500{
5501 PyObject *result;
5502 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5503 if (tmp == NULL)
5504 return NULL;
5505 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5506 Py_DECREF(tmp);
5507 return result;
5508}
5509
5510PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005511PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005512{
Victor Stinnerb960b342011-11-20 19:12:52 +01005513 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005514}
5515
Guido van Rossumd57fd912000-03-10 22:53:23 +00005516/* --- UTF-16 Codec ------------------------------------------------------- */
5517
Tim Peters772747b2001-08-09 22:21:55 +00005518PyObject *
5519PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005520 Py_ssize_t size,
5521 const char *errors,
5522 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005523{
Walter Dörwald69652032004-09-07 20:24:22 +00005524 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5525}
5526
5527PyObject *
5528PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005529 Py_ssize_t size,
5530 const char *errors,
5531 int *byteorder,
5532 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005533{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005534 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005535 Py_ssize_t startinpos;
5536 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005537 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005538 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005539 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005540 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005541 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005542 PyObject *errorHandler = NULL;
5543 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005544 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545
Tim Peters772747b2001-08-09 22:21:55 +00005546 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005547 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005548
5549 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005550 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005551
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005552 /* Check for BOM marks (U+FEFF) in the input and adjust current
5553 byte order setting accordingly. In native mode, the leading BOM
5554 mark is skipped, in all other modes, it is copied to the output
5555 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005556 if (bo == 0 && size >= 2) {
5557 const Py_UCS4 bom = (q[1] << 8) | q[0];
5558 if (bom == 0xFEFF) {
5559 q += 2;
5560 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005561 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005562 else if (bom == 0xFFFE) {
5563 q += 2;
5564 bo = 1;
5565 }
5566 if (byteorder)
5567 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005568 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005569
Antoine Pitrou63065d72012-05-15 23:48:04 +02005570 if (q == e) {
5571 if (consumed)
5572 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005573 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005574 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005575
Christian Heimes743e0cd2012-10-17 23:52:17 +02005576#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005577 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005578 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005579#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005580 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005581 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005582#endif
Tim Peters772747b2001-08-09 22:21:55 +00005583
Antoine Pitrou63065d72012-05-15 23:48:04 +02005584 /* Note: size will always be longer than the resulting Unicode
5585 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005586 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005587 writer.min_length = (e - q + 1) / 2;
5588 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005589 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005590
Antoine Pitrou63065d72012-05-15 23:48:04 +02005591 while (1) {
5592 Py_UCS4 ch = 0;
5593 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005594 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005595 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005596 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005597 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005598 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005599 native_ordering);
5600 else
5601 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005602 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005603 native_ordering);
5604 } else if (kind == PyUnicode_2BYTE_KIND) {
5605 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005606 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005607 native_ordering);
5608 } else {
5609 assert(kind == PyUnicode_4BYTE_KIND);
5610 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005611 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005612 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005613 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005614 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005615
Antoine Pitrou63065d72012-05-15 23:48:04 +02005616 switch (ch)
5617 {
5618 case 0:
5619 /* remaining byte at the end? (size should be even) */
5620 if (q == e || consumed)
5621 goto End;
5622 errmsg = "truncated data";
5623 startinpos = ((const char *)q) - starts;
5624 endinpos = ((const char *)e) - starts;
5625 break;
5626 /* The remaining input chars are ignored if the callback
5627 chooses to skip the input */
5628 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005629 q -= 2;
5630 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005631 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005632 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005633 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005634 endinpos = ((const char *)e) - starts;
5635 break;
5636 case 2:
5637 errmsg = "illegal encoding";
5638 startinpos = ((const char *)q) - 2 - starts;
5639 endinpos = startinpos + 2;
5640 break;
5641 case 3:
5642 errmsg = "illegal UTF-16 surrogate";
5643 startinpos = ((const char *)q) - 4 - starts;
5644 endinpos = startinpos + 2;
5645 break;
5646 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005647 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005648 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005649 continue;
5650 }
5651
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005652 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005653 errors,
5654 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005655 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005656 &starts,
5657 (const char **)&e,
5658 &startinpos,
5659 &endinpos,
5660 &exc,
5661 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005662 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005663 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005664 }
5665
Antoine Pitrou63065d72012-05-15 23:48:04 +02005666End:
Walter Dörwald69652032004-09-07 20:24:22 +00005667 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005668 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005669
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005670 Py_XDECREF(errorHandler);
5671 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005672 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673
Benjamin Peterson29060642009-01-31 22:14:21 +00005674 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005675 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005676 Py_XDECREF(errorHandler);
5677 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005678 return NULL;
5679}
5680
Tim Peters772747b2001-08-09 22:21:55 +00005681PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005682_PyUnicode_EncodeUTF16(PyObject *str,
5683 const char *errors,
5684 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005685{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005686 enum PyUnicode_Kind kind;
5687 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005688 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005689 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005690 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005691 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005692#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005693 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005694#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005695 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005696#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005697 const char *encoding;
5698 Py_ssize_t nsize, pos;
5699 PyObject *errorHandler = NULL;
5700 PyObject *exc = NULL;
5701 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005702
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005703 if (!PyUnicode_Check(str)) {
5704 PyErr_BadArgument();
5705 return NULL;
5706 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005707 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005708 return NULL;
5709 kind = PyUnicode_KIND(str);
5710 data = PyUnicode_DATA(str);
5711 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005712
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005713 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005714 if (kind == PyUnicode_4BYTE_KIND) {
5715 const Py_UCS4 *in = (const Py_UCS4 *)data;
5716 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005717 while (in < end) {
5718 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005719 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005720 }
5721 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005722 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005723 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005724 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005725 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005726 nsize = len + pairs + (byteorder == 0);
5727 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005728 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005730 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005732 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005733 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005734 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005735 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005736 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005737 }
5738 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005739 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005740 }
Tim Peters772747b2001-08-09 22:21:55 +00005741
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005742 if (kind == PyUnicode_1BYTE_KIND) {
5743 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5744 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005745 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005746
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005747 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005748 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005749 }
5750 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005751 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005752 }
5753 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005754 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005755 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005756
5757 pos = 0;
5758 while (pos < len) {
5759 Py_ssize_t repsize, moreunits;
5760
5761 if (kind == PyUnicode_2BYTE_KIND) {
5762 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5763 &out, native_ordering);
5764 }
5765 else {
5766 assert(kind == PyUnicode_4BYTE_KIND);
5767 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5768 &out, native_ordering);
5769 }
5770 if (pos == len)
5771 break;
5772
5773 rep = unicode_encode_call_errorhandler(
5774 errors, &errorHandler,
5775 encoding, "surrogates not allowed",
5776 str, &exc, pos, pos + 1, &pos);
5777 if (!rep)
5778 goto error;
5779
5780 if (PyBytes_Check(rep)) {
5781 repsize = PyBytes_GET_SIZE(rep);
5782 if (repsize & 1) {
5783 raise_encode_exception(&exc, encoding,
5784 str, pos - 1, pos,
5785 "surrogates not allowed");
5786 goto error;
5787 }
5788 moreunits = repsize / 2;
5789 }
5790 else {
5791 assert(PyUnicode_Check(rep));
5792 if (PyUnicode_READY(rep) < 0)
5793 goto error;
5794 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5795 if (!PyUnicode_IS_ASCII(rep)) {
5796 raise_encode_exception(&exc, encoding,
5797 str, pos - 1, pos,
5798 "surrogates not allowed");
5799 goto error;
5800 }
5801 }
5802
5803 /* two bytes are reserved for each surrogate */
5804 if (moreunits > 1) {
5805 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5806 Py_ssize_t morebytes = 2 * (moreunits - 1);
5807 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5808 /* integer overflow */
5809 PyErr_NoMemory();
5810 goto error;
5811 }
5812 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5813 goto error;
5814 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5815 }
5816
5817 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005818 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005819 out += moreunits;
5820 } else /* rep is unicode */ {
5821 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5822 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5823 &out, native_ordering);
5824 }
5825
5826 Py_CLEAR(rep);
5827 }
5828
5829 /* Cut back to size actually needed. This is necessary for, for example,
5830 encoding of a string containing isolated surrogates and the 'ignore' handler
5831 is used. */
5832 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5833 if (nsize != PyBytes_GET_SIZE(v))
5834 _PyBytes_Resize(&v, nsize);
5835 Py_XDECREF(errorHandler);
5836 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005837 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005838 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005839 error:
5840 Py_XDECREF(rep);
5841 Py_XDECREF(errorHandler);
5842 Py_XDECREF(exc);
5843 Py_XDECREF(v);
5844 return NULL;
5845#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005846}
5847
Alexander Belopolsky40018472011-02-26 01:02:56 +00005848PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005849PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5850 Py_ssize_t size,
5851 const char *errors,
5852 int byteorder)
5853{
5854 PyObject *result;
5855 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5856 if (tmp == NULL)
5857 return NULL;
5858 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5859 Py_DECREF(tmp);
5860 return result;
5861}
5862
5863PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005864PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005865{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005866 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005867}
5868
5869/* --- Unicode Escape Codec ----------------------------------------------- */
5870
Fredrik Lundh06d12682001-01-24 07:59:11 +00005871static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005872
Alexander Belopolsky40018472011-02-26 01:02:56 +00005873PyObject *
5874PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005875 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005876 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005878 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005879 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005881 PyObject *errorHandler = NULL;
5882 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005883
Victor Stinner62ec3312016-09-06 17:04:34 -07005884 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005885 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005886 }
5887 /* Escaped strings will always be longer than the resulting
5888 Unicode string, so we start with size here and then reduce the
5889 length after conversion to the true value.
5890 (but if the error callback returns a long replacement string
5891 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005892 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005893 writer.min_length = size;
5894 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5895 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005896 }
5897
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898 end = s + size;
5899 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005900 unsigned char c = (unsigned char) *s++;
5901 Py_UCS4 ch;
5902 int count;
5903 Py_ssize_t startinpos;
5904 Py_ssize_t endinpos;
5905 const char *message;
5906
5907#define WRITE_ASCII_CHAR(ch) \
5908 do { \
5909 assert(ch <= 127); \
5910 assert(writer.pos < writer.size); \
5911 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5912 } while(0)
5913
5914#define WRITE_CHAR(ch) \
5915 do { \
5916 if (ch <= writer.maxchar) { \
5917 assert(writer.pos < writer.size); \
5918 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5919 } \
5920 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5921 goto onError; \
5922 } \
5923 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924
5925 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005926 if (c != '\\') {
5927 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928 continue;
5929 }
5930
Victor Stinner62ec3312016-09-06 17:04:34 -07005931 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005933 if (s >= end) {
5934 message = "\\ at end of string";
5935 goto error;
5936 }
5937 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005938
Victor Stinner62ec3312016-09-06 17:04:34 -07005939 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005940 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941
Benjamin Peterson29060642009-01-31 22:14:21 +00005942 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005943 case '\n': continue;
5944 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5945 case '\'': WRITE_ASCII_CHAR('\''); continue;
5946 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5947 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005948 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005949 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5950 case 't': WRITE_ASCII_CHAR('\t'); continue;
5951 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5952 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005953 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005954 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005955 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005956 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005957
Benjamin Peterson29060642009-01-31 22:14:21 +00005958 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005959 case '0': case '1': case '2': case '3':
5960 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005961 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005962 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005963 ch = (ch<<3) + *s++ - '0';
5964 if (s < end && '0' <= *s && *s <= '7') {
5965 ch = (ch<<3) + *s++ - '0';
5966 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005968 WRITE_CHAR(ch);
5969 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970
Benjamin Peterson29060642009-01-31 22:14:21 +00005971 /* hex escapes */
5972 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005974 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005975 message = "truncated \\xXX escape";
5976 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977
Benjamin Peterson29060642009-01-31 22:14:21 +00005978 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005980 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005981 message = "truncated \\uXXXX escape";
5982 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983
Benjamin Peterson29060642009-01-31 22:14:21 +00005984 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005985 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005986 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005987 message = "truncated \\UXXXXXXXX escape";
5988 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07005989 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02005990 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07005991 ch <<= 4;
5992 if (c >= '0' && c <= '9') {
5993 ch += c - '0';
5994 }
5995 else if (c >= 'a' && c <= 'f') {
5996 ch += c - ('a' - 10);
5997 }
5998 else if (c >= 'A' && c <= 'F') {
5999 ch += c - ('A' - 10);
6000 }
6001 else {
6002 break;
6003 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006004 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006005 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006006 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006007 }
6008
6009 /* when we get here, ch is a 32-bit unicode character */
6010 if (ch > MAX_UNICODE) {
6011 message = "illegal Unicode character";
6012 goto error;
6013 }
6014
6015 WRITE_CHAR(ch);
6016 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006017
Benjamin Peterson29060642009-01-31 22:14:21 +00006018 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006019 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006020 if (ucnhash_CAPI == NULL) {
6021 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006022 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6023 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006024 if (ucnhash_CAPI == NULL) {
6025 PyErr_SetString(
6026 PyExc_UnicodeError,
6027 "\\N escapes not supported (can't load unicodedata module)"
6028 );
6029 goto onError;
6030 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006031 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006032
6033 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006034 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006035 const char *start = ++s;
6036 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006037 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006038 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006039 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006040 namelen = s - start;
6041 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006042 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006043 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006044 ch = 0xffffffff; /* in case 'getcode' messes up */
6045 if (namelen <= INT_MAX &&
6046 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6047 &ch, 0)) {
6048 assert(ch <= MAX_UNICODE);
6049 WRITE_CHAR(ch);
6050 continue;
6051 }
6052 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006053 }
6054 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006055 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006056
6057 default:
R David Murray110b6fe2016-09-08 15:34:08 -04006058 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6059 "invalid escape sequence '\\%c'", c) < 0)
6060 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006061 WRITE_ASCII_CHAR('\\');
6062 WRITE_CHAR(c);
6063 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006065
6066 error:
6067 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006068 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006069 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006070 errors, &errorHandler,
6071 "unicodeescape", message,
6072 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006073 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006074 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006075 }
6076 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6077 goto onError;
6078 }
6079
6080#undef WRITE_ASCII_CHAR
6081#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006083
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006084 Py_XDECREF(errorHandler);
6085 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006086 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006087
Benjamin Peterson29060642009-01-31 22:14:21 +00006088 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006089 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006090 Py_XDECREF(errorHandler);
6091 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006092 return NULL;
6093}
6094
6095/* Return a Unicode-Escape string version of the Unicode object.
6096
6097 If quotes is true, the string is enclosed in u"" or u'' quotes as
6098 appropriate.
6099
6100*/
6101
Alexander Belopolsky40018472011-02-26 01:02:56 +00006102PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006103PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006104{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006105 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006106 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006107 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006108 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006109 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006110 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006111
Ezio Melottie7f90372012-10-05 03:33:31 +03006112 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006113 escape.
6114
Ezio Melottie7f90372012-10-05 03:33:31 +03006115 For UCS1 strings it's '\xxx', 4 bytes per source character.
6116 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6117 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006118 */
6119
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006120 if (!PyUnicode_Check(unicode)) {
6121 PyErr_BadArgument();
6122 return NULL;
6123 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006124 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006125 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006126 }
Victor Stinner358af132015-10-12 22:36:57 +02006127
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006128 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006129 if (len == 0) {
6130 return PyBytes_FromStringAndSize(NULL, 0);
6131 }
6132
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006133 kind = PyUnicode_KIND(unicode);
6134 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006135 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6136 bytes, and 1 byte characters 4. */
6137 expandsize = kind * 2 + 2;
6138 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize) {
6139 return PyErr_NoMemory();
6140 }
6141 repr = PyBytes_FromStringAndSize(NULL, 2 + expandsize * len + 1);
6142 if (repr == NULL) {
6143 return NULL;
6144 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006145
Victor Stinner62ec3312016-09-06 17:04:34 -07006146 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006147 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006148 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006149
Victor Stinner62ec3312016-09-06 17:04:34 -07006150 /* U+0000-U+00ff range */
6151 if (ch < 0x100) {
6152 if (ch >= ' ' && ch < 127) {
6153 if (ch != '\\') {
6154 /* Copy printable US ASCII as-is */
6155 *p++ = (char) ch;
6156 }
6157 /* Escape backslashes */
6158 else {
6159 *p++ = '\\';
6160 *p++ = '\\';
6161 }
6162 }
Victor Stinner358af132015-10-12 22:36:57 +02006163
Victor Stinner62ec3312016-09-06 17:04:34 -07006164 /* Map special whitespace to '\t', \n', '\r' */
6165 else if (ch == '\t') {
6166 *p++ = '\\';
6167 *p++ = 't';
6168 }
6169 else if (ch == '\n') {
6170 *p++ = '\\';
6171 *p++ = 'n';
6172 }
6173 else if (ch == '\r') {
6174 *p++ = '\\';
6175 *p++ = 'r';
6176 }
6177
6178 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6179 else {
6180 *p++ = '\\';
6181 *p++ = 'x';
6182 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6183 *p++ = Py_hexdigits[ch & 0x000F];
6184 }
Tim Petersced69f82003-09-16 20:30:58 +00006185 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006186 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6187 else if (ch < 0x10000) {
6188 /* U+0100-U+ffff */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006189 *p++ = '\\';
6190 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006191 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6192 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6193 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6194 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006196 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6197 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006198
Victor Stinner62ec3312016-09-06 17:04:34 -07006199 /* Make sure that the first two digits are zero */
6200 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006201 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006202 *p++ = 'U';
6203 *p++ = '0';
6204 *p++ = '0';
6205 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6206 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6207 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6208 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6209 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6210 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006211 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006212 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006213
Victor Stinner62ec3312016-09-06 17:04:34 -07006214 assert(p - PyBytes_AS_STRING(repr) > 0);
6215 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6216 return NULL;
6217 }
6218 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006219}
6220
Alexander Belopolsky40018472011-02-26 01:02:56 +00006221PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006222PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6223 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006224{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006225 PyObject *result;
6226 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006227 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006229 }
6230
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006231 result = PyUnicode_AsUnicodeEscapeString(tmp);
6232 Py_DECREF(tmp);
6233 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234}
6235
6236/* --- Raw Unicode Escape Codec ------------------------------------------- */
6237
Alexander Belopolsky40018472011-02-26 01:02:56 +00006238PyObject *
6239PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006240 Py_ssize_t size,
6241 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006242{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006243 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006244 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006245 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006246 PyObject *errorHandler = NULL;
6247 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006248
Victor Stinner62ec3312016-09-06 17:04:34 -07006249 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006250 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006251 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006252
Guido van Rossumd57fd912000-03-10 22:53:23 +00006253 /* Escaped strings will always be longer than the resulting
6254 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006255 length after conversion to the true value. (But decoding error
6256 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006257 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006258 writer.min_length = size;
6259 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6260 goto onError;
6261 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006262
Guido van Rossumd57fd912000-03-10 22:53:23 +00006263 end = s + size;
6264 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006265 unsigned char c = (unsigned char) *s++;
6266 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006267 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006268 Py_ssize_t startinpos;
6269 Py_ssize_t endinpos;
6270 const char *message;
6271
6272#define WRITE_CHAR(ch) \
6273 do { \
6274 if (ch <= writer.maxchar) { \
6275 assert(writer.pos < writer.size); \
6276 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6277 } \
6278 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6279 goto onError; \
6280 } \
6281 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006282
Benjamin Peterson29060642009-01-31 22:14:21 +00006283 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006284 if (c != '\\' || s >= end) {
6285 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006286 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006287 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006288
Victor Stinner62ec3312016-09-06 17:04:34 -07006289 c = (unsigned char) *s++;
6290 if (c == 'u') {
6291 count = 4;
6292 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006293 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006294 else if (c == 'U') {
6295 count = 8;
6296 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006297 }
6298 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006299 assert(writer.pos < writer.size);
6300 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6301 WRITE_CHAR(c);
6302 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006303 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006304 startinpos = s - starts - 2;
6305
6306 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6307 for (ch = 0; count && s < end; ++s, --count) {
6308 c = (unsigned char)*s;
6309 ch <<= 4;
6310 if (c >= '0' && c <= '9') {
6311 ch += c - '0';
6312 }
6313 else if (c >= 'a' && c <= 'f') {
6314 ch += c - ('a' - 10);
6315 }
6316 else if (c >= 'A' && c <= 'F') {
6317 ch += c - ('A' - 10);
6318 }
6319 else {
6320 break;
6321 }
6322 }
6323 if (!count) {
6324 if (ch <= MAX_UNICODE) {
6325 WRITE_CHAR(ch);
6326 continue;
6327 }
6328 message = "\\Uxxxxxxxx out of range";
6329 }
6330
6331 endinpos = s-starts;
6332 writer.min_length = end - s + writer.pos;
6333 if (unicode_decode_call_errorhandler_writer(
6334 errors, &errorHandler,
6335 "rawunicodeescape", message,
6336 &starts, &end, &startinpos, &endinpos, &exc, &s,
6337 &writer)) {
6338 goto onError;
6339 }
6340 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6341 goto onError;
6342 }
6343
6344#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006346 Py_XDECREF(errorHandler);
6347 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006348 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006349
Benjamin Peterson29060642009-01-31 22:14:21 +00006350 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006351 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006352 Py_XDECREF(errorHandler);
6353 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006354 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006355
Guido van Rossumd57fd912000-03-10 22:53:23 +00006356}
6357
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006358
Alexander Belopolsky40018472011-02-26 01:02:56 +00006359PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006360PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006361{
Victor Stinner62ec3312016-09-06 17:04:34 -07006362 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006363 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006364 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006365 int kind;
6366 void *data;
6367 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006368
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006369 if (!PyUnicode_Check(unicode)) {
6370 PyErr_BadArgument();
6371 return NULL;
6372 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006373 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006374 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006375 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006376 kind = PyUnicode_KIND(unicode);
6377 data = PyUnicode_DATA(unicode);
6378 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006379 if (kind == PyUnicode_1BYTE_KIND) {
6380 return PyBytes_FromStringAndSize(data, len);
6381 }
Victor Stinner0e368262011-11-10 20:12:49 +01006382
Victor Stinner62ec3312016-09-06 17:04:34 -07006383 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6384 bytes, and 1 byte characters 4. */
6385 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006386
Victor Stinner62ec3312016-09-06 17:04:34 -07006387 if (len > PY_SSIZE_T_MAX / expandsize) {
6388 return PyErr_NoMemory();
6389 }
6390 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6391 if (repr == NULL) {
6392 return NULL;
6393 }
6394 if (len == 0) {
6395 return repr;
6396 }
6397
6398 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006399 for (pos = 0; pos < len; pos++) {
6400 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006401
Victor Stinner62ec3312016-09-06 17:04:34 -07006402 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6403 if (ch < 0x100) {
6404 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006405 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006406 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6407 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006408 *p++ = '\\';
6409 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006410 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6411 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6412 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6413 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006414 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006415 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6416 else {
6417 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6418 *p++ = '\\';
6419 *p++ = 'U';
6420 *p++ = '0';
6421 *p++ = '0';
6422 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6423 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6424 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6425 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6426 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6427 *p++ = Py_hexdigits[ch & 15];
6428 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006429 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006430
Victor Stinner62ec3312016-09-06 17:04:34 -07006431 assert(p > PyBytes_AS_STRING(repr));
6432 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6433 return NULL;
6434 }
6435 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006436}
6437
Alexander Belopolsky40018472011-02-26 01:02:56 +00006438PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006439PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6440 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006441{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006442 PyObject *result;
6443 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6444 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006445 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006446 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6447 Py_DECREF(tmp);
6448 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006449}
6450
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006451/* --- Unicode Internal Codec ------------------------------------------- */
6452
Alexander Belopolsky40018472011-02-26 01:02:56 +00006453PyObject *
6454_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006455 Py_ssize_t size,
6456 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006457{
6458 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006459 Py_ssize_t startinpos;
6460 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006461 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006462 const char *end;
6463 const char *reason;
6464 PyObject *errorHandler = NULL;
6465 PyObject *exc = NULL;
6466
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006467 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006468 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006469 1))
6470 return NULL;
6471
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006472 if (size == 0)
6473 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006474
Victor Stinner8f674cc2013-04-17 23:02:17 +02006475 _PyUnicodeWriter_Init(&writer);
6476 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6477 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006479 }
6480 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006481
Victor Stinner8f674cc2013-04-17 23:02:17 +02006482 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006483 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006484 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006485 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006486 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006487 endinpos = end-starts;
6488 reason = "truncated input";
6489 goto error;
6490 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006491 /* We copy the raw representation one byte at a time because the
6492 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006493 ((char *) &uch)[0] = s[0];
6494 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006495#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006496 ((char *) &uch)[2] = s[2];
6497 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006498#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006499 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006500#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006501 /* We have to sanity check the raw data, otherwise doom looms for
6502 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006503 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006504 endinpos = s - starts + Py_UNICODE_SIZE;
6505 reason = "illegal code point (> 0x10FFFF)";
6506 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006507 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006508#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006509 s += Py_UNICODE_SIZE;
6510#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006511 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006512 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006513 Py_UNICODE uch2;
6514 ((char *) &uch2)[0] = s[0];
6515 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006516 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006517 {
Victor Stinner551ac952011-11-29 22:58:13 +01006518 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006519 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006520 }
6521 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006522#endif
6523
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006524 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006525 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006526 continue;
6527
6528 error:
6529 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006530 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006531 errors, &errorHandler,
6532 "unicode_internal", reason,
6533 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006534 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006535 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006536 }
6537
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006538 Py_XDECREF(errorHandler);
6539 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006540 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006541
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006543 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006544 Py_XDECREF(errorHandler);
6545 Py_XDECREF(exc);
6546 return NULL;
6547}
6548
Guido van Rossumd57fd912000-03-10 22:53:23 +00006549/* --- Latin-1 Codec ------------------------------------------------------ */
6550
Alexander Belopolsky40018472011-02-26 01:02:56 +00006551PyObject *
6552PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006553 Py_ssize_t size,
6554 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006555{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006556 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006557 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006558}
6559
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006560/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006561static void
6562make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006563 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006564 PyObject *unicode,
6565 Py_ssize_t startpos, Py_ssize_t endpos,
6566 const char *reason)
6567{
6568 if (*exceptionObject == NULL) {
6569 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006570 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006571 encoding, unicode, startpos, endpos, reason);
6572 }
6573 else {
6574 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6575 goto onError;
6576 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6577 goto onError;
6578 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6579 goto onError;
6580 return;
6581 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006582 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006583 }
6584}
6585
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006586/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006587static void
6588raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006589 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006590 PyObject *unicode,
6591 Py_ssize_t startpos, Py_ssize_t endpos,
6592 const char *reason)
6593{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006594 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006595 encoding, unicode, startpos, endpos, reason);
6596 if (*exceptionObject != NULL)
6597 PyCodec_StrictErrors(*exceptionObject);
6598}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006599
6600/* error handling callback helper:
6601 build arguments, call the callback and check the arguments,
6602 put the result into newpos and return the replacement string, which
6603 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006604static PyObject *
6605unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006606 PyObject **errorHandler,
6607 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006608 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006609 Py_ssize_t startpos, Py_ssize_t endpos,
6610 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006611{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006612 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006613 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006614 PyObject *restuple;
6615 PyObject *resunicode;
6616
6617 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006618 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006619 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006620 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006621 }
6622
Benjamin Petersonbac79492012-01-14 13:34:47 -05006623 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006624 return NULL;
6625 len = PyUnicode_GET_LENGTH(unicode);
6626
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006627 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006628 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006629 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006630 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006631
6632 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006633 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006634 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006635 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006637 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006638 Py_DECREF(restuple);
6639 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006640 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006641 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006642 &resunicode, newpos)) {
6643 Py_DECREF(restuple);
6644 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006645 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006646 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6647 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6648 Py_DECREF(restuple);
6649 return NULL;
6650 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006651 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006652 *newpos = len + *newpos;
6653 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006654 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006655 Py_DECREF(restuple);
6656 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006657 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006658 Py_INCREF(resunicode);
6659 Py_DECREF(restuple);
6660 return resunicode;
6661}
6662
Alexander Belopolsky40018472011-02-26 01:02:56 +00006663static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006664unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006665 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006666 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006667{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006668 /* input state */
6669 Py_ssize_t pos=0, size;
6670 int kind;
6671 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006672 /* pointer into the output */
6673 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006674 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6675 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006676 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006677 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006678 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006679 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006680 /* output object */
6681 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682
Benjamin Petersonbac79492012-01-14 13:34:47 -05006683 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006684 return NULL;
6685 size = PyUnicode_GET_LENGTH(unicode);
6686 kind = PyUnicode_KIND(unicode);
6687 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006688 /* allocate enough for a simple encoding without
6689 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006690 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006691 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006692
6693 _PyBytesWriter_Init(&writer);
6694 str = _PyBytesWriter_Alloc(&writer, size);
6695 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006696 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006698 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006699 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006700
Benjamin Peterson29060642009-01-31 22:14:21 +00006701 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006702 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006703 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006704 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006705 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006706 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006707 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006708 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006709 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006710 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006711 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006712 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006713
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006714 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006716
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006717 /* Only overallocate the buffer if it's not the last write */
6718 writer.overallocate = (collend < size);
6719
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006721 if (error_handler == _Py_ERROR_UNKNOWN)
6722 error_handler = get_error_handler(errors);
6723
6724 switch (error_handler) {
6725 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006726 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006728
6729 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006730 memset(str, '?', collend - collstart);
6731 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006732 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006733 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006734 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 break;
Victor Stinner50149202015-09-22 00:26:54 +02006736
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006737 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006738 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006739 writer.min_size -= (collend - collstart);
6740 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006741 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006742 if (str == NULL)
6743 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006744 pos = collend;
6745 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006746
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006747 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006748 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006749 writer.min_size -= (collend - collstart);
6750 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006751 unicode, collstart, collend);
6752 if (str == NULL)
6753 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006754 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 break;
Victor Stinner50149202015-09-22 00:26:54 +02006756
Victor Stinnerc3713e92015-09-29 12:32:13 +02006757 case _Py_ERROR_SURROGATEESCAPE:
6758 for (i = collstart; i < collend; ++i) {
6759 ch = PyUnicode_READ(kind, data, i);
6760 if (ch < 0xdc80 || 0xdcff < ch) {
6761 /* Not a UTF-8b surrogate */
6762 break;
6763 }
6764 *str++ = (char)(ch - 0xdc00);
6765 ++pos;
6766 }
6767 if (i >= collend)
6768 break;
6769 collstart = pos;
6770 assert(collstart != collend);
6771 /* fallback to general error handling */
6772
Benjamin Peterson29060642009-01-31 22:14:21 +00006773 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006774 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6775 encoding, reason, unicode, &exc,
6776 collstart, collend, &newpos);
6777 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006778 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006779
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006780 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006781 writer.min_size -= 1;
6782
Victor Stinner6bd525b2015-10-09 13:10:05 +02006783 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006784 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006785 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006786 PyBytes_AS_STRING(rep),
6787 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006788 if (str == NULL)
6789 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006790 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006791 else {
6792 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006793
Victor Stinner6bd525b2015-10-09 13:10:05 +02006794 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006795 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006796
6797 if (PyUnicode_IS_ASCII(rep)) {
6798 /* Fast path: all characters are smaller than limit */
6799 assert(limit >= 128);
6800 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6801 str = _PyBytesWriter_WriteBytes(&writer, str,
6802 PyUnicode_DATA(rep),
6803 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006804 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006805 else {
6806 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6807
6808 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6809 if (str == NULL)
6810 goto onError;
6811
6812 /* check if there is anything unencodable in the
6813 replacement and copy it to the output */
6814 for (i = 0; repsize-->0; ++i, ++str) {
6815 ch = PyUnicode_READ_CHAR(rep, i);
6816 if (ch >= limit) {
6817 raise_encode_exception(&exc, encoding, unicode,
6818 pos, pos+1, reason);
6819 goto onError;
6820 }
6821 *str = (char)ch;
6822 }
6823 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006824 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006825 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006826 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006827 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006828
6829 /* If overallocation was disabled, ensure that it was the last
6830 write. Otherwise, we missed an optimization */
6831 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006832 }
6833 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006834
Victor Stinner50149202015-09-22 00:26:54 +02006835 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006836 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006837 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006838
6839 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006840 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006841 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006842 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006843 Py_XDECREF(exc);
6844 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006845}
6846
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006847/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006848PyObject *
6849PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006850 Py_ssize_t size,
6851 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006852{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006853 PyObject *result;
6854 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6855 if (unicode == NULL)
6856 return NULL;
6857 result = unicode_encode_ucs1(unicode, errors, 256);
6858 Py_DECREF(unicode);
6859 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006860}
6861
Alexander Belopolsky40018472011-02-26 01:02:56 +00006862PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006863_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006864{
6865 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006866 PyErr_BadArgument();
6867 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006868 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006869 if (PyUnicode_READY(unicode) == -1)
6870 return NULL;
6871 /* Fast path: if it is a one-byte string, construct
6872 bytes object directly. */
6873 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6874 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6875 PyUnicode_GET_LENGTH(unicode));
6876 /* Non-Latin-1 characters present. Defer to above function to
6877 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006878 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006879}
6880
6881PyObject*
6882PyUnicode_AsLatin1String(PyObject *unicode)
6883{
6884 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006885}
6886
6887/* --- 7-bit ASCII Codec -------------------------------------------------- */
6888
Alexander Belopolsky40018472011-02-26 01:02:56 +00006889PyObject *
6890PyUnicode_DecodeASCII(const char *s,
6891 Py_ssize_t size,
6892 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006893{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006894 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006895 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006896 int kind;
6897 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006898 Py_ssize_t startinpos;
6899 Py_ssize_t endinpos;
6900 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006901 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006902 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006903 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006904 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006905
Guido van Rossumd57fd912000-03-10 22:53:23 +00006906 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006907 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006908
Guido van Rossumd57fd912000-03-10 22:53:23 +00006909 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006910 if (size == 1 && (unsigned char)s[0] < 128)
6911 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006912
Victor Stinner8f674cc2013-04-17 23:02:17 +02006913 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006914 writer.min_length = size;
6915 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006916 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006917
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006918 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006919 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006920 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006921 writer.pos = outpos;
6922 if (writer.pos == size)
6923 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006924
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006925 s += writer.pos;
6926 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006927 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006928 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006929 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006930 PyUnicode_WRITE(kind, data, writer.pos, c);
6931 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006932 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006933 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006934 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006935
6936 /* byte outsize range 0x00..0x7f: call the error handler */
6937
6938 if (error_handler == _Py_ERROR_UNKNOWN)
6939 error_handler = get_error_handler(errors);
6940
6941 switch (error_handler)
6942 {
6943 case _Py_ERROR_REPLACE:
6944 case _Py_ERROR_SURROGATEESCAPE:
6945 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006946 but we may switch to UCS2 at the first write */
6947 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6948 goto onError;
6949 kind = writer.kind;
6950 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006951
6952 if (error_handler == _Py_ERROR_REPLACE)
6953 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6954 else
6955 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6956 writer.pos++;
6957 ++s;
6958 break;
6959
6960 case _Py_ERROR_IGNORE:
6961 ++s;
6962 break;
6963
6964 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006965 startinpos = s-starts;
6966 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006967 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006968 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006969 "ascii", "ordinal not in range(128)",
6970 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006971 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006972 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006973 kind = writer.kind;
6974 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006975 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006976 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006977 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006978 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006979 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006980
Benjamin Peterson29060642009-01-31 22:14:21 +00006981 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006982 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006983 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006984 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006985 return NULL;
6986}
6987
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006988/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006989PyObject *
6990PyUnicode_EncodeASCII(const Py_UNICODE *p,
6991 Py_ssize_t size,
6992 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006993{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006994 PyObject *result;
6995 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6996 if (unicode == NULL)
6997 return NULL;
6998 result = unicode_encode_ucs1(unicode, errors, 128);
6999 Py_DECREF(unicode);
7000 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007001}
7002
Alexander Belopolsky40018472011-02-26 01:02:56 +00007003PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007004_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007005{
7006 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007007 PyErr_BadArgument();
7008 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007009 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007010 if (PyUnicode_READY(unicode) == -1)
7011 return NULL;
7012 /* Fast path: if it is an ASCII-only string, construct bytes object
7013 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007014 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007015 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7016 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007017 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007018}
7019
7020PyObject *
7021PyUnicode_AsASCIIString(PyObject *unicode)
7022{
7023 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007024}
7025
Steve Dowercc16be82016-09-08 10:35:16 -07007026#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007027
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007028/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007029
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007030#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007031#define NEED_RETRY
7032#endif
7033
Victor Stinner3a50e702011-10-18 21:21:00 +02007034#ifndef WC_ERR_INVALID_CHARS
7035# define WC_ERR_INVALID_CHARS 0x0080
7036#endif
7037
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007038static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007039code_page_name(UINT code_page, PyObject **obj)
7040{
7041 *obj = NULL;
7042 if (code_page == CP_ACP)
7043 return "mbcs";
7044 if (code_page == CP_UTF7)
7045 return "CP_UTF7";
7046 if (code_page == CP_UTF8)
7047 return "CP_UTF8";
7048
7049 *obj = PyBytes_FromFormat("cp%u", code_page);
7050 if (*obj == NULL)
7051 return NULL;
7052 return PyBytes_AS_STRING(*obj);
7053}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007054
Victor Stinner3a50e702011-10-18 21:21:00 +02007055static DWORD
7056decode_code_page_flags(UINT code_page)
7057{
7058 if (code_page == CP_UTF7) {
7059 /* The CP_UTF7 decoder only supports flags=0 */
7060 return 0;
7061 }
7062 else
7063 return MB_ERR_INVALID_CHARS;
7064}
7065
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007066/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007067 * Decode a byte string from a Windows code page into unicode object in strict
7068 * mode.
7069 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007070 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7071 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007072 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007073static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007074decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007075 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 const char *in,
7077 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007078{
Victor Stinner3a50e702011-10-18 21:21:00 +02007079 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007080 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007081 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007082
7083 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007084 assert(insize > 0);
7085 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7086 if (outsize <= 0)
7087 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007088
7089 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007090 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007091 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007092 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007093 if (*v == NULL)
7094 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007096 }
7097 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007098 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007100 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007101 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007102 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007103 }
7104
7105 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007106 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7107 if (outsize <= 0)
7108 goto error;
7109 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007110
Victor Stinner3a50e702011-10-18 21:21:00 +02007111error:
7112 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7113 return -2;
7114 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007115 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007116}
7117
Victor Stinner3a50e702011-10-18 21:21:00 +02007118/*
7119 * Decode a byte string from a code page into unicode object with an error
7120 * handler.
7121 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007122 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007123 * UnicodeDecodeError exception and returns -1 on error.
7124 */
7125static int
7126decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007127 PyObject **v,
7128 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007129 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007130{
7131 const char *startin = in;
7132 const char *endin = in + size;
7133 const DWORD flags = decode_code_page_flags(code_page);
7134 /* Ideally, we should get reason from FormatMessage. This is the Windows
7135 2000 English version of the message. */
7136 const char *reason = "No mapping for the Unicode character exists "
7137 "in the target code page.";
7138 /* each step cannot decode more than 1 character, but a character can be
7139 represented as a surrogate pair */
7140 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007141 int insize;
7142 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007143 PyObject *errorHandler = NULL;
7144 PyObject *exc = NULL;
7145 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007146 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007147 DWORD err;
7148 int ret = -1;
7149
7150 assert(size > 0);
7151
7152 encoding = code_page_name(code_page, &encoding_obj);
7153 if (encoding == NULL)
7154 return -1;
7155
Victor Stinner7d00cc12014-03-17 23:08:06 +01007156 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007157 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7158 UnicodeDecodeError. */
7159 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7160 if (exc != NULL) {
7161 PyCodec_StrictErrors(exc);
7162 Py_CLEAR(exc);
7163 }
7164 goto error;
7165 }
7166
7167 if (*v == NULL) {
7168 /* Create unicode object */
7169 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7170 PyErr_NoMemory();
7171 goto error;
7172 }
Victor Stinnerab595942011-12-17 04:59:06 +01007173 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007174 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007175 if (*v == NULL)
7176 goto error;
7177 startout = PyUnicode_AS_UNICODE(*v);
7178 }
7179 else {
7180 /* Extend unicode object */
7181 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7182 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7183 PyErr_NoMemory();
7184 goto error;
7185 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007186 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007187 goto error;
7188 startout = PyUnicode_AS_UNICODE(*v) + n;
7189 }
7190
7191 /* Decode the byte string character per character */
7192 out = startout;
7193 while (in < endin)
7194 {
7195 /* Decode a character */
7196 insize = 1;
7197 do
7198 {
7199 outsize = MultiByteToWideChar(code_page, flags,
7200 in, insize,
7201 buffer, Py_ARRAY_LENGTH(buffer));
7202 if (outsize > 0)
7203 break;
7204 err = GetLastError();
7205 if (err != ERROR_NO_UNICODE_TRANSLATION
7206 && err != ERROR_INSUFFICIENT_BUFFER)
7207 {
7208 PyErr_SetFromWindowsErr(0);
7209 goto error;
7210 }
7211 insize++;
7212 }
7213 /* 4=maximum length of a UTF-8 sequence */
7214 while (insize <= 4 && (in + insize) <= endin);
7215
7216 if (outsize <= 0) {
7217 Py_ssize_t startinpos, endinpos, outpos;
7218
Victor Stinner7d00cc12014-03-17 23:08:06 +01007219 /* last character in partial decode? */
7220 if (in + insize >= endin && !final)
7221 break;
7222
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 startinpos = in - startin;
7224 endinpos = startinpos + 1;
7225 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007226 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 errors, &errorHandler,
7228 encoding, reason,
7229 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007230 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 {
7232 goto error;
7233 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007234 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007235 }
7236 else {
7237 in += insize;
7238 memcpy(out, buffer, outsize * sizeof(wchar_t));
7239 out += outsize;
7240 }
7241 }
7242
7243 /* write a NUL character at the end */
7244 *out = 0;
7245
7246 /* Extend unicode object */
7247 outsize = out - startout;
7248 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007249 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007251 /* (in - startin) <= size and size is an int */
7252 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007253
7254error:
7255 Py_XDECREF(encoding_obj);
7256 Py_XDECREF(errorHandler);
7257 Py_XDECREF(exc);
7258 return ret;
7259}
7260
Victor Stinner3a50e702011-10-18 21:21:00 +02007261static PyObject *
7262decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007263 const char *s, Py_ssize_t size,
7264 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007265{
Victor Stinner76a31a62011-11-04 00:05:13 +01007266 PyObject *v = NULL;
7267 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007268
Victor Stinner3a50e702011-10-18 21:21:00 +02007269 if (code_page < 0) {
7270 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7271 return NULL;
7272 }
7273
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007274 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007275 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007276
Victor Stinner76a31a62011-11-04 00:05:13 +01007277 do
7278 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007279#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007280 if (size > INT_MAX) {
7281 chunk_size = INT_MAX;
7282 final = 0;
7283 done = 0;
7284 }
7285 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007286#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007287 {
7288 chunk_size = (int)size;
7289 final = (consumed == NULL);
7290 done = 1;
7291 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007292
Victor Stinner76a31a62011-11-04 00:05:13 +01007293 if (chunk_size == 0 && done) {
7294 if (v != NULL)
7295 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007296 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007297 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007298
Victor Stinner76a31a62011-11-04 00:05:13 +01007299 converted = decode_code_page_strict(code_page, &v,
7300 s, chunk_size);
7301 if (converted == -2)
7302 converted = decode_code_page_errors(code_page, &v,
7303 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007304 errors, final);
7305 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007306
7307 if (converted < 0) {
7308 Py_XDECREF(v);
7309 return NULL;
7310 }
7311
7312 if (consumed)
7313 *consumed += converted;
7314
7315 s += converted;
7316 size -= converted;
7317 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007318
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007319 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007320}
7321
Alexander Belopolsky40018472011-02-26 01:02:56 +00007322PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007323PyUnicode_DecodeCodePageStateful(int code_page,
7324 const char *s,
7325 Py_ssize_t size,
7326 const char *errors,
7327 Py_ssize_t *consumed)
7328{
7329 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7330}
7331
7332PyObject *
7333PyUnicode_DecodeMBCSStateful(const char *s,
7334 Py_ssize_t size,
7335 const char *errors,
7336 Py_ssize_t *consumed)
7337{
7338 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7339}
7340
7341PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007342PyUnicode_DecodeMBCS(const char *s,
7343 Py_ssize_t size,
7344 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007345{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007346 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7347}
7348
Victor Stinner3a50e702011-10-18 21:21:00 +02007349static DWORD
7350encode_code_page_flags(UINT code_page, const char *errors)
7351{
7352 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007353 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007354 }
7355 else if (code_page == CP_UTF7) {
7356 /* CP_UTF7 only supports flags=0 */
7357 return 0;
7358 }
7359 else {
7360 if (errors != NULL && strcmp(errors, "replace") == 0)
7361 return 0;
7362 else
7363 return WC_NO_BEST_FIT_CHARS;
7364 }
7365}
7366
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007367/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007368 * Encode a Unicode string to a Windows code page into a byte string in strict
7369 * mode.
7370 *
7371 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007372 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007373 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007374static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007375encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007376 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007377 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007378{
Victor Stinner554f3f02010-06-16 23:33:54 +00007379 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007380 BOOL *pusedDefaultChar = &usedDefaultChar;
7381 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007382 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007383 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007384 const DWORD flags = encode_code_page_flags(code_page, NULL);
7385 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007386 /* Create a substring so that we can get the UTF-16 representation
7387 of just the slice under consideration. */
7388 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007389
Martin v. Löwis3d325192011-11-04 18:23:06 +01007390 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007391
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007393 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007395 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007396
Victor Stinner2fc507f2011-11-04 20:06:39 +01007397 substring = PyUnicode_Substring(unicode, offset, offset+len);
7398 if (substring == NULL)
7399 return -1;
7400 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7401 if (p == NULL) {
7402 Py_DECREF(substring);
7403 return -1;
7404 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007405 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007406
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007407 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007408 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007409 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007410 NULL, 0,
7411 NULL, pusedDefaultChar);
7412 if (outsize <= 0)
7413 goto error;
7414 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007415 if (pusedDefaultChar && *pusedDefaultChar) {
7416 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007417 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007418 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007419
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007421 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007422 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007423 if (*outbytes == NULL) {
7424 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007425 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007426 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007427 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007428 }
7429 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007430 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007431 const Py_ssize_t n = PyBytes_Size(*outbytes);
7432 if (outsize > PY_SSIZE_T_MAX - n) {
7433 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007434 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007435 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007436 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007437 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7438 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007439 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007440 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007441 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007442 }
7443
7444 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007446 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007447 out, outsize,
7448 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007449 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007450 if (outsize <= 0)
7451 goto error;
7452 if (pusedDefaultChar && *pusedDefaultChar)
7453 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007454 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007455
Victor Stinner3a50e702011-10-18 21:21:00 +02007456error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007457 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7459 return -2;
7460 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007461 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007462}
7463
Victor Stinner3a50e702011-10-18 21:21:00 +02007464/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007465 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007466 * error handler.
7467 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007468 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007469 * -1 on other error.
7470 */
7471static int
7472encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007473 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007474 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007475{
Victor Stinner3a50e702011-10-18 21:21:00 +02007476 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007477 Py_ssize_t pos = unicode_offset;
7478 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007479 /* Ideally, we should get reason from FormatMessage. This is the Windows
7480 2000 English version of the message. */
7481 const char *reason = "invalid character";
7482 /* 4=maximum length of a UTF-8 sequence */
7483 char buffer[4];
7484 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7485 Py_ssize_t outsize;
7486 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007487 PyObject *errorHandler = NULL;
7488 PyObject *exc = NULL;
7489 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007490 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007491 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 PyObject *rep;
7493 int ret = -1;
7494
7495 assert(insize > 0);
7496
7497 encoding = code_page_name(code_page, &encoding_obj);
7498 if (encoding == NULL)
7499 return -1;
7500
7501 if (errors == NULL || strcmp(errors, "strict") == 0) {
7502 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7503 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007504 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 if (exc != NULL) {
7506 PyCodec_StrictErrors(exc);
7507 Py_DECREF(exc);
7508 }
7509 Py_XDECREF(encoding_obj);
7510 return -1;
7511 }
7512
7513 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7514 pusedDefaultChar = &usedDefaultChar;
7515 else
7516 pusedDefaultChar = NULL;
7517
7518 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7519 PyErr_NoMemory();
7520 goto error;
7521 }
7522 outsize = insize * Py_ARRAY_LENGTH(buffer);
7523
7524 if (*outbytes == NULL) {
7525 /* Create string object */
7526 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7527 if (*outbytes == NULL)
7528 goto error;
7529 out = PyBytes_AS_STRING(*outbytes);
7530 }
7531 else {
7532 /* Extend string object */
7533 Py_ssize_t n = PyBytes_Size(*outbytes);
7534 if (n > PY_SSIZE_T_MAX - outsize) {
7535 PyErr_NoMemory();
7536 goto error;
7537 }
7538 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7539 goto error;
7540 out = PyBytes_AS_STRING(*outbytes) + n;
7541 }
7542
7543 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007544 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007545 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007546 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7547 wchar_t chars[2];
7548 int charsize;
7549 if (ch < 0x10000) {
7550 chars[0] = (wchar_t)ch;
7551 charsize = 1;
7552 }
7553 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007554 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7555 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007556 charsize = 2;
7557 }
7558
Victor Stinner3a50e702011-10-18 21:21:00 +02007559 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007560 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007561 buffer, Py_ARRAY_LENGTH(buffer),
7562 NULL, pusedDefaultChar);
7563 if (outsize > 0) {
7564 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7565 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007566 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007567 memcpy(out, buffer, outsize);
7568 out += outsize;
7569 continue;
7570 }
7571 }
7572 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7573 PyErr_SetFromWindowsErr(0);
7574 goto error;
7575 }
7576
Victor Stinner3a50e702011-10-18 21:21:00 +02007577 rep = unicode_encode_call_errorhandler(
7578 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007579 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007580 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007581 if (rep == NULL)
7582 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007583 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007584
7585 if (PyBytes_Check(rep)) {
7586 outsize = PyBytes_GET_SIZE(rep);
7587 if (outsize != 1) {
7588 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7589 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7590 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7591 Py_DECREF(rep);
7592 goto error;
7593 }
7594 out = PyBytes_AS_STRING(*outbytes) + offset;
7595 }
7596 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7597 out += outsize;
7598 }
7599 else {
7600 Py_ssize_t i;
7601 enum PyUnicode_Kind kind;
7602 void *data;
7603
Benjamin Petersonbac79492012-01-14 13:34:47 -05007604 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007605 Py_DECREF(rep);
7606 goto error;
7607 }
7608
7609 outsize = PyUnicode_GET_LENGTH(rep);
7610 if (outsize != 1) {
7611 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7612 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7613 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7614 Py_DECREF(rep);
7615 goto error;
7616 }
7617 out = PyBytes_AS_STRING(*outbytes) + offset;
7618 }
7619 kind = PyUnicode_KIND(rep);
7620 data = PyUnicode_DATA(rep);
7621 for (i=0; i < outsize; i++) {
7622 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7623 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007624 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007625 encoding, unicode,
7626 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007627 "unable to encode error handler result to ASCII");
7628 Py_DECREF(rep);
7629 goto error;
7630 }
7631 *out = (unsigned char)ch;
7632 out++;
7633 }
7634 }
7635 Py_DECREF(rep);
7636 }
7637 /* write a NUL byte */
7638 *out = 0;
7639 outsize = out - PyBytes_AS_STRING(*outbytes);
7640 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7641 if (_PyBytes_Resize(outbytes, outsize) < 0)
7642 goto error;
7643 ret = 0;
7644
7645error:
7646 Py_XDECREF(encoding_obj);
7647 Py_XDECREF(errorHandler);
7648 Py_XDECREF(exc);
7649 return ret;
7650}
7651
Victor Stinner3a50e702011-10-18 21:21:00 +02007652static PyObject *
7653encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007654 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007655 const char *errors)
7656{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007657 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007658 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007659 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007660 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007661
Victor Stinner29dacf22015-01-26 16:41:32 +01007662 if (!PyUnicode_Check(unicode)) {
7663 PyErr_BadArgument();
7664 return NULL;
7665 }
7666
Benjamin Petersonbac79492012-01-14 13:34:47 -05007667 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007668 return NULL;
7669 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007670
Victor Stinner3a50e702011-10-18 21:21:00 +02007671 if (code_page < 0) {
7672 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7673 return NULL;
7674 }
7675
Martin v. Löwis3d325192011-11-04 18:23:06 +01007676 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007677 return PyBytes_FromStringAndSize(NULL, 0);
7678
Victor Stinner7581cef2011-11-03 22:32:33 +01007679 offset = 0;
7680 do
7681 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007682#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007683 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007684 chunks. */
7685 if (len > INT_MAX/2) {
7686 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007687 done = 0;
7688 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007689 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007690#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007691 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007692 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007693 done = 1;
7694 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007695
Victor Stinner76a31a62011-11-04 00:05:13 +01007696 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007697 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007698 errors);
7699 if (ret == -2)
7700 ret = encode_code_page_errors(code_page, &outbytes,
7701 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007702 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007703 if (ret < 0) {
7704 Py_XDECREF(outbytes);
7705 return NULL;
7706 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007707
Victor Stinner7581cef2011-11-03 22:32:33 +01007708 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007709 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007710 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007711
Victor Stinner3a50e702011-10-18 21:21:00 +02007712 return outbytes;
7713}
7714
7715PyObject *
7716PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7717 Py_ssize_t size,
7718 const char *errors)
7719{
Victor Stinner7581cef2011-11-03 22:32:33 +01007720 PyObject *unicode, *res;
7721 unicode = PyUnicode_FromUnicode(p, size);
7722 if (unicode == NULL)
7723 return NULL;
7724 res = encode_code_page(CP_ACP, unicode, errors);
7725 Py_DECREF(unicode);
7726 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007727}
7728
7729PyObject *
7730PyUnicode_EncodeCodePage(int code_page,
7731 PyObject *unicode,
7732 const char *errors)
7733{
Victor Stinner7581cef2011-11-03 22:32:33 +01007734 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007735}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007736
Alexander Belopolsky40018472011-02-26 01:02:56 +00007737PyObject *
7738PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007739{
Victor Stinner7581cef2011-11-03 22:32:33 +01007740 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007741}
7742
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007743#undef NEED_RETRY
7744
Steve Dowercc16be82016-09-08 10:35:16 -07007745#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007746
Guido van Rossumd57fd912000-03-10 22:53:23 +00007747/* --- Character Mapping Codec -------------------------------------------- */
7748
Victor Stinnerfb161b12013-04-18 01:44:27 +02007749static int
7750charmap_decode_string(const char *s,
7751 Py_ssize_t size,
7752 PyObject *mapping,
7753 const char *errors,
7754 _PyUnicodeWriter *writer)
7755{
7756 const char *starts = s;
7757 const char *e;
7758 Py_ssize_t startinpos, endinpos;
7759 PyObject *errorHandler = NULL, *exc = NULL;
7760 Py_ssize_t maplen;
7761 enum PyUnicode_Kind mapkind;
7762 void *mapdata;
7763 Py_UCS4 x;
7764 unsigned char ch;
7765
7766 if (PyUnicode_READY(mapping) == -1)
7767 return -1;
7768
7769 maplen = PyUnicode_GET_LENGTH(mapping);
7770 mapdata = PyUnicode_DATA(mapping);
7771 mapkind = PyUnicode_KIND(mapping);
7772
7773 e = s + size;
7774
7775 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7776 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7777 * is disabled in encoding aliases, latin1 is preferred because
7778 * its implementation is faster. */
7779 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7780 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7781 Py_UCS4 maxchar = writer->maxchar;
7782
7783 assert (writer->kind == PyUnicode_1BYTE_KIND);
7784 while (s < e) {
7785 ch = *s;
7786 x = mapdata_ucs1[ch];
7787 if (x > maxchar) {
7788 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7789 goto onError;
7790 maxchar = writer->maxchar;
7791 outdata = (Py_UCS1 *)writer->data;
7792 }
7793 outdata[writer->pos] = x;
7794 writer->pos++;
7795 ++s;
7796 }
7797 return 0;
7798 }
7799
7800 while (s < e) {
7801 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7802 enum PyUnicode_Kind outkind = writer->kind;
7803 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7804 if (outkind == PyUnicode_1BYTE_KIND) {
7805 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7806 Py_UCS4 maxchar = writer->maxchar;
7807 while (s < e) {
7808 ch = *s;
7809 x = mapdata_ucs2[ch];
7810 if (x > maxchar)
7811 goto Error;
7812 outdata[writer->pos] = x;
7813 writer->pos++;
7814 ++s;
7815 }
7816 break;
7817 }
7818 else if (outkind == PyUnicode_2BYTE_KIND) {
7819 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7820 while (s < e) {
7821 ch = *s;
7822 x = mapdata_ucs2[ch];
7823 if (x == 0xFFFE)
7824 goto Error;
7825 outdata[writer->pos] = x;
7826 writer->pos++;
7827 ++s;
7828 }
7829 break;
7830 }
7831 }
7832 ch = *s;
7833
7834 if (ch < maplen)
7835 x = PyUnicode_READ(mapkind, mapdata, ch);
7836 else
7837 x = 0xfffe; /* invalid value */
7838Error:
7839 if (x == 0xfffe)
7840 {
7841 /* undefined mapping */
7842 startinpos = s-starts;
7843 endinpos = startinpos+1;
7844 if (unicode_decode_call_errorhandler_writer(
7845 errors, &errorHandler,
7846 "charmap", "character maps to <undefined>",
7847 &starts, &e, &startinpos, &endinpos, &exc, &s,
7848 writer)) {
7849 goto onError;
7850 }
7851 continue;
7852 }
7853
7854 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7855 goto onError;
7856 ++s;
7857 }
7858 Py_XDECREF(errorHandler);
7859 Py_XDECREF(exc);
7860 return 0;
7861
7862onError:
7863 Py_XDECREF(errorHandler);
7864 Py_XDECREF(exc);
7865 return -1;
7866}
7867
7868static int
7869charmap_decode_mapping(const char *s,
7870 Py_ssize_t size,
7871 PyObject *mapping,
7872 const char *errors,
7873 _PyUnicodeWriter *writer)
7874{
7875 const char *starts = s;
7876 const char *e;
7877 Py_ssize_t startinpos, endinpos;
7878 PyObject *errorHandler = NULL, *exc = NULL;
7879 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007880 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007881
7882 e = s + size;
7883
7884 while (s < e) {
7885 ch = *s;
7886
7887 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7888 key = PyLong_FromLong((long)ch);
7889 if (key == NULL)
7890 goto onError;
7891
7892 item = PyObject_GetItem(mapping, key);
7893 Py_DECREF(key);
7894 if (item == NULL) {
7895 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7896 /* No mapping found means: mapping is undefined. */
7897 PyErr_Clear();
7898 goto Undefined;
7899 } else
7900 goto onError;
7901 }
7902
7903 /* Apply mapping */
7904 if (item == Py_None)
7905 goto Undefined;
7906 if (PyLong_Check(item)) {
7907 long value = PyLong_AS_LONG(item);
7908 if (value == 0xFFFE)
7909 goto Undefined;
7910 if (value < 0 || value > MAX_UNICODE) {
7911 PyErr_Format(PyExc_TypeError,
7912 "character mapping must be in range(0x%lx)",
7913 (unsigned long)MAX_UNICODE + 1);
7914 goto onError;
7915 }
7916
7917 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7918 goto onError;
7919 }
7920 else if (PyUnicode_Check(item)) {
7921 if (PyUnicode_READY(item) == -1)
7922 goto onError;
7923 if (PyUnicode_GET_LENGTH(item) == 1) {
7924 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7925 if (value == 0xFFFE)
7926 goto Undefined;
7927 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7928 goto onError;
7929 }
7930 else {
7931 writer->overallocate = 1;
7932 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7933 goto onError;
7934 }
7935 }
7936 else {
7937 /* wrong return value */
7938 PyErr_SetString(PyExc_TypeError,
7939 "character mapping must return integer, None or str");
7940 goto onError;
7941 }
7942 Py_CLEAR(item);
7943 ++s;
7944 continue;
7945
7946Undefined:
7947 /* undefined mapping */
7948 Py_CLEAR(item);
7949 startinpos = s-starts;
7950 endinpos = startinpos+1;
7951 if (unicode_decode_call_errorhandler_writer(
7952 errors, &errorHandler,
7953 "charmap", "character maps to <undefined>",
7954 &starts, &e, &startinpos, &endinpos, &exc, &s,
7955 writer)) {
7956 goto onError;
7957 }
7958 }
7959 Py_XDECREF(errorHandler);
7960 Py_XDECREF(exc);
7961 return 0;
7962
7963onError:
7964 Py_XDECREF(item);
7965 Py_XDECREF(errorHandler);
7966 Py_XDECREF(exc);
7967 return -1;
7968}
7969
Alexander Belopolsky40018472011-02-26 01:02:56 +00007970PyObject *
7971PyUnicode_DecodeCharmap(const char *s,
7972 Py_ssize_t size,
7973 PyObject *mapping,
7974 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007975{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007976 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007977
Guido van Rossumd57fd912000-03-10 22:53:23 +00007978 /* Default to Latin-1 */
7979 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007980 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007981
Guido van Rossumd57fd912000-03-10 22:53:23 +00007982 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007983 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007984 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007985 writer.min_length = size;
7986 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007987 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007988
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007989 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007990 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7991 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007992 }
7993 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007994 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7995 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007996 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007997 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007998
Benjamin Peterson29060642009-01-31 22:14:21 +00007999 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008000 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008001 return NULL;
8002}
8003
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008004/* Charmap encoding: the lookup table */
8005
Alexander Belopolsky40018472011-02-26 01:02:56 +00008006struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008007 PyObject_HEAD
8008 unsigned char level1[32];
8009 int count2, count3;
8010 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008011};
8012
8013static PyObject*
8014encoding_map_size(PyObject *obj, PyObject* args)
8015{
8016 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008017 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008018 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008019}
8020
8021static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008022 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008023 PyDoc_STR("Return the size (in bytes) of this object") },
8024 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025};
8026
8027static void
8028encoding_map_dealloc(PyObject* o)
8029{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008030 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008031}
8032
8033static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008034 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008035 "EncodingMap", /*tp_name*/
8036 sizeof(struct encoding_map), /*tp_basicsize*/
8037 0, /*tp_itemsize*/
8038 /* methods */
8039 encoding_map_dealloc, /*tp_dealloc*/
8040 0, /*tp_print*/
8041 0, /*tp_getattr*/
8042 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008043 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 0, /*tp_repr*/
8045 0, /*tp_as_number*/
8046 0, /*tp_as_sequence*/
8047 0, /*tp_as_mapping*/
8048 0, /*tp_hash*/
8049 0, /*tp_call*/
8050 0, /*tp_str*/
8051 0, /*tp_getattro*/
8052 0, /*tp_setattro*/
8053 0, /*tp_as_buffer*/
8054 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8055 0, /*tp_doc*/
8056 0, /*tp_traverse*/
8057 0, /*tp_clear*/
8058 0, /*tp_richcompare*/
8059 0, /*tp_weaklistoffset*/
8060 0, /*tp_iter*/
8061 0, /*tp_iternext*/
8062 encoding_map_methods, /*tp_methods*/
8063 0, /*tp_members*/
8064 0, /*tp_getset*/
8065 0, /*tp_base*/
8066 0, /*tp_dict*/
8067 0, /*tp_descr_get*/
8068 0, /*tp_descr_set*/
8069 0, /*tp_dictoffset*/
8070 0, /*tp_init*/
8071 0, /*tp_alloc*/
8072 0, /*tp_new*/
8073 0, /*tp_free*/
8074 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008075};
8076
8077PyObject*
8078PyUnicode_BuildEncodingMap(PyObject* string)
8079{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008080 PyObject *result;
8081 struct encoding_map *mresult;
8082 int i;
8083 int need_dict = 0;
8084 unsigned char level1[32];
8085 unsigned char level2[512];
8086 unsigned char *mlevel1, *mlevel2, *mlevel3;
8087 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008088 int kind;
8089 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008090 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008091 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008093 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008094 PyErr_BadArgument();
8095 return NULL;
8096 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008097 kind = PyUnicode_KIND(string);
8098 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008099 length = PyUnicode_GET_LENGTH(string);
8100 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008101 memset(level1, 0xFF, sizeof level1);
8102 memset(level2, 0xFF, sizeof level2);
8103
8104 /* If there isn't a one-to-one mapping of NULL to \0,
8105 or if there are non-BMP characters, we need to use
8106 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008107 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008108 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008109 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008110 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008111 ch = PyUnicode_READ(kind, data, i);
8112 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113 need_dict = 1;
8114 break;
8115 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008116 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008117 /* unmapped character */
8118 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008119 l1 = ch >> 11;
8120 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008121 if (level1[l1] == 0xFF)
8122 level1[l1] = count2++;
8123 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008124 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008125 }
8126
8127 if (count2 >= 0xFF || count3 >= 0xFF)
8128 need_dict = 1;
8129
8130 if (need_dict) {
8131 PyObject *result = PyDict_New();
8132 PyObject *key, *value;
8133 if (!result)
8134 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008135 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008136 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008137 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008138 if (!key || !value)
8139 goto failed1;
8140 if (PyDict_SetItem(result, key, value) == -1)
8141 goto failed1;
8142 Py_DECREF(key);
8143 Py_DECREF(value);
8144 }
8145 return result;
8146 failed1:
8147 Py_XDECREF(key);
8148 Py_XDECREF(value);
8149 Py_DECREF(result);
8150 return NULL;
8151 }
8152
8153 /* Create a three-level trie */
8154 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8155 16*count2 + 128*count3 - 1);
8156 if (!result)
8157 return PyErr_NoMemory();
8158 PyObject_Init(result, &EncodingMapType);
8159 mresult = (struct encoding_map*)result;
8160 mresult->count2 = count2;
8161 mresult->count3 = count3;
8162 mlevel1 = mresult->level1;
8163 mlevel2 = mresult->level23;
8164 mlevel3 = mresult->level23 + 16*count2;
8165 memcpy(mlevel1, level1, 32);
8166 memset(mlevel2, 0xFF, 16*count2);
8167 memset(mlevel3, 0, 128*count3);
8168 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008169 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008170 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008171 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8172 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008173 /* unmapped character */
8174 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008175 o1 = ch>>11;
8176 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008177 i2 = 16*mlevel1[o1] + o2;
8178 if (mlevel2[i2] == 0xFF)
8179 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008180 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008181 i3 = 128*mlevel2[i2] + o3;
8182 mlevel3[i3] = i;
8183 }
8184 return result;
8185}
8186
8187static int
Victor Stinner22168992011-11-20 17:09:18 +01008188encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008189{
8190 struct encoding_map *map = (struct encoding_map*)mapping;
8191 int l1 = c>>11;
8192 int l2 = (c>>7) & 0xF;
8193 int l3 = c & 0x7F;
8194 int i;
8195
Victor Stinner22168992011-11-20 17:09:18 +01008196 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008197 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008198 if (c == 0)
8199 return 0;
8200 /* level 1*/
8201 i = map->level1[l1];
8202 if (i == 0xFF) {
8203 return -1;
8204 }
8205 /* level 2*/
8206 i = map->level23[16*i+l2];
8207 if (i == 0xFF) {
8208 return -1;
8209 }
8210 /* level 3 */
8211 i = map->level23[16*map->count2 + 128*i + l3];
8212 if (i == 0) {
8213 return -1;
8214 }
8215 return i;
8216}
8217
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008218/* Lookup the character ch in the mapping. If the character
8219 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008220 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008221static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008222charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008223{
Christian Heimes217cfd12007-12-02 14:31:20 +00008224 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008225 PyObject *x;
8226
8227 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008228 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008229 x = PyObject_GetItem(mapping, w);
8230 Py_DECREF(w);
8231 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8233 /* No mapping found means: mapping is undefined. */
8234 PyErr_Clear();
8235 x = Py_None;
8236 Py_INCREF(x);
8237 return x;
8238 } else
8239 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008240 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008241 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008243 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 long value = PyLong_AS_LONG(x);
8245 if (value < 0 || value > 255) {
8246 PyErr_SetString(PyExc_TypeError,
8247 "character mapping must be in range(256)");
8248 Py_DECREF(x);
8249 return NULL;
8250 }
8251 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008252 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008253 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008255 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008256 /* wrong return value */
8257 PyErr_Format(PyExc_TypeError,
8258 "character mapping must return integer, bytes or None, not %.400s",
8259 x->ob_type->tp_name);
8260 Py_DECREF(x);
8261 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008262 }
8263}
8264
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008265static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008266charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008267{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008268 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8269 /* exponentially overallocate to minimize reallocations */
8270 if (requiredsize < 2*outsize)
8271 requiredsize = 2*outsize;
8272 if (_PyBytes_Resize(outobj, requiredsize))
8273 return -1;
8274 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008275}
8276
Benjamin Peterson14339b62009-01-31 16:36:08 +00008277typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008279} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008280/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008281 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008282 space is available. Return a new reference to the object that
8283 was put in the output buffer, or Py_None, if the mapping was undefined
8284 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008285 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008286static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008287charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008288 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008290 PyObject *rep;
8291 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008292 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293
Christian Heimes90aa7642007-12-19 02:45:37 +00008294 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008295 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008296 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008297 if (res == -1)
8298 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 if (outsize<requiredsize)
8300 if (charmapencode_resize(outobj, outpos, requiredsize))
8301 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008302 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008303 outstart[(*outpos)++] = (char)res;
8304 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008305 }
8306
8307 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008308 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008310 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 Py_DECREF(rep);
8312 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008313 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 if (PyLong_Check(rep)) {
8315 Py_ssize_t requiredsize = *outpos+1;
8316 if (outsize<requiredsize)
8317 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8318 Py_DECREF(rep);
8319 return enc_EXCEPTION;
8320 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008321 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008323 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008324 else {
8325 const char *repchars = PyBytes_AS_STRING(rep);
8326 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8327 Py_ssize_t requiredsize = *outpos+repsize;
8328 if (outsize<requiredsize)
8329 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8330 Py_DECREF(rep);
8331 return enc_EXCEPTION;
8332 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008333 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 memcpy(outstart + *outpos, repchars, repsize);
8335 *outpos += repsize;
8336 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008337 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008338 Py_DECREF(rep);
8339 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008340}
8341
8342/* handle an error in PyUnicode_EncodeCharmap
8343 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008344static int
8345charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008346 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008347 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008348 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008349 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350{
8351 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008352 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008353 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008354 enum PyUnicode_Kind kind;
8355 void *data;
8356 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008358 Py_ssize_t collstartpos = *inpos;
8359 Py_ssize_t collendpos = *inpos+1;
8360 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008361 char *encoding = "charmap";
8362 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008363 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008364 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008365 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008366
Benjamin Petersonbac79492012-01-14 13:34:47 -05008367 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008368 return -1;
8369 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008370 /* find all unencodable characters */
8371 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008372 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008373 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008374 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008375 val = encoding_map_lookup(ch, mapping);
8376 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008377 break;
8378 ++collendpos;
8379 continue;
8380 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008381
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008382 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8383 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 if (rep==NULL)
8385 return -1;
8386 else if (rep!=Py_None) {
8387 Py_DECREF(rep);
8388 break;
8389 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008390 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392 }
8393 /* cache callback name lookup
8394 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008395 if (*error_handler == _Py_ERROR_UNKNOWN)
8396 *error_handler = get_error_handler(errors);
8397
8398 switch (*error_handler) {
8399 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008400 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008401 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008402
8403 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008404 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 x = charmapencode_output('?', mapping, res, respos);
8406 if (x==enc_EXCEPTION) {
8407 return -1;
8408 }
8409 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008410 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 return -1;
8412 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008413 }
8414 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008415 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008416 *inpos = collendpos;
8417 break;
Victor Stinner50149202015-09-22 00:26:54 +02008418
8419 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008420 /* generate replacement (temporarily (mis)uses p) */
8421 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008422 char buffer[2+29+1+1];
8423 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008424 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 for (cp = buffer; *cp; ++cp) {
8426 x = charmapencode_output(*cp, mapping, res, respos);
8427 if (x==enc_EXCEPTION)
8428 return -1;
8429 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008430 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008431 return -1;
8432 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008433 }
8434 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008435 *inpos = collendpos;
8436 break;
Victor Stinner50149202015-09-22 00:26:54 +02008437
Benjamin Peterson14339b62009-01-31 16:36:08 +00008438 default:
Victor Stinner50149202015-09-22 00:26:54 +02008439 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008440 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008442 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008444 if (PyBytes_Check(repunicode)) {
8445 /* Directly copy bytes result to output. */
8446 Py_ssize_t outsize = PyBytes_Size(*res);
8447 Py_ssize_t requiredsize;
8448 repsize = PyBytes_Size(repunicode);
8449 requiredsize = *respos + repsize;
8450 if (requiredsize > outsize)
8451 /* Make room for all additional bytes. */
8452 if (charmapencode_resize(res, respos, requiredsize)) {
8453 Py_DECREF(repunicode);
8454 return -1;
8455 }
8456 memcpy(PyBytes_AsString(*res) + *respos,
8457 PyBytes_AsString(repunicode), repsize);
8458 *respos += repsize;
8459 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008460 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008461 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008462 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008463 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008464 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008465 Py_DECREF(repunicode);
8466 return -1;
8467 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008468 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008469 data = PyUnicode_DATA(repunicode);
8470 kind = PyUnicode_KIND(repunicode);
8471 for (index = 0; index < repsize; index++) {
8472 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8473 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008475 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008476 return -1;
8477 }
8478 else if (x==enc_FAILED) {
8479 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008480 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 return -1;
8482 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008483 }
8484 *inpos = newpos;
8485 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008486 }
8487 return 0;
8488}
8489
Alexander Belopolsky40018472011-02-26 01:02:56 +00008490PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008491_PyUnicode_EncodeCharmap(PyObject *unicode,
8492 PyObject *mapping,
8493 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008494{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008495 /* output object */
8496 PyObject *res = NULL;
8497 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008498 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008499 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008500 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008501 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008502 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008504 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008505 void *data;
8506 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008507
Benjamin Petersonbac79492012-01-14 13:34:47 -05008508 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008509 return NULL;
8510 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008511 data = PyUnicode_DATA(unicode);
8512 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008513
Guido van Rossumd57fd912000-03-10 22:53:23 +00008514 /* Default to Latin-1 */
8515 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008516 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008517
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518 /* allocate enough for a simple encoding without
8519 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008520 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008521 if (res == NULL)
8522 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008523 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008525
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008526 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008527 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008529 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 if (x==enc_EXCEPTION) /* error */
8531 goto onError;
8532 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008533 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008535 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008536 &res, &respos)) {
8537 goto onError;
8538 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008539 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 else
8541 /* done with this character => adjust input position */
8542 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008543 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008544
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008545 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008546 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008547 if (_PyBytes_Resize(&res, respos) < 0)
8548 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008549
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008550 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008551 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008552 return res;
8553
Benjamin Peterson29060642009-01-31 22:14:21 +00008554 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008555 Py_XDECREF(res);
8556 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008557 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008558 return NULL;
8559}
8560
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008561/* Deprecated */
8562PyObject *
8563PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8564 Py_ssize_t size,
8565 PyObject *mapping,
8566 const char *errors)
8567{
8568 PyObject *result;
8569 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8570 if (unicode == NULL)
8571 return NULL;
8572 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8573 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008574 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008575}
8576
Alexander Belopolsky40018472011-02-26 01:02:56 +00008577PyObject *
8578PyUnicode_AsCharmapString(PyObject *unicode,
8579 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008580{
8581 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 PyErr_BadArgument();
8583 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008584 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008585 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008586}
8587
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008589static void
8590make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008591 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008592 Py_ssize_t startpos, Py_ssize_t endpos,
8593 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008594{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008595 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008596 *exceptionObject = _PyUnicodeTranslateError_Create(
8597 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008598 }
8599 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008600 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8601 goto onError;
8602 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8603 goto onError;
8604 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8605 goto onError;
8606 return;
8607 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008608 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008609 }
8610}
8611
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008612/* error handling callback helper:
8613 build arguments, call the callback and check the arguments,
8614 put the result into newpos and return the replacement string, which
8615 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008616static PyObject *
8617unicode_translate_call_errorhandler(const char *errors,
8618 PyObject **errorHandler,
8619 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008620 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008621 Py_ssize_t startpos, Py_ssize_t endpos,
8622 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008623{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008624 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008625
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008626 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627 PyObject *restuple;
8628 PyObject *resunicode;
8629
8630 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008632 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008633 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008634 }
8635
8636 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008637 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640
8641 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008643 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008645 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008646 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008647 Py_DECREF(restuple);
8648 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008650 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008651 &resunicode, &i_newpos)) {
8652 Py_DECREF(restuple);
8653 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008654 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008655 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008656 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008657 else
8658 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008660 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008661 Py_DECREF(restuple);
8662 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008663 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 Py_INCREF(resunicode);
8665 Py_DECREF(restuple);
8666 return resunicode;
8667}
8668
8669/* Lookup the character ch in the mapping and put the result in result,
8670 which must be decrefed by the caller.
8671 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008672static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008673charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008674{
Christian Heimes217cfd12007-12-02 14:31:20 +00008675 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008676 PyObject *x;
8677
8678 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008679 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008680 x = PyObject_GetItem(mapping, w);
8681 Py_DECREF(w);
8682 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008683 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8684 /* No mapping found means: use 1:1 mapping. */
8685 PyErr_Clear();
8686 *result = NULL;
8687 return 0;
8688 } else
8689 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008690 }
8691 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 *result = x;
8693 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008694 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008695 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008696 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008697 if (value < 0 || value > MAX_UNICODE) {
8698 PyErr_Format(PyExc_ValueError,
8699 "character mapping must be in range(0x%x)",
8700 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008701 Py_DECREF(x);
8702 return -1;
8703 }
8704 *result = x;
8705 return 0;
8706 }
8707 else if (PyUnicode_Check(x)) {
8708 *result = x;
8709 return 0;
8710 }
8711 else {
8712 /* wrong return value */
8713 PyErr_SetString(PyExc_TypeError,
8714 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008715 Py_DECREF(x);
8716 return -1;
8717 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008718}
Victor Stinner1194ea02014-04-04 19:37:40 +02008719
8720/* lookup the character, write the result into the writer.
8721 Return 1 if the result was written into the writer, return 0 if the mapping
8722 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008723static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008724charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8725 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008726{
Victor Stinner1194ea02014-04-04 19:37:40 +02008727 PyObject *item;
8728
8729 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008731
8732 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008733 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008734 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008735 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008737 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008738 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008739
8740 if (item == Py_None) {
8741 Py_DECREF(item);
8742 return 0;
8743 }
8744
8745 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008746 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8747 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8748 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008749 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8750 Py_DECREF(item);
8751 return -1;
8752 }
8753 Py_DECREF(item);
8754 return 1;
8755 }
8756
8757 if (!PyUnicode_Check(item)) {
8758 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008759 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008760 }
8761
8762 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8763 Py_DECREF(item);
8764 return -1;
8765 }
8766
8767 Py_DECREF(item);
8768 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008769}
8770
Victor Stinner89a76ab2014-04-05 11:44:04 +02008771static int
8772unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8773 Py_UCS1 *translate)
8774{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008775 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008776 int ret = 0;
8777
Victor Stinner89a76ab2014-04-05 11:44:04 +02008778 if (charmaptranslate_lookup(ch, mapping, &item)) {
8779 return -1;
8780 }
8781
8782 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008783 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008784 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008785 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008786 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008787 /* not found => default to 1:1 mapping */
8788 translate[ch] = ch;
8789 return 1;
8790 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008791 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008792 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008793 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8794 used it */
8795 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008796 /* invalid character or character outside ASCII:
8797 skip the fast translate */
8798 goto exit;
8799 }
8800 translate[ch] = (Py_UCS1)replace;
8801 }
8802 else if (PyUnicode_Check(item)) {
8803 Py_UCS4 replace;
8804
8805 if (PyUnicode_READY(item) == -1) {
8806 Py_DECREF(item);
8807 return -1;
8808 }
8809 if (PyUnicode_GET_LENGTH(item) != 1)
8810 goto exit;
8811
8812 replace = PyUnicode_READ_CHAR(item, 0);
8813 if (replace > 127)
8814 goto exit;
8815 translate[ch] = (Py_UCS1)replace;
8816 }
8817 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008818 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008819 goto exit;
8820 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008821 ret = 1;
8822
Benjamin Peterson1365de72014-04-07 20:15:41 -04008823 exit:
8824 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008825 return ret;
8826}
8827
8828/* Fast path for ascii => ascii translation. Return 1 if the whole string
8829 was translated into writer, return 0 if the input string was partially
8830 translated into writer, raise an exception and return -1 on error. */
8831static int
8832unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008833 _PyUnicodeWriter *writer, int ignore,
8834 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008835{
Victor Stinner872b2912014-04-05 14:27:07 +02008836 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008837 Py_ssize_t len;
8838 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008839 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008840
Victor Stinner89a76ab2014-04-05 11:44:04 +02008841 len = PyUnicode_GET_LENGTH(input);
8842
Victor Stinner872b2912014-04-05 14:27:07 +02008843 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008844
8845 in = PyUnicode_1BYTE_DATA(input);
8846 end = in + len;
8847
8848 assert(PyUnicode_IS_ASCII(writer->buffer));
8849 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8850 out = PyUnicode_1BYTE_DATA(writer->buffer);
8851
Victor Stinner872b2912014-04-05 14:27:07 +02008852 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008853 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008854 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008855 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008856 int translate = unicode_fast_translate_lookup(mapping, ch,
8857 ascii_table);
8858 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008859 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008860 if (translate == 0)
8861 goto exit;
8862 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008863 }
Victor Stinner872b2912014-04-05 14:27:07 +02008864 if (ch2 == 0xfe) {
8865 if (ignore)
8866 continue;
8867 goto exit;
8868 }
8869 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008870 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008871 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008872 }
Victor Stinner872b2912014-04-05 14:27:07 +02008873 res = 1;
8874
8875exit:
8876 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008877 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008878 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008879}
8880
Victor Stinner3222da22015-10-01 22:07:32 +02008881static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008882_PyUnicode_TranslateCharmap(PyObject *input,
8883 PyObject *mapping,
8884 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008885{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008886 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008887 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008888 Py_ssize_t size, i;
8889 int kind;
8890 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008891 _PyUnicodeWriter writer;
8892 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008893 char *reason = "character maps to <undefined>";
8894 PyObject *errorHandler = NULL;
8895 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008896 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008897 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008898
Guido van Rossumd57fd912000-03-10 22:53:23 +00008899 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008900 PyErr_BadArgument();
8901 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008902 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008903
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008904 if (PyUnicode_READY(input) == -1)
8905 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008906 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008907 kind = PyUnicode_KIND(input);
8908 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008909
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008910 if (size == 0)
8911 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008912
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008913 /* allocate enough for a simple 1:1 translation without
8914 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008915 _PyUnicodeWriter_Init(&writer);
8916 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008917 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008918
Victor Stinner872b2912014-04-05 14:27:07 +02008919 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8920
Victor Stinner33798672016-03-01 21:59:58 +01008921 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008922 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008923 if (PyUnicode_IS_ASCII(input)) {
8924 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8925 if (res < 0) {
8926 _PyUnicodeWriter_Dealloc(&writer);
8927 return NULL;
8928 }
8929 if (res == 1)
8930 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008931 }
Victor Stinner33798672016-03-01 21:59:58 +01008932 else {
8933 i = 0;
8934 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008936 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008937 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008938 int translate;
8939 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8940 Py_ssize_t newpos;
8941 /* startpos for collecting untranslatable chars */
8942 Py_ssize_t collstart;
8943 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008944 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008945
Victor Stinner1194ea02014-04-04 19:37:40 +02008946 ch = PyUnicode_READ(kind, data, i);
8947 translate = charmaptranslate_output(ch, mapping, &writer);
8948 if (translate < 0)
8949 goto onError;
8950
8951 if (translate != 0) {
8952 /* it worked => adjust input pointer */
8953 ++i;
8954 continue;
8955 }
8956
8957 /* untranslatable character */
8958 collstart = i;
8959 collend = i+1;
8960
8961 /* find all untranslatable characters */
8962 while (collend < size) {
8963 PyObject *x;
8964 ch = PyUnicode_READ(kind, data, collend);
8965 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008966 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008967 Py_XDECREF(x);
8968 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008969 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008970 ++collend;
8971 }
8972
8973 if (ignore) {
8974 i = collend;
8975 }
8976 else {
8977 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8978 reason, input, &exc,
8979 collstart, collend, &newpos);
8980 if (repunicode == NULL)
8981 goto onError;
8982 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008983 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008984 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008985 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008986 Py_DECREF(repunicode);
8987 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008988 }
8989 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008990 Py_XDECREF(exc);
8991 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008992 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008993
Benjamin Peterson29060642009-01-31 22:14:21 +00008994 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008995 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008996 Py_XDECREF(exc);
8997 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008998 return NULL;
8999}
9000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009001/* Deprecated. Use PyUnicode_Translate instead. */
9002PyObject *
9003PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9004 Py_ssize_t size,
9005 PyObject *mapping,
9006 const char *errors)
9007{
Christian Heimes5f520f42012-09-11 14:03:25 +02009008 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009009 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9010 if (!unicode)
9011 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009012 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9013 Py_DECREF(unicode);
9014 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009015}
9016
Alexander Belopolsky40018472011-02-26 01:02:56 +00009017PyObject *
9018PyUnicode_Translate(PyObject *str,
9019 PyObject *mapping,
9020 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009021{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009022 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009023 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009024 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009025}
Tim Petersced69f82003-09-16 20:30:58 +00009026
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009027static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009028fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009029{
9030 /* No need to call PyUnicode_READY(self) because this function is only
9031 called as a callback from fixup() which does it already. */
9032 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9033 const int kind = PyUnicode_KIND(self);
9034 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009035 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009036 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009037 Py_ssize_t i;
9038
9039 for (i = 0; i < len; ++i) {
9040 ch = PyUnicode_READ(kind, data, i);
9041 fixed = 0;
9042 if (ch > 127) {
9043 if (Py_UNICODE_ISSPACE(ch))
9044 fixed = ' ';
9045 else {
9046 const int decimal = Py_UNICODE_TODECIMAL(ch);
9047 if (decimal >= 0)
9048 fixed = '0' + decimal;
9049 }
9050 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009051 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009052 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053 PyUnicode_WRITE(kind, data, i, fixed);
9054 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009055 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009056 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009058 }
9059
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009060 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009061}
9062
9063PyObject *
9064_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9065{
9066 if (!PyUnicode_Check(unicode)) {
9067 PyErr_BadInternalCall();
9068 return NULL;
9069 }
9070 if (PyUnicode_READY(unicode) == -1)
9071 return NULL;
9072 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9073 /* If the string is already ASCII, just return the same string */
9074 Py_INCREF(unicode);
9075 return unicode;
9076 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009077 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009078}
9079
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009080PyObject *
9081PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9082 Py_ssize_t length)
9083{
Victor Stinnerf0124502011-11-21 23:12:56 +01009084 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009085 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009086 Py_UCS4 maxchar;
9087 enum PyUnicode_Kind kind;
9088 void *data;
9089
Victor Stinner99d7ad02012-02-22 13:37:39 +01009090 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009091 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009092 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009093 if (ch > 127) {
9094 int decimal = Py_UNICODE_TODECIMAL(ch);
9095 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009096 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009097 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009098 }
9099 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009100
9101 /* Copy to a new string */
9102 decimal = PyUnicode_New(length, maxchar);
9103 if (decimal == NULL)
9104 return decimal;
9105 kind = PyUnicode_KIND(decimal);
9106 data = PyUnicode_DATA(decimal);
9107 /* Iterate over code points */
9108 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009109 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009110 if (ch > 127) {
9111 int decimal = Py_UNICODE_TODECIMAL(ch);
9112 if (decimal >= 0)
9113 ch = '0' + decimal;
9114 }
9115 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009116 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009117 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009118}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009119/* --- Decimal Encoder ---------------------------------------------------- */
9120
Alexander Belopolsky40018472011-02-26 01:02:56 +00009121int
9122PyUnicode_EncodeDecimal(Py_UNICODE *s,
9123 Py_ssize_t length,
9124 char *output,
9125 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009126{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009127 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009128 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009129 enum PyUnicode_Kind kind;
9130 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009131
9132 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009133 PyErr_BadArgument();
9134 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009135 }
9136
Victor Stinner42bf7752011-11-21 22:52:58 +01009137 unicode = PyUnicode_FromUnicode(s, length);
9138 if (unicode == NULL)
9139 return -1;
9140
Benjamin Petersonbac79492012-01-14 13:34:47 -05009141 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009142 Py_DECREF(unicode);
9143 return -1;
9144 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009145 kind = PyUnicode_KIND(unicode);
9146 data = PyUnicode_DATA(unicode);
9147
Victor Stinnerb84d7232011-11-22 01:50:07 +01009148 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009149 PyObject *exc;
9150 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009151 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009152 Py_ssize_t startpos;
9153
9154 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009155
Benjamin Peterson29060642009-01-31 22:14:21 +00009156 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009157 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009158 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009159 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009160 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009161 decimal = Py_UNICODE_TODECIMAL(ch);
9162 if (decimal >= 0) {
9163 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009164 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009165 continue;
9166 }
9167 if (0 < ch && ch < 256) {
9168 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009169 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009170 continue;
9171 }
Victor Stinner6345be92011-11-25 20:09:01 +01009172
Victor Stinner42bf7752011-11-21 22:52:58 +01009173 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009174 exc = NULL;
9175 raise_encode_exception(&exc, "decimal", unicode,
9176 startpos, startpos+1,
9177 "invalid decimal Unicode string");
9178 Py_XDECREF(exc);
9179 Py_DECREF(unicode);
9180 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009181 }
9182 /* 0-terminate the output string */
9183 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009184 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009185 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009186}
9187
Guido van Rossumd57fd912000-03-10 22:53:23 +00009188/* --- Helpers ------------------------------------------------------------ */
9189
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009190/* helper macro to fixup start/end slice values */
9191#define ADJUST_INDICES(start, end, len) \
9192 if (end > len) \
9193 end = len; \
9194 else if (end < 0) { \
9195 end += len; \
9196 if (end < 0) \
9197 end = 0; \
9198 } \
9199 if (start < 0) { \
9200 start += len; \
9201 if (start < 0) \
9202 start = 0; \
9203 }
9204
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009205static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009206any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009207 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009208 Py_ssize_t end,
9209 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009210{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009211 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212 void *buf1, *buf2;
9213 Py_ssize_t len1, len2, result;
9214
9215 kind1 = PyUnicode_KIND(s1);
9216 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009217 if (kind1 < kind2)
9218 return -1;
9219
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220 len1 = PyUnicode_GET_LENGTH(s1);
9221 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009222 ADJUST_INDICES(start, end, len1);
9223 if (end - start < len2)
9224 return -1;
9225
9226 buf1 = PyUnicode_DATA(s1);
9227 buf2 = PyUnicode_DATA(s2);
9228 if (len2 == 1) {
9229 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9230 result = findchar((const char *)buf1 + kind1*start,
9231 kind1, end - start, ch, direction);
9232 if (result == -1)
9233 return -1;
9234 else
9235 return start + result;
9236 }
9237
9238 if (kind2 != kind1) {
9239 buf2 = _PyUnicode_AsKind(s2, kind1);
9240 if (!buf2)
9241 return -2;
9242 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009243
Victor Stinner794d5672011-10-10 03:21:36 +02009244 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009245 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009246 case PyUnicode_1BYTE_KIND:
9247 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9248 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9249 else
9250 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9251 break;
9252 case PyUnicode_2BYTE_KIND:
9253 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9254 break;
9255 case PyUnicode_4BYTE_KIND:
9256 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9257 break;
9258 default:
9259 assert(0); result = -2;
9260 }
9261 }
9262 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009263 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009264 case PyUnicode_1BYTE_KIND:
9265 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9266 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9267 else
9268 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9269 break;
9270 case PyUnicode_2BYTE_KIND:
9271 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9272 break;
9273 case PyUnicode_4BYTE_KIND:
9274 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9275 break;
9276 default:
9277 assert(0); result = -2;
9278 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 }
9280
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009281 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009282 PyMem_Free(buf2);
9283
9284 return result;
9285}
9286
9287Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009288_PyUnicode_InsertThousandsGrouping(
9289 PyObject *unicode, Py_ssize_t index,
9290 Py_ssize_t n_buffer,
9291 void *digits, Py_ssize_t n_digits,
9292 Py_ssize_t min_width,
9293 const char *grouping, PyObject *thousands_sep,
9294 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009295{
Victor Stinner41a863c2012-02-24 00:37:51 +01009296 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009297 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009298 Py_ssize_t thousands_sep_len;
9299 Py_ssize_t len;
9300
9301 if (unicode != NULL) {
9302 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009303 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009304 }
9305 else {
9306 kind = PyUnicode_1BYTE_KIND;
9307 data = NULL;
9308 }
9309 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9310 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9311 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9312 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009313 if (thousands_sep_kind < kind) {
9314 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9315 if (!thousands_sep_data)
9316 return -1;
9317 }
9318 else {
9319 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9320 if (!data)
9321 return -1;
9322 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009323 }
9324
Benjamin Petersonead6b532011-12-20 17:23:42 -06009325 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009326 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009327 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009328 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009329 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009330 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009331 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009332 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009333 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009334 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009335 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009336 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009337 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009338 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009339 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009340 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009341 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009342 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009343 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009344 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009345 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009346 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009347 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009348 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009349 break;
9350 default:
9351 assert(0);
9352 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009354 if (unicode != NULL && thousands_sep_kind != kind) {
9355 if (thousands_sep_kind < kind)
9356 PyMem_Free(thousands_sep_data);
9357 else
9358 PyMem_Free(data);
9359 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009360 if (unicode == NULL) {
9361 *maxchar = 127;
9362 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009363 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009364 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009365 }
9366 }
9367 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368}
9369
9370
Alexander Belopolsky40018472011-02-26 01:02:56 +00009371Py_ssize_t
9372PyUnicode_Count(PyObject *str,
9373 PyObject *substr,
9374 Py_ssize_t start,
9375 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009377 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009378 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 void *buf1 = NULL, *buf2 = NULL;
9380 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009381
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009382 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009383 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009384
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009385 kind1 = PyUnicode_KIND(str);
9386 kind2 = PyUnicode_KIND(substr);
9387 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009388 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009389
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009390 len1 = PyUnicode_GET_LENGTH(str);
9391 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009393 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009394 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009395
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009396 buf1 = PyUnicode_DATA(str);
9397 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009398 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009399 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009400 if (!buf2)
9401 goto onError;
9402 }
9403
9404 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009405 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009406 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009407 result = asciilib_count(
9408 ((Py_UCS1*)buf1) + start, end - start,
9409 buf2, len2, PY_SSIZE_T_MAX
9410 );
9411 else
9412 result = ucs1lib_count(
9413 ((Py_UCS1*)buf1) + start, end - start,
9414 buf2, len2, PY_SSIZE_T_MAX
9415 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 break;
9417 case PyUnicode_2BYTE_KIND:
9418 result = ucs2lib_count(
9419 ((Py_UCS2*)buf1) + start, end - start,
9420 buf2, len2, PY_SSIZE_T_MAX
9421 );
9422 break;
9423 case PyUnicode_4BYTE_KIND:
9424 result = ucs4lib_count(
9425 ((Py_UCS4*)buf1) + start, end - start,
9426 buf2, len2, PY_SSIZE_T_MAX
9427 );
9428 break;
9429 default:
9430 assert(0); result = 0;
9431 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009432
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009433 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 PyMem_Free(buf2);
9435
Guido van Rossumd57fd912000-03-10 22:53:23 +00009436 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009438 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 PyMem_Free(buf2);
9440 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009441}
9442
Alexander Belopolsky40018472011-02-26 01:02:56 +00009443Py_ssize_t
9444PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009445 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009446 Py_ssize_t start,
9447 Py_ssize_t end,
9448 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009449{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009450 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009451 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009452
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009453 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454}
9455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009456Py_ssize_t
9457PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9458 Py_ssize_t start, Py_ssize_t end,
9459 int direction)
9460{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009462 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009463 if (PyUnicode_READY(str) == -1)
9464 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009465 if (start < 0 || end < 0) {
9466 PyErr_SetString(PyExc_IndexError, "string index out of range");
9467 return -2;
9468 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009469 if (end > PyUnicode_GET_LENGTH(str))
9470 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009471 if (start >= end)
9472 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009473 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009474 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9475 kind, end-start, ch, direction);
9476 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009477 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009478 else
9479 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480}
9481
Alexander Belopolsky40018472011-02-26 01:02:56 +00009482static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009483tailmatch(PyObject *self,
9484 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009485 Py_ssize_t start,
9486 Py_ssize_t end,
9487 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009488{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009489 int kind_self;
9490 int kind_sub;
9491 void *data_self;
9492 void *data_sub;
9493 Py_ssize_t offset;
9494 Py_ssize_t i;
9495 Py_ssize_t end_sub;
9496
9497 if (PyUnicode_READY(self) == -1 ||
9498 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009499 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009501 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9502 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009504 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009505
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009506 if (PyUnicode_GET_LENGTH(substring) == 0)
9507 return 1;
9508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009509 kind_self = PyUnicode_KIND(self);
9510 data_self = PyUnicode_DATA(self);
9511 kind_sub = PyUnicode_KIND(substring);
9512 data_sub = PyUnicode_DATA(substring);
9513 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9514
9515 if (direction > 0)
9516 offset = end;
9517 else
9518 offset = start;
9519
9520 if (PyUnicode_READ(kind_self, data_self, offset) ==
9521 PyUnicode_READ(kind_sub, data_sub, 0) &&
9522 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9523 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9524 /* If both are of the same kind, memcmp is sufficient */
9525 if (kind_self == kind_sub) {
9526 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009527 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009528 data_sub,
9529 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009530 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009532 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009533 else {
9534 /* We do not need to compare 0 and len(substring)-1 because
9535 the if statement above ensured already that they are equal
9536 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009537 for (i = 1; i < end_sub; ++i) {
9538 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9539 PyUnicode_READ(kind_sub, data_sub, i))
9540 return 0;
9541 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009542 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009543 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009544 }
9545
9546 return 0;
9547}
9548
Alexander Belopolsky40018472011-02-26 01:02:56 +00009549Py_ssize_t
9550PyUnicode_Tailmatch(PyObject *str,
9551 PyObject *substr,
9552 Py_ssize_t start,
9553 Py_ssize_t end,
9554 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009555{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009556 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009557 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009558
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009559 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009560}
9561
Guido van Rossumd57fd912000-03-10 22:53:23 +00009562/* Apply fixfct filter to the Unicode object self and return a
9563 reference to the modified object */
9564
Alexander Belopolsky40018472011-02-26 01:02:56 +00009565static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009566fixup(PyObject *self,
9567 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009568{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569 PyObject *u;
9570 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009571 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009572
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009573 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009574 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009575 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009576 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009577
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009578 /* fix functions return the new maximum character in a string,
9579 if the kind of the resulting unicode object does not change,
9580 everything is fine. Otherwise we need to change the string kind
9581 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009582 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009583
9584 if (maxchar_new == 0) {
9585 /* no changes */;
9586 if (PyUnicode_CheckExact(self)) {
9587 Py_DECREF(u);
9588 Py_INCREF(self);
9589 return self;
9590 }
9591 else
9592 return u;
9593 }
9594
Victor Stinnere6abb482012-05-02 01:15:40 +02009595 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009596
Victor Stinnereaab6042011-12-11 22:22:39 +01009597 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009598 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009599
9600 /* In case the maximum character changed, we need to
9601 convert the string to the new category. */
9602 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9603 if (v == NULL) {
9604 Py_DECREF(u);
9605 return NULL;
9606 }
9607 if (maxchar_new > maxchar_old) {
9608 /* If the maxchar increased so that the kind changed, not all
9609 characters are representable anymore and we need to fix the
9610 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009611 _PyUnicode_FastCopyCharacters(v, 0,
9612 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009613 maxchar_old = fixfct(v);
9614 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009615 }
9616 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009617 _PyUnicode_FastCopyCharacters(v, 0,
9618 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009619 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009620 Py_DECREF(u);
9621 assert(_PyUnicode_CheckConsistency(v, 1));
9622 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009623}
9624
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009625static PyObject *
9626ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009627{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009628 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9629 char *resdata, *data = PyUnicode_DATA(self);
9630 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009631
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009632 res = PyUnicode_New(len, 127);
9633 if (res == NULL)
9634 return NULL;
9635 resdata = PyUnicode_DATA(res);
9636 if (lower)
9637 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009639 _Py_bytes_upper(resdata, data, len);
9640 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009641}
9642
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009643static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009644handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009645{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009646 Py_ssize_t j;
9647 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009648 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009649 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009650
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009651 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9652
9653 where ! is a negation and \p{xxx} is a character with property xxx.
9654 */
9655 for (j = i - 1; j >= 0; j--) {
9656 c = PyUnicode_READ(kind, data, j);
9657 if (!_PyUnicode_IsCaseIgnorable(c))
9658 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009659 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009660 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9661 if (final_sigma) {
9662 for (j = i + 1; j < length; j++) {
9663 c = PyUnicode_READ(kind, data, j);
9664 if (!_PyUnicode_IsCaseIgnorable(c))
9665 break;
9666 }
9667 final_sigma = j == length || !_PyUnicode_IsCased(c);
9668 }
9669 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009670}
9671
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009672static int
9673lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9674 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009675{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009676 /* Obscure special case. */
9677 if (c == 0x3A3) {
9678 mapped[0] = handle_capital_sigma(kind, data, length, i);
9679 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009680 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009681 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009682}
9683
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009684static Py_ssize_t
9685do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009686{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009687 Py_ssize_t i, k = 0;
9688 int n_res, j;
9689 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009690
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009691 c = PyUnicode_READ(kind, data, 0);
9692 n_res = _PyUnicode_ToUpperFull(c, mapped);
9693 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009694 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009695 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009696 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009697 for (i = 1; i < length; i++) {
9698 c = PyUnicode_READ(kind, data, i);
9699 n_res = lower_ucs4(kind, data, length, i, c, mapped);
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];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009703 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009704 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009705 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009706}
9707
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009708static Py_ssize_t
9709do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9710 Py_ssize_t i, k = 0;
9711
9712 for (i = 0; i < length; i++) {
9713 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9714 int n_res, j;
9715 if (Py_UNICODE_ISUPPER(c)) {
9716 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9717 }
9718 else if (Py_UNICODE_ISLOWER(c)) {
9719 n_res = _PyUnicode_ToUpperFull(c, mapped);
9720 }
9721 else {
9722 n_res = 1;
9723 mapped[0] = c;
9724 }
9725 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009726 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009727 res[k++] = mapped[j];
9728 }
9729 }
9730 return k;
9731}
9732
9733static Py_ssize_t
9734do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9735 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009736{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009737 Py_ssize_t i, k = 0;
9738
9739 for (i = 0; i < length; i++) {
9740 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9741 int n_res, j;
9742 if (lower)
9743 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9744 else
9745 n_res = _PyUnicode_ToUpperFull(c, mapped);
9746 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009747 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009748 res[k++] = mapped[j];
9749 }
9750 }
9751 return k;
9752}
9753
9754static Py_ssize_t
9755do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9756{
9757 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9758}
9759
9760static Py_ssize_t
9761do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9762{
9763 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9764}
9765
Benjamin Petersone51757f2012-01-12 21:10:29 -05009766static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009767do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9768{
9769 Py_ssize_t i, k = 0;
9770
9771 for (i = 0; i < length; i++) {
9772 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9773 Py_UCS4 mapped[3];
9774 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9775 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009776 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009777 res[k++] = mapped[j];
9778 }
9779 }
9780 return k;
9781}
9782
9783static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009784do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9785{
9786 Py_ssize_t i, k = 0;
9787 int previous_is_cased;
9788
9789 previous_is_cased = 0;
9790 for (i = 0; i < length; i++) {
9791 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9792 Py_UCS4 mapped[3];
9793 int n_res, j;
9794
9795 if (previous_is_cased)
9796 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9797 else
9798 n_res = _PyUnicode_ToTitleFull(c, mapped);
9799
9800 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009801 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009802 res[k++] = mapped[j];
9803 }
9804
9805 previous_is_cased = _PyUnicode_IsCased(c);
9806 }
9807 return k;
9808}
9809
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009810static PyObject *
9811case_operation(PyObject *self,
9812 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9813{
9814 PyObject *res = NULL;
9815 Py_ssize_t length, newlength = 0;
9816 int kind, outkind;
9817 void *data, *outdata;
9818 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9819
Benjamin Petersoneea48462012-01-16 14:28:50 -05009820 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009821
9822 kind = PyUnicode_KIND(self);
9823 data = PyUnicode_DATA(self);
9824 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009825 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009826 PyErr_SetString(PyExc_OverflowError, "string is too long");
9827 return NULL;
9828 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009829 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009830 if (tmp == NULL)
9831 return PyErr_NoMemory();
9832 newlength = perform(kind, data, length, tmp, &maxchar);
9833 res = PyUnicode_New(newlength, maxchar);
9834 if (res == NULL)
9835 goto leave;
9836 tmpend = tmp + newlength;
9837 outdata = PyUnicode_DATA(res);
9838 outkind = PyUnicode_KIND(res);
9839 switch (outkind) {
9840 case PyUnicode_1BYTE_KIND:
9841 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9842 break;
9843 case PyUnicode_2BYTE_KIND:
9844 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9845 break;
9846 case PyUnicode_4BYTE_KIND:
9847 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9848 break;
9849 default:
9850 assert(0);
9851 break;
9852 }
9853 leave:
9854 PyMem_FREE(tmp);
9855 return res;
9856}
9857
Tim Peters8ce9f162004-08-27 01:49:32 +00009858PyObject *
9859PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009860{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009861 PyObject *res;
9862 PyObject *fseq;
9863 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009864 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009865
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009866 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009867 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009868 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009869 }
9870
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009871 /* NOTE: the following code can't call back into Python code,
9872 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009873 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009874
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009875 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009876 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009877 res = _PyUnicode_JoinArray(separator, items, seqlen);
9878 Py_DECREF(fseq);
9879 return res;
9880}
9881
9882PyObject *
9883_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9884{
9885 PyObject *res = NULL; /* the result */
9886 PyObject *sep = NULL;
9887 Py_ssize_t seplen;
9888 PyObject *item;
9889 Py_ssize_t sz, i, res_offset;
9890 Py_UCS4 maxchar;
9891 Py_UCS4 item_maxchar;
9892 int use_memcpy;
9893 unsigned char *res_data = NULL, *sep_data = NULL;
9894 PyObject *last_obj;
9895 unsigned int kind = 0;
9896
Tim Peters05eba1f2004-08-27 21:32:02 +00009897 /* If empty sequence, return u"". */
9898 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009899 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009900 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009901
Tim Peters05eba1f2004-08-27 21:32:02 +00009902 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009903 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009904 if (seqlen == 1) {
9905 if (PyUnicode_CheckExact(items[0])) {
9906 res = items[0];
9907 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009908 return res;
9909 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009910 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009911 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009912 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009913 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009914 /* Set up sep and seplen */
9915 if (separator == NULL) {
9916 /* fall back to a blank space separator */
9917 sep = PyUnicode_FromOrdinal(' ');
9918 if (!sep)
9919 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009920 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009921 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009922 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009923 else {
9924 if (!PyUnicode_Check(separator)) {
9925 PyErr_Format(PyExc_TypeError,
9926 "separator: expected str instance,"
9927 " %.80s found",
9928 Py_TYPE(separator)->tp_name);
9929 goto onError;
9930 }
9931 if (PyUnicode_READY(separator))
9932 goto onError;
9933 sep = separator;
9934 seplen = PyUnicode_GET_LENGTH(separator);
9935 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9936 /* inc refcount to keep this code path symmetric with the
9937 above case of a blank separator */
9938 Py_INCREF(sep);
9939 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009940 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009941 }
9942
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009943 /* There are at least two things to join, or else we have a subclass
9944 * of str in the sequence.
9945 * Do a pre-pass to figure out the total amount of space we'll
9946 * need (sz), and see whether all argument are strings.
9947 */
9948 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009949#ifdef Py_DEBUG
9950 use_memcpy = 0;
9951#else
9952 use_memcpy = 1;
9953#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009954 for (i = 0; i < seqlen; i++) {
9955 const Py_ssize_t old_sz = sz;
9956 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009957 if (!PyUnicode_Check(item)) {
9958 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009959 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009960 " %.80s found",
9961 i, Py_TYPE(item)->tp_name);
9962 goto onError;
9963 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009964 if (PyUnicode_READY(item) == -1)
9965 goto onError;
9966 sz += PyUnicode_GET_LENGTH(item);
9967 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009968 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009969 if (i != 0)
9970 sz += seplen;
9971 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9972 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009973 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009974 goto onError;
9975 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009976 if (use_memcpy && last_obj != NULL) {
9977 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9978 use_memcpy = 0;
9979 }
9980 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009981 }
Tim Petersced69f82003-09-16 20:30:58 +00009982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009984 if (res == NULL)
9985 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009986
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009987 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009988#ifdef Py_DEBUG
9989 use_memcpy = 0;
9990#else
9991 if (use_memcpy) {
9992 res_data = PyUnicode_1BYTE_DATA(res);
9993 kind = PyUnicode_KIND(res);
9994 if (seplen != 0)
9995 sep_data = PyUnicode_1BYTE_DATA(sep);
9996 }
9997#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009998 if (use_memcpy) {
9999 for (i = 0; i < seqlen; ++i) {
10000 Py_ssize_t itemlen;
10001 item = items[i];
10002
10003 /* Copy item, and maybe the separator. */
10004 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010005 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010006 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010007 kind * seplen);
10008 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010009 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010010
10011 itemlen = PyUnicode_GET_LENGTH(item);
10012 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010013 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010014 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010015 kind * itemlen);
10016 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010017 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010018 }
10019 assert(res_data == PyUnicode_1BYTE_DATA(res)
10020 + kind * PyUnicode_GET_LENGTH(res));
10021 }
10022 else {
10023 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10024 Py_ssize_t itemlen;
10025 item = items[i];
10026
10027 /* Copy item, and maybe the separator. */
10028 if (i && seplen != 0) {
10029 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10030 res_offset += seplen;
10031 }
10032
10033 itemlen = PyUnicode_GET_LENGTH(item);
10034 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010035 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010036 res_offset += itemlen;
10037 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010038 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010039 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010040 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010043 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010045
Benjamin Peterson29060642009-01-31 22:14:21 +000010046 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010048 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010049 return NULL;
10050}
10051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052#define FILL(kind, data, value, start, length) \
10053 do { \
10054 Py_ssize_t i_ = 0; \
10055 assert(kind != PyUnicode_WCHAR_KIND); \
10056 switch ((kind)) { \
10057 case PyUnicode_1BYTE_KIND: { \
10058 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010059 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 break; \
10061 } \
10062 case PyUnicode_2BYTE_KIND: { \
10063 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10064 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10065 break; \
10066 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010067 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10069 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10070 break; \
10071 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010072 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 } \
10074 } while (0)
10075
Victor Stinnerd3f08822012-05-29 12:57:52 +020010076void
10077_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10078 Py_UCS4 fill_char)
10079{
10080 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10081 const void *data = PyUnicode_DATA(unicode);
10082 assert(PyUnicode_IS_READY(unicode));
10083 assert(unicode_modifiable(unicode));
10084 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10085 assert(start >= 0);
10086 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10087 FILL(kind, data, fill_char, start, length);
10088}
10089
Victor Stinner3fe55312012-01-04 00:33:50 +010010090Py_ssize_t
10091PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10092 Py_UCS4 fill_char)
10093{
10094 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010095
10096 if (!PyUnicode_Check(unicode)) {
10097 PyErr_BadInternalCall();
10098 return -1;
10099 }
10100 if (PyUnicode_READY(unicode) == -1)
10101 return -1;
10102 if (unicode_check_modifiable(unicode))
10103 return -1;
10104
Victor Stinnerd3f08822012-05-29 12:57:52 +020010105 if (start < 0) {
10106 PyErr_SetString(PyExc_IndexError, "string index out of range");
10107 return -1;
10108 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010109 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10110 PyErr_SetString(PyExc_ValueError,
10111 "fill character is bigger than "
10112 "the string maximum character");
10113 return -1;
10114 }
10115
10116 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10117 length = Py_MIN(maxlen, length);
10118 if (length <= 0)
10119 return 0;
10120
Victor Stinnerd3f08822012-05-29 12:57:52 +020010121 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010122 return length;
10123}
10124
Victor Stinner9310abb2011-10-05 00:59:23 +020010125static PyObject *
10126pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010127 Py_ssize_t left,
10128 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010130{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 PyObject *u;
10132 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010133 int kind;
10134 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135
10136 if (left < 0)
10137 left = 0;
10138 if (right < 0)
10139 right = 0;
10140
Victor Stinnerc4b49542011-12-11 22:44:26 +010010141 if (left == 0 && right == 0)
10142 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10145 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010146 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10147 return NULL;
10148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010150 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010152 if (!u)
10153 return NULL;
10154
10155 kind = PyUnicode_KIND(u);
10156 data = PyUnicode_DATA(u);
10157 if (left)
10158 FILL(kind, data, fill, 0, left);
10159 if (right)
10160 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010161 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010162 assert(_PyUnicode_CheckConsistency(u, 1));
10163 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010164}
10165
Alexander Belopolsky40018472011-02-26 01:02:56 +000010166PyObject *
10167PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010168{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010169 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010170
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010171 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010172 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010173
Benjamin Petersonead6b532011-12-20 17:23:42 -060010174 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010175 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010176 if (PyUnicode_IS_ASCII(string))
10177 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010178 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010179 PyUnicode_GET_LENGTH(string), keepends);
10180 else
10181 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010182 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010183 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 break;
10185 case PyUnicode_2BYTE_KIND:
10186 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010187 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 PyUnicode_GET_LENGTH(string), keepends);
10189 break;
10190 case PyUnicode_4BYTE_KIND:
10191 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010192 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 PyUnicode_GET_LENGTH(string), keepends);
10194 break;
10195 default:
10196 assert(0);
10197 list = 0;
10198 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010199 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010200}
10201
Alexander Belopolsky40018472011-02-26 01:02:56 +000010202static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010203split(PyObject *self,
10204 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010205 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010206{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010207 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 void *buf1, *buf2;
10209 Py_ssize_t len1, len2;
10210 PyObject* out;
10211
Guido van Rossumd57fd912000-03-10 22:53:23 +000010212 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010213 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 if (PyUnicode_READY(self) == -1)
10216 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010219 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010221 if (PyUnicode_IS_ASCII(self))
10222 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010223 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010224 PyUnicode_GET_LENGTH(self), maxcount
10225 );
10226 else
10227 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010228 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010229 PyUnicode_GET_LENGTH(self), maxcount
10230 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 case PyUnicode_2BYTE_KIND:
10232 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010233 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 PyUnicode_GET_LENGTH(self), maxcount
10235 );
10236 case PyUnicode_4BYTE_KIND:
10237 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010238 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 PyUnicode_GET_LENGTH(self), maxcount
10240 );
10241 default:
10242 assert(0);
10243 return NULL;
10244 }
10245
10246 if (PyUnicode_READY(substring) == -1)
10247 return NULL;
10248
10249 kind1 = PyUnicode_KIND(self);
10250 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 len1 = PyUnicode_GET_LENGTH(self);
10252 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010253 if (kind1 < kind2 || len1 < len2) {
10254 out = PyList_New(1);
10255 if (out == NULL)
10256 return NULL;
10257 Py_INCREF(self);
10258 PyList_SET_ITEM(out, 0, self);
10259 return out;
10260 }
10261 buf1 = PyUnicode_DATA(self);
10262 buf2 = PyUnicode_DATA(substring);
10263 if (kind2 != kind1) {
10264 buf2 = _PyUnicode_AsKind(substring, kind1);
10265 if (!buf2)
10266 return NULL;
10267 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010269 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010271 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10272 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010273 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010274 else
10275 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010276 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 break;
10278 case PyUnicode_2BYTE_KIND:
10279 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010280 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 break;
10282 case PyUnicode_4BYTE_KIND:
10283 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010284 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 break;
10286 default:
10287 out = NULL;
10288 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010289 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 PyMem_Free(buf2);
10291 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010292}
10293
Alexander Belopolsky40018472011-02-26 01:02:56 +000010294static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010295rsplit(PyObject *self,
10296 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010297 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010298{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010299 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 void *buf1, *buf2;
10301 Py_ssize_t len1, len2;
10302 PyObject* out;
10303
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010304 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010305 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 if (PyUnicode_READY(self) == -1)
10308 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010311 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010313 if (PyUnicode_IS_ASCII(self))
10314 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010315 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010316 PyUnicode_GET_LENGTH(self), maxcount
10317 );
10318 else
10319 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010320 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010321 PyUnicode_GET_LENGTH(self), maxcount
10322 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 case PyUnicode_2BYTE_KIND:
10324 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010325 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326 PyUnicode_GET_LENGTH(self), maxcount
10327 );
10328 case PyUnicode_4BYTE_KIND:
10329 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010330 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 PyUnicode_GET_LENGTH(self), maxcount
10332 );
10333 default:
10334 assert(0);
10335 return NULL;
10336 }
10337
10338 if (PyUnicode_READY(substring) == -1)
10339 return NULL;
10340
10341 kind1 = PyUnicode_KIND(self);
10342 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 len1 = PyUnicode_GET_LENGTH(self);
10344 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010345 if (kind1 < kind2 || len1 < len2) {
10346 out = PyList_New(1);
10347 if (out == NULL)
10348 return NULL;
10349 Py_INCREF(self);
10350 PyList_SET_ITEM(out, 0, self);
10351 return out;
10352 }
10353 buf1 = PyUnicode_DATA(self);
10354 buf2 = PyUnicode_DATA(substring);
10355 if (kind2 != kind1) {
10356 buf2 = _PyUnicode_AsKind(substring, kind1);
10357 if (!buf2)
10358 return NULL;
10359 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010361 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010362 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010363 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10364 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010365 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010366 else
10367 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010368 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 break;
10370 case PyUnicode_2BYTE_KIND:
10371 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010372 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 break;
10374 case PyUnicode_4BYTE_KIND:
10375 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010376 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 break;
10378 default:
10379 out = NULL;
10380 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010381 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 PyMem_Free(buf2);
10383 return out;
10384}
10385
10386static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010387anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10388 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010390 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010392 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10393 return asciilib_find(buf1, len1, buf2, len2, offset);
10394 else
10395 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 case PyUnicode_2BYTE_KIND:
10397 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10398 case PyUnicode_4BYTE_KIND:
10399 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10400 }
10401 assert(0);
10402 return -1;
10403}
10404
10405static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010406anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10407 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010409 switch (kind) {
10410 case PyUnicode_1BYTE_KIND:
10411 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10412 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10413 else
10414 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10415 case PyUnicode_2BYTE_KIND:
10416 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10417 case PyUnicode_4BYTE_KIND:
10418 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10419 }
10420 assert(0);
10421 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010422}
10423
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010424static void
10425replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10426 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10427{
10428 int kind = PyUnicode_KIND(u);
10429 void *data = PyUnicode_DATA(u);
10430 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10431 if (kind == PyUnicode_1BYTE_KIND) {
10432 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10433 (Py_UCS1 *)data + len,
10434 u1, u2, maxcount);
10435 }
10436 else if (kind == PyUnicode_2BYTE_KIND) {
10437 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10438 (Py_UCS2 *)data + len,
10439 u1, u2, maxcount);
10440 }
10441 else {
10442 assert(kind == PyUnicode_4BYTE_KIND);
10443 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10444 (Py_UCS4 *)data + len,
10445 u1, u2, maxcount);
10446 }
10447}
10448
Alexander Belopolsky40018472011-02-26 01:02:56 +000010449static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450replace(PyObject *self, PyObject *str1,
10451 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010452{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010453 PyObject *u;
10454 char *sbuf = PyUnicode_DATA(self);
10455 char *buf1 = PyUnicode_DATA(str1);
10456 char *buf2 = PyUnicode_DATA(str2);
10457 int srelease = 0, release1 = 0, release2 = 0;
10458 int skind = PyUnicode_KIND(self);
10459 int kind1 = PyUnicode_KIND(str1);
10460 int kind2 = PyUnicode_KIND(str2);
10461 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10462 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10463 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010464 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010465 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010466
10467 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010468 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010469 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010470 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010471
Victor Stinner59de0ee2011-10-07 10:01:28 +020010472 if (str1 == str2)
10473 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474
Victor Stinner49a0a212011-10-12 23:46:10 +020010475 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010476 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10477 if (maxchar < maxchar_str1)
10478 /* substring too wide to be present */
10479 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010480 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10481 /* Replacing str1 with str2 may cause a maxchar reduction in the
10482 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010483 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010484 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010487 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010489 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010491 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010492 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010493 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010494
Victor Stinner69ed0f42013-04-09 21:48:24 +020010495 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010496 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010497 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010498 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010499 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010501 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010503
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010504 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10505 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010506 }
10507 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010508 int rkind = skind;
10509 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010510 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010512 if (kind1 < rkind) {
10513 /* widen substring */
10514 buf1 = _PyUnicode_AsKind(str1, rkind);
10515 if (!buf1) goto error;
10516 release1 = 1;
10517 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010518 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010519 if (i < 0)
10520 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 if (rkind > kind2) {
10522 /* widen replacement */
10523 buf2 = _PyUnicode_AsKind(str2, rkind);
10524 if (!buf2) goto error;
10525 release2 = 1;
10526 }
10527 else if (rkind < kind2) {
10528 /* widen self and buf1 */
10529 rkind = kind2;
10530 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010531 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 sbuf = _PyUnicode_AsKind(self, rkind);
10533 if (!sbuf) goto error;
10534 srelease = 1;
10535 buf1 = _PyUnicode_AsKind(str1, rkind);
10536 if (!buf1) goto error;
10537 release1 = 1;
10538 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010539 u = PyUnicode_New(slen, maxchar);
10540 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010542 assert(PyUnicode_KIND(u) == rkind);
10543 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010544
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010545 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010546 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010547 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010548 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010549 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010551
10552 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010553 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010554 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010555 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010556 if (i == -1)
10557 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010558 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010560 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010562 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010563 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010564 }
10565 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010567 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010568 int rkind = skind;
10569 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010572 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 buf1 = _PyUnicode_AsKind(str1, rkind);
10574 if (!buf1) goto error;
10575 release1 = 1;
10576 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010577 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010578 if (n == 0)
10579 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010581 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 buf2 = _PyUnicode_AsKind(str2, rkind);
10583 if (!buf2) goto error;
10584 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010585 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010587 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 rkind = kind2;
10589 sbuf = _PyUnicode_AsKind(self, rkind);
10590 if (!sbuf) goto error;
10591 srelease = 1;
10592 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010593 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010594 buf1 = _PyUnicode_AsKind(str1, rkind);
10595 if (!buf1) goto error;
10596 release1 = 1;
10597 }
10598 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10599 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010600 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 PyErr_SetString(PyExc_OverflowError,
10602 "replace string is too long");
10603 goto error;
10604 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010605 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010606 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010607 _Py_INCREF_UNICODE_EMPTY();
10608 if (!unicode_empty)
10609 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010610 u = unicode_empty;
10611 goto done;
10612 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010613 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 PyErr_SetString(PyExc_OverflowError,
10615 "replace string is too long");
10616 goto error;
10617 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010618 u = PyUnicode_New(new_size, maxchar);
10619 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010620 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010621 assert(PyUnicode_KIND(u) == rkind);
10622 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 ires = i = 0;
10624 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010625 while (n-- > 0) {
10626 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010627 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010628 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010629 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010630 if (j == -1)
10631 break;
10632 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010633 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010634 memcpy(res + rkind * ires,
10635 sbuf + rkind * i,
10636 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010637 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010638 }
10639 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010641 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010643 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010645 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010647 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010648 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010649 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010650 memcpy(res + rkind * ires,
10651 sbuf + rkind * i,
10652 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010653 }
10654 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010655 /* interleave */
10656 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010657 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010659 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010660 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010661 if (--n <= 0)
10662 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010663 memcpy(res + rkind * ires,
10664 sbuf + rkind * i,
10665 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 ires++;
10667 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010668 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010669 memcpy(res + rkind * ires,
10670 sbuf + rkind * i,
10671 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010672 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010673 }
10674
10675 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010676 unicode_adjust_maxchar(&u);
10677 if (u == NULL)
10678 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010679 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010680
10681 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010682 if (srelease)
10683 PyMem_FREE(sbuf);
10684 if (release1)
10685 PyMem_FREE(buf1);
10686 if (release2)
10687 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010688 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010690
Benjamin Peterson29060642009-01-31 22:14:21 +000010691 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010692 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 if (srelease)
10694 PyMem_FREE(sbuf);
10695 if (release1)
10696 PyMem_FREE(buf1);
10697 if (release2)
10698 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010699 return unicode_result_unchanged(self);
10700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010701 error:
10702 if (srelease && sbuf)
10703 PyMem_FREE(sbuf);
10704 if (release1 && buf1)
10705 PyMem_FREE(buf1);
10706 if (release2 && buf2)
10707 PyMem_FREE(buf2);
10708 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010709}
10710
10711/* --- Unicode Object Methods --------------------------------------------- */
10712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010713PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010714 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010715\n\
10716Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010717characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718
10719static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010720unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010721{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010722 if (PyUnicode_READY(self) == -1)
10723 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010724 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010725}
10726
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010727PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010728 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010729\n\
10730Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010731have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010732
10733static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010734unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010735{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010736 if (PyUnicode_READY(self) == -1)
10737 return NULL;
10738 if (PyUnicode_GET_LENGTH(self) == 0)
10739 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010740 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010741}
10742
Benjamin Petersond5890c82012-01-14 13:23:30 -050010743PyDoc_STRVAR(casefold__doc__,
10744 "S.casefold() -> str\n\
10745\n\
10746Return a version of S suitable for caseless comparisons.");
10747
10748static PyObject *
10749unicode_casefold(PyObject *self)
10750{
10751 if (PyUnicode_READY(self) == -1)
10752 return NULL;
10753 if (PyUnicode_IS_ASCII(self))
10754 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010755 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010756}
10757
10758
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010759/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010760
10761static int
10762convert_uc(PyObject *obj, void *addr)
10763{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010764 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010765
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010766 if (!PyUnicode_Check(obj)) {
10767 PyErr_Format(PyExc_TypeError,
10768 "The fill character must be a unicode character, "
10769 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010770 return 0;
10771 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010772 if (PyUnicode_READY(obj) < 0)
10773 return 0;
10774 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010775 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010776 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010777 return 0;
10778 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010779 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010780 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010781}
10782
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010783PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010784 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010786Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010787done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010788
10789static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010790unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010791{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010792 Py_ssize_t marg, left;
10793 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 Py_UCS4 fillchar = ' ';
10795
Victor Stinnere9a29352011-10-01 02:14:59 +020010796 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010797 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798
Benjamin Petersonbac79492012-01-14 13:34:47 -050010799 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010800 return NULL;
10801
Victor Stinnerc4b49542011-12-11 22:44:26 +010010802 if (PyUnicode_GET_LENGTH(self) >= width)
10803 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010804
Victor Stinnerc4b49542011-12-11 22:44:26 +010010805 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010806 left = marg / 2 + (marg & width & 1);
10807
Victor Stinner9310abb2011-10-05 00:59:23 +020010808 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010809}
10810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010811/* This function assumes that str1 and str2 are readied by the caller. */
10812
Marc-André Lemburge5034372000-08-08 08:04:29 +000010813static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010814unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010815{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010816#define COMPARE(TYPE1, TYPE2) \
10817 do { \
10818 TYPE1* p1 = (TYPE1 *)data1; \
10819 TYPE2* p2 = (TYPE2 *)data2; \
10820 TYPE1* end = p1 + len; \
10821 Py_UCS4 c1, c2; \
10822 for (; p1 != end; p1++, p2++) { \
10823 c1 = *p1; \
10824 c2 = *p2; \
10825 if (c1 != c2) \
10826 return (c1 < c2) ? -1 : 1; \
10827 } \
10828 } \
10829 while (0)
10830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010831 int kind1, kind2;
10832 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010833 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010834
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010835 kind1 = PyUnicode_KIND(str1);
10836 kind2 = PyUnicode_KIND(str2);
10837 data1 = PyUnicode_DATA(str1);
10838 data2 = PyUnicode_DATA(str2);
10839 len1 = PyUnicode_GET_LENGTH(str1);
10840 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010841 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010842
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010843 switch(kind1) {
10844 case PyUnicode_1BYTE_KIND:
10845 {
10846 switch(kind2) {
10847 case PyUnicode_1BYTE_KIND:
10848 {
10849 int cmp = memcmp(data1, data2, len);
10850 /* normalize result of memcmp() into the range [-1; 1] */
10851 if (cmp < 0)
10852 return -1;
10853 if (cmp > 0)
10854 return 1;
10855 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010856 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010857 case PyUnicode_2BYTE_KIND:
10858 COMPARE(Py_UCS1, Py_UCS2);
10859 break;
10860 case PyUnicode_4BYTE_KIND:
10861 COMPARE(Py_UCS1, Py_UCS4);
10862 break;
10863 default:
10864 assert(0);
10865 }
10866 break;
10867 }
10868 case PyUnicode_2BYTE_KIND:
10869 {
10870 switch(kind2) {
10871 case PyUnicode_1BYTE_KIND:
10872 COMPARE(Py_UCS2, Py_UCS1);
10873 break;
10874 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010875 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010876 COMPARE(Py_UCS2, Py_UCS2);
10877 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010878 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010879 case PyUnicode_4BYTE_KIND:
10880 COMPARE(Py_UCS2, Py_UCS4);
10881 break;
10882 default:
10883 assert(0);
10884 }
10885 break;
10886 }
10887 case PyUnicode_4BYTE_KIND:
10888 {
10889 switch(kind2) {
10890 case PyUnicode_1BYTE_KIND:
10891 COMPARE(Py_UCS4, Py_UCS1);
10892 break;
10893 case PyUnicode_2BYTE_KIND:
10894 COMPARE(Py_UCS4, Py_UCS2);
10895 break;
10896 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010897 {
10898#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10899 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10900 /* normalize result of wmemcmp() into the range [-1; 1] */
10901 if (cmp < 0)
10902 return -1;
10903 if (cmp > 0)
10904 return 1;
10905#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010906 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010907#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010908 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010909 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010910 default:
10911 assert(0);
10912 }
10913 break;
10914 }
10915 default:
10916 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010917 }
10918
Victor Stinner770e19e2012-10-04 22:59:45 +020010919 if (len1 == len2)
10920 return 0;
10921 if (len1 < len2)
10922 return -1;
10923 else
10924 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010925
10926#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010927}
10928
Benjamin Peterson621b4302016-09-09 13:54:34 -070010929static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010930unicode_compare_eq(PyObject *str1, PyObject *str2)
10931{
10932 int kind;
10933 void *data1, *data2;
10934 Py_ssize_t len;
10935 int cmp;
10936
Victor Stinnere5567ad2012-10-23 02:48:49 +020010937 len = PyUnicode_GET_LENGTH(str1);
10938 if (PyUnicode_GET_LENGTH(str2) != len)
10939 return 0;
10940 kind = PyUnicode_KIND(str1);
10941 if (PyUnicode_KIND(str2) != kind)
10942 return 0;
10943 data1 = PyUnicode_DATA(str1);
10944 data2 = PyUnicode_DATA(str2);
10945
10946 cmp = memcmp(data1, data2, len * kind);
10947 return (cmp == 0);
10948}
10949
10950
Alexander Belopolsky40018472011-02-26 01:02:56 +000010951int
10952PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010954 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10955 if (PyUnicode_READY(left) == -1 ||
10956 PyUnicode_READY(right) == -1)
10957 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010958
10959 /* a string is equal to itself */
10960 if (left == right)
10961 return 0;
10962
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010963 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010965 PyErr_Format(PyExc_TypeError,
10966 "Can't compare %.100s and %.100s",
10967 left->ob_type->tp_name,
10968 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010969 return -1;
10970}
10971
Martin v. Löwis5b222132007-06-10 09:51:05 +000010972int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010973_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10974{
10975 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10976 if (right_str == NULL)
10977 return -1;
10978 return PyUnicode_Compare(left, right_str);
10979}
10980
10981int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010982PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10983{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010984 Py_ssize_t i;
10985 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010986 Py_UCS4 chr;
10987
Victor Stinner910337b2011-10-03 03:20:16 +020010988 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010989 if (PyUnicode_READY(uni) == -1)
10990 return -1;
10991 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010992 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010993 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010994 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010995 size_t len, len2 = strlen(str);
10996 int cmp;
10997
10998 len = Py_MIN(len1, len2);
10999 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011000 if (cmp != 0) {
11001 if (cmp < 0)
11002 return -1;
11003 else
11004 return 1;
11005 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011006 if (len1 > len2)
11007 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011008 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011009 return -1; /* str is longer */
11010 return 0;
11011 }
11012 else {
11013 void *data = PyUnicode_DATA(uni);
11014 /* Compare Unicode string and source character set string */
11015 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011016 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011017 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11018 /* This check keeps Python strings that end in '\0' from comparing equal
11019 to C strings identical up to that point. */
11020 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11021 return 1; /* uni is longer */
11022 if (str[i])
11023 return -1; /* str is longer */
11024 return 0;
11025 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011026}
11027
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011028
Benjamin Peterson29060642009-01-31 22:14:21 +000011029#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011030 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011031
Alexander Belopolsky40018472011-02-26 01:02:56 +000011032PyObject *
11033PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011034{
11035 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011036 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011037
Victor Stinnere5567ad2012-10-23 02:48:49 +020011038 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11039 Py_RETURN_NOTIMPLEMENTED;
11040
11041 if (PyUnicode_READY(left) == -1 ||
11042 PyUnicode_READY(right) == -1)
11043 return NULL;
11044
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011045 if (left == right) {
11046 switch (op) {
11047 case Py_EQ:
11048 case Py_LE:
11049 case Py_GE:
11050 /* a string is equal to itself */
11051 v = Py_True;
11052 break;
11053 case Py_NE:
11054 case Py_LT:
11055 case Py_GT:
11056 v = Py_False;
11057 break;
11058 default:
11059 PyErr_BadArgument();
11060 return NULL;
11061 }
11062 }
11063 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011064 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011065 result ^= (op == Py_NE);
11066 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011067 }
11068 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011069 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011070
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011071 /* Convert the return value to a Boolean */
11072 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011073 case Py_LE:
11074 v = TEST_COND(result <= 0);
11075 break;
11076 case Py_GE:
11077 v = TEST_COND(result >= 0);
11078 break;
11079 case Py_LT:
11080 v = TEST_COND(result == -1);
11081 break;
11082 case Py_GT:
11083 v = TEST_COND(result == 1);
11084 break;
11085 default:
11086 PyErr_BadArgument();
11087 return NULL;
11088 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011089 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011090 Py_INCREF(v);
11091 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011092}
11093
Alexander Belopolsky40018472011-02-26 01:02:56 +000011094int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011095_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11096{
11097 return unicode_eq(aa, bb);
11098}
11099
11100int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011101PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011102{
Victor Stinner77282cb2013-04-14 19:22:47 +020011103 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011104 void *buf1, *buf2;
11105 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011106 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011107
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011108 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011109 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011110 "'in <string>' requires string as left operand, not %.100s",
11111 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011112 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011113 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011114 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011115 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011116 if (ensure_unicode(str) < 0)
11117 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011118
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011119 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011120 kind2 = PyUnicode_KIND(substr);
11121 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011122 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011123 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011124 len2 = PyUnicode_GET_LENGTH(substr);
11125 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011126 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011127 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011128 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011129 if (len2 == 1) {
11130 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11131 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011132 return result;
11133 }
11134 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011135 buf2 = _PyUnicode_AsKind(substr, kind1);
11136 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011137 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011138 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011139
Victor Stinner77282cb2013-04-14 19:22:47 +020011140 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011141 case PyUnicode_1BYTE_KIND:
11142 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11143 break;
11144 case PyUnicode_2BYTE_KIND:
11145 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11146 break;
11147 case PyUnicode_4BYTE_KIND:
11148 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11149 break;
11150 default:
11151 result = -1;
11152 assert(0);
11153 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011154
Victor Stinner77282cb2013-04-14 19:22:47 +020011155 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 PyMem_Free(buf2);
11157
Guido van Rossum403d68b2000-03-13 15:55:09 +000011158 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011159}
11160
Guido van Rossumd57fd912000-03-10 22:53:23 +000011161/* Concat to string or Unicode object giving a new Unicode object. */
11162
Alexander Belopolsky40018472011-02-26 01:02:56 +000011163PyObject *
11164PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011166 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011167 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011168 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011170 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11171 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011172
11173 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011174 if (left == unicode_empty)
11175 return PyUnicode_FromObject(right);
11176 if (right == unicode_empty)
11177 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011179 left_len = PyUnicode_GET_LENGTH(left);
11180 right_len = PyUnicode_GET_LENGTH(right);
11181 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011182 PyErr_SetString(PyExc_OverflowError,
11183 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011184 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011185 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011186 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011187
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011188 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11189 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011190 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011191
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011193 result = PyUnicode_New(new_len, maxchar);
11194 if (result == NULL)
11195 return NULL;
11196 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11197 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11198 assert(_PyUnicode_CheckConsistency(result, 1));
11199 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200}
11201
Walter Dörwald1ab83302007-05-18 17:15:44 +000011202void
Victor Stinner23e56682011-10-03 03:54:37 +020011203PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011204{
Victor Stinner23e56682011-10-03 03:54:37 +020011205 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011206 Py_UCS4 maxchar, maxchar2;
11207 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011208
11209 if (p_left == NULL) {
11210 if (!PyErr_Occurred())
11211 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011212 return;
11213 }
Victor Stinner23e56682011-10-03 03:54:37 +020011214 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011215 if (right == NULL || left == NULL
11216 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011217 if (!PyErr_Occurred())
11218 PyErr_BadInternalCall();
11219 goto error;
11220 }
11221
Benjamin Petersonbac79492012-01-14 13:34:47 -050011222 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011223 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011224 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011225 goto error;
11226
Victor Stinner488fa492011-12-12 00:01:39 +010011227 /* Shortcuts */
11228 if (left == unicode_empty) {
11229 Py_DECREF(left);
11230 Py_INCREF(right);
11231 *p_left = right;
11232 return;
11233 }
11234 if (right == unicode_empty)
11235 return;
11236
11237 left_len = PyUnicode_GET_LENGTH(left);
11238 right_len = PyUnicode_GET_LENGTH(right);
11239 if (left_len > PY_SSIZE_T_MAX - right_len) {
11240 PyErr_SetString(PyExc_OverflowError,
11241 "strings are too large to concat");
11242 goto error;
11243 }
11244 new_len = left_len + right_len;
11245
11246 if (unicode_modifiable(left)
11247 && PyUnicode_CheckExact(right)
11248 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011249 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11250 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011251 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011252 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011253 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11254 {
11255 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011256 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011257 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011258
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011259 /* copy 'right' into the newly allocated area of 'left' */
11260 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011261 }
Victor Stinner488fa492011-12-12 00:01:39 +010011262 else {
11263 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11264 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011265 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011266
Victor Stinner488fa492011-12-12 00:01:39 +010011267 /* Concat the two Unicode strings */
11268 res = PyUnicode_New(new_len, maxchar);
11269 if (res == NULL)
11270 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011271 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11272 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011273 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011274 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011275 }
11276 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011277 return;
11278
11279error:
Victor Stinner488fa492011-12-12 00:01:39 +010011280 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011281}
11282
11283void
11284PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11285{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011286 PyUnicode_Append(pleft, right);
11287 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011288}
11289
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011290/*
11291Wraps stringlib_parse_args_finds() and additionally ensures that the
11292first argument is a unicode object.
11293*/
11294
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011295static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011296parse_args_finds_unicode(const char * function_name, PyObject *args,
11297 PyObject **substring,
11298 Py_ssize_t *start, Py_ssize_t *end)
11299{
11300 if(stringlib_parse_args_finds(function_name, args, substring,
11301 start, end)) {
11302 if (ensure_unicode(*substring) < 0)
11303 return 0;
11304 return 1;
11305 }
11306 return 0;
11307}
11308
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011309PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011310 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011311\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011312Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011313string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011314interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315
11316static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011317unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011319 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011320 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011321 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011322 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011323 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011324 void *buf1, *buf2;
11325 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011326
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011327 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011328 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011330 kind1 = PyUnicode_KIND(self);
11331 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011332 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011333 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011334
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011335 len1 = PyUnicode_GET_LENGTH(self);
11336 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011337 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011338 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011339 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011340
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011341 buf1 = PyUnicode_DATA(self);
11342 buf2 = PyUnicode_DATA(substring);
11343 if (kind2 != kind1) {
11344 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011345 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011346 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011347 }
11348 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 case PyUnicode_1BYTE_KIND:
11350 iresult = ucs1lib_count(
11351 ((Py_UCS1*)buf1) + start, end - start,
11352 buf2, len2, PY_SSIZE_T_MAX
11353 );
11354 break;
11355 case PyUnicode_2BYTE_KIND:
11356 iresult = ucs2lib_count(
11357 ((Py_UCS2*)buf1) + start, end - start,
11358 buf2, len2, PY_SSIZE_T_MAX
11359 );
11360 break;
11361 case PyUnicode_4BYTE_KIND:
11362 iresult = ucs4lib_count(
11363 ((Py_UCS4*)buf1) + start, end - start,
11364 buf2, len2, PY_SSIZE_T_MAX
11365 );
11366 break;
11367 default:
11368 assert(0); iresult = 0;
11369 }
11370
11371 result = PyLong_FromSsize_t(iresult);
11372
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011373 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011374 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376 return result;
11377}
11378
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011379PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011380 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011382Encode S using the codec registered for encoding. Default encoding\n\
11383is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011384handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011385a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11386'xmlcharrefreplace' as well as any other name registered with\n\
11387codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388
11389static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011390unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011392 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393 char *encoding = NULL;
11394 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011395
Benjamin Peterson308d6372009-09-18 21:42:35 +000011396 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11397 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011399 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011400}
11401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011402PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011403 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404\n\
11405Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011406If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
11408static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011409unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011411 Py_ssize_t i, j, line_pos, src_len, incr;
11412 Py_UCS4 ch;
11413 PyObject *u;
11414 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011415 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011417 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011418 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419
Ezio Melotti745d54d2013-11-16 19:10:57 +020011420 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11421 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011422 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423
Antoine Pitrou22425222011-10-04 19:10:51 +020011424 if (PyUnicode_READY(self) == -1)
11425 return NULL;
11426
Thomas Wouters7e474022000-07-16 12:04:32 +000011427 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011428 src_len = PyUnicode_GET_LENGTH(self);
11429 i = j = line_pos = 0;
11430 kind = PyUnicode_KIND(self);
11431 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011432 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011433 for (; i < src_len; i++) {
11434 ch = PyUnicode_READ(kind, src_data, i);
11435 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011436 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011437 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011438 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011439 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011440 goto overflow;
11441 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011442 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011443 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011444 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011447 goto overflow;
11448 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011450 if (ch == '\n' || ch == '\r')
11451 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011453 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011454 if (!found)
11455 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011456
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011458 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459 if (!u)
11460 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011461 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Antoine Pitroue71d5742011-10-04 15:55:09 +020011463 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464
Antoine Pitroue71d5742011-10-04 15:55:09 +020011465 for (; i < src_len; i++) {
11466 ch = PyUnicode_READ(kind, src_data, i);
11467 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011468 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011469 incr = tabsize - (line_pos % tabsize);
11470 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011471 FILL(kind, dest_data, ' ', j, incr);
11472 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011473 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011474 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011475 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011476 line_pos++;
11477 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011478 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011479 if (ch == '\n' || ch == '\r')
11480 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011482 }
11483 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011484 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011485
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011487 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11488 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489}
11490
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011491PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011492 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493\n\
11494Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011495such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496arguments start and end are interpreted as in slice notation.\n\
11497\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011498Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499
11500static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011501unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011503 /* initialize variables to prevent gcc warning */
11504 PyObject *substring = NULL;
11505 Py_ssize_t start = 0;
11506 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011507 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011509 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011512 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011515 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 if (result == -2)
11518 return NULL;
11519
Christian Heimes217cfd12007-12-02 14:31:20 +000011520 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521}
11522
11523static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011524unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011526 void *data;
11527 enum PyUnicode_Kind kind;
11528 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011529
11530 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11531 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011532 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011533 }
11534 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11535 PyErr_SetString(PyExc_IndexError, "string index out of range");
11536 return NULL;
11537 }
11538 kind = PyUnicode_KIND(self);
11539 data = PyUnicode_DATA(self);
11540 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011541 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011542}
11543
Guido van Rossumc2504932007-09-18 19:42:40 +000011544/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011545 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011546static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011547unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548{
Guido van Rossumc2504932007-09-18 19:42:40 +000011549 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011550 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011551
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011552#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011553 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011554#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011555 if (_PyUnicode_HASH(self) != -1)
11556 return _PyUnicode_HASH(self);
11557 if (PyUnicode_READY(self) == -1)
11558 return -1;
11559 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011560 /*
11561 We make the hash of the empty string be 0, rather than using
11562 (prefix ^ suffix), since this slightly obfuscates the hash secret
11563 */
11564 if (len == 0) {
11565 _PyUnicode_HASH(self) = 0;
11566 return 0;
11567 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011568 x = _Py_HashBytes(PyUnicode_DATA(self),
11569 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011570 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011571 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572}
11573
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011574PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011575 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011577Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578
11579static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011582 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011583 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011584 PyObject *substring = NULL;
11585 Py_ssize_t start = 0;
11586 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011588 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011591 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011592 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011593
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011594 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011595
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 if (result == -2)
11597 return NULL;
11598
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599 if (result < 0) {
11600 PyErr_SetString(PyExc_ValueError, "substring not found");
11601 return NULL;
11602 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011603
Christian Heimes217cfd12007-12-02 14:31:20 +000011604 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605}
11606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011607PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011608 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011610Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011611at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612
11613static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011614unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616 Py_ssize_t i, length;
11617 int kind;
11618 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619 int cased;
11620
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 if (PyUnicode_READY(self) == -1)
11622 return NULL;
11623 length = PyUnicode_GET_LENGTH(self);
11624 kind = PyUnicode_KIND(self);
11625 data = PyUnicode_DATA(self);
11626
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628 if (length == 1)
11629 return PyBool_FromLong(
11630 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011632 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011634 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011635
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011637 for (i = 0; i < length; i++) {
11638 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011639
Benjamin Peterson29060642009-01-31 22:14:21 +000011640 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11641 return PyBool_FromLong(0);
11642 else if (!cased && Py_UNICODE_ISLOWER(ch))
11643 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011645 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646}
11647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011648PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011649 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011650\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011651Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011652at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011653
11654static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011655unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011656{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011657 Py_ssize_t i, length;
11658 int kind;
11659 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660 int cased;
11661
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 if (PyUnicode_READY(self) == -1)
11663 return NULL;
11664 length = PyUnicode_GET_LENGTH(self);
11665 kind = PyUnicode_KIND(self);
11666 data = PyUnicode_DATA(self);
11667
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669 if (length == 1)
11670 return PyBool_FromLong(
11671 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011673 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011675 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011676
Guido van Rossumd57fd912000-03-10 22:53:23 +000011677 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011678 for (i = 0; i < length; i++) {
11679 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011680
Benjamin Peterson29060642009-01-31 22:14:21 +000011681 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11682 return PyBool_FromLong(0);
11683 else if (!cased && Py_UNICODE_ISUPPER(ch))
11684 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011685 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011686 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687}
11688
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011689PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011690 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011692Return True if S is a titlecased string and there is at least one\n\
11693character in S, i.e. upper- and titlecase characters may only\n\
11694follow uncased characters and lowercase characters only cased ones.\n\
11695Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696
11697static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011698unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700 Py_ssize_t i, length;
11701 int kind;
11702 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703 int cased, previous_is_cased;
11704
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 if (PyUnicode_READY(self) == -1)
11706 return NULL;
11707 length = PyUnicode_GET_LENGTH(self);
11708 kind = PyUnicode_KIND(self);
11709 data = PyUnicode_DATA(self);
11710
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 if (length == 1) {
11713 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11714 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11715 (Py_UNICODE_ISUPPER(ch) != 0));
11716 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011718 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011720 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011721
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722 cased = 0;
11723 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011724 for (i = 0; i < length; i++) {
11725 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011726
Benjamin Peterson29060642009-01-31 22:14:21 +000011727 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11728 if (previous_is_cased)
11729 return PyBool_FromLong(0);
11730 previous_is_cased = 1;
11731 cased = 1;
11732 }
11733 else if (Py_UNICODE_ISLOWER(ch)) {
11734 if (!previous_is_cased)
11735 return PyBool_FromLong(0);
11736 previous_is_cased = 1;
11737 cased = 1;
11738 }
11739 else
11740 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011742 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011743}
11744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011745PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011746 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011748Return True if all characters in S are whitespace\n\
11749and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750
11751static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011752unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011753{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754 Py_ssize_t i, length;
11755 int kind;
11756 void *data;
11757
11758 if (PyUnicode_READY(self) == -1)
11759 return NULL;
11760 length = PyUnicode_GET_LENGTH(self);
11761 kind = PyUnicode_KIND(self);
11762 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 if (length == 1)
11766 return PyBool_FromLong(
11767 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011769 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011771 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011772
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011773 for (i = 0; i < length; i++) {
11774 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011775 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011776 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011778 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779}
11780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011781PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011782 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011783\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011784Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011785and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011786
11787static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011788unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011789{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011790 Py_ssize_t i, length;
11791 int kind;
11792 void *data;
11793
11794 if (PyUnicode_READY(self) == -1)
11795 return NULL;
11796 length = PyUnicode_GET_LENGTH(self);
11797 kind = PyUnicode_KIND(self);
11798 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011799
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011800 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 if (length == 1)
11802 return PyBool_FromLong(
11803 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011804
11805 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011807 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011808
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011809 for (i = 0; i < length; i++) {
11810 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011811 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011812 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011813 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011814}
11815
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011816PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011818\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011819Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011820and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011821
11822static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011823unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011824{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 int kind;
11826 void *data;
11827 Py_ssize_t len, i;
11828
11829 if (PyUnicode_READY(self) == -1)
11830 return NULL;
11831
11832 kind = PyUnicode_KIND(self);
11833 data = PyUnicode_DATA(self);
11834 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011835
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011836 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011837 if (len == 1) {
11838 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11839 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11840 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011841
11842 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011843 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011844 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 for (i = 0; i < len; i++) {
11847 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011848 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011849 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011850 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011851 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011852}
11853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011854PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011855 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011857Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011858False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011859
11860static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011861unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 Py_ssize_t i, length;
11864 int kind;
11865 void *data;
11866
11867 if (PyUnicode_READY(self) == -1)
11868 return NULL;
11869 length = PyUnicode_GET_LENGTH(self);
11870 kind = PyUnicode_KIND(self);
11871 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011874 if (length == 1)
11875 return PyBool_FromLong(
11876 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011878 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011880 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 for (i = 0; i < length; i++) {
11883 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011884 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011886 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887}
11888
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011889PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011890 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011892Return True if all characters in S are digits\n\
11893and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894
11895static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011896unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011898 Py_ssize_t i, length;
11899 int kind;
11900 void *data;
11901
11902 if (PyUnicode_READY(self) == -1)
11903 return NULL;
11904 length = PyUnicode_GET_LENGTH(self);
11905 kind = PyUnicode_KIND(self);
11906 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011907
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 if (length == 1) {
11910 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11911 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11912 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011914 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011916 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011917
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 for (i = 0; i < length; i++) {
11919 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011920 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011922 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923}
11924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011925PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011926 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011928Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011929False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930
11931static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011932unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011934 Py_ssize_t i, length;
11935 int kind;
11936 void *data;
11937
11938 if (PyUnicode_READY(self) == -1)
11939 return NULL;
11940 length = PyUnicode_GET_LENGTH(self);
11941 kind = PyUnicode_KIND(self);
11942 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943
Guido van Rossumd57fd912000-03-10 22:53:23 +000011944 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011945 if (length == 1)
11946 return PyBool_FromLong(
11947 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011949 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011950 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011951 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011952
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 for (i = 0; i < length; i++) {
11954 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011955 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011956 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011957 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958}
11959
Martin v. Löwis47383402007-08-15 07:32:56 +000011960int
11961PyUnicode_IsIdentifier(PyObject *self)
11962{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011963 int kind;
11964 void *data;
11965 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011966 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 if (PyUnicode_READY(self) == -1) {
11969 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011970 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011971 }
11972
11973 /* Special case for empty strings */
11974 if (PyUnicode_GET_LENGTH(self) == 0)
11975 return 0;
11976 kind = PyUnicode_KIND(self);
11977 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011978
11979 /* PEP 3131 says that the first character must be in
11980 XID_Start and subsequent characters in XID_Continue,
11981 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011982 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011983 letters, digits, underscore). However, given the current
11984 definition of XID_Start and XID_Continue, it is sufficient
11985 to check just for these, except that _ must be allowed
11986 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011987 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011988 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011989 return 0;
11990
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011991 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011993 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011994 return 1;
11995}
11996
11997PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011998 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011999\n\
12000Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012001to the language definition.\n\
12002\n\
12003Use keyword.iskeyword() to test for reserved identifiers\n\
12004such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012005
12006static PyObject*
12007unicode_isidentifier(PyObject *self)
12008{
12009 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12010}
12011
Georg Brandl559e5d72008-06-11 18:37:52 +000012012PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012013 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012014\n\
12015Return True if all characters in S are considered\n\
12016printable in repr() or S is empty, False otherwise.");
12017
12018static PyObject*
12019unicode_isprintable(PyObject *self)
12020{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 Py_ssize_t i, length;
12022 int kind;
12023 void *data;
12024
12025 if (PyUnicode_READY(self) == -1)
12026 return NULL;
12027 length = PyUnicode_GET_LENGTH(self);
12028 kind = PyUnicode_KIND(self);
12029 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012030
12031 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012032 if (length == 1)
12033 return PyBool_FromLong(
12034 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012035
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036 for (i = 0; i < length; i++) {
12037 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012038 Py_RETURN_FALSE;
12039 }
12040 }
12041 Py_RETURN_TRUE;
12042}
12043
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012044PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012045 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046\n\
12047Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012048iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012049
12050static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012051unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012052{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012053 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012054}
12055
Martin v. Löwis18e16552006-02-15 17:27:45 +000012056static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012057unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012058{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012059 if (PyUnicode_READY(self) == -1)
12060 return -1;
12061 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062}
12063
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012064PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012065 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012066\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012067Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012068done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012069
12070static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012071unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012072{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012073 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012074 Py_UCS4 fillchar = ' ';
12075
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012076 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012077 return NULL;
12078
Benjamin Petersonbac79492012-01-14 13:34:47 -050012079 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012080 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012081
Victor Stinnerc4b49542011-12-11 22:44:26 +010012082 if (PyUnicode_GET_LENGTH(self) >= width)
12083 return unicode_result_unchanged(self);
12084
12085 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086}
12087
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012088PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012089 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012091Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092
12093static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012094unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012096 if (PyUnicode_READY(self) == -1)
12097 return NULL;
12098 if (PyUnicode_IS_ASCII(self))
12099 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012100 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101}
12102
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012103#define LEFTSTRIP 0
12104#define RIGHTSTRIP 1
12105#define BOTHSTRIP 2
12106
12107/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012108static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012109
12110#define STRIPNAME(i) (stripformat[i]+3)
12111
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012112/* externally visible for str.strip(unicode) */
12113PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012114_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012115{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012116 void *data;
12117 int kind;
12118 Py_ssize_t i, j, len;
12119 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012120 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012121
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012122 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12123 return NULL;
12124
12125 kind = PyUnicode_KIND(self);
12126 data = PyUnicode_DATA(self);
12127 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012128 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012129 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12130 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012131 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012132
Benjamin Peterson14339b62009-01-31 16:36:08 +000012133 i = 0;
12134 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012135 while (i < len) {
12136 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12137 if (!BLOOM(sepmask, ch))
12138 break;
12139 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12140 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012141 i++;
12142 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012143 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012144
Benjamin Peterson14339b62009-01-31 16:36:08 +000012145 j = len;
12146 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012147 j--;
12148 while (j >= i) {
12149 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12150 if (!BLOOM(sepmask, ch))
12151 break;
12152 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12153 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012154 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012155 }
12156
Benjamin Peterson29060642009-01-31 22:14:21 +000012157 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012158 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012159
Victor Stinner7931d9a2011-11-04 00:22:48 +010012160 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012161}
12162
12163PyObject*
12164PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12165{
12166 unsigned char *data;
12167 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012168 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012169
Victor Stinnerde636f32011-10-01 03:55:54 +020012170 if (PyUnicode_READY(self) == -1)
12171 return NULL;
12172
Victor Stinner684d5fd2012-05-03 02:32:34 +020012173 length = PyUnicode_GET_LENGTH(self);
12174 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012175
Victor Stinner684d5fd2012-05-03 02:32:34 +020012176 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012177 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012178
Victor Stinnerde636f32011-10-01 03:55:54 +020012179 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012180 PyErr_SetString(PyExc_IndexError, "string index out of range");
12181 return NULL;
12182 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012183 if (start >= length || end < start)
12184 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012185
Victor Stinner684d5fd2012-05-03 02:32:34 +020012186 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012187 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012188 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012189 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012190 }
12191 else {
12192 kind = PyUnicode_KIND(self);
12193 data = PyUnicode_1BYTE_DATA(self);
12194 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012195 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012196 length);
12197 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012198}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199
12200static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012201do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 Py_ssize_t len, i, j;
12204
12205 if (PyUnicode_READY(self) == -1)
12206 return NULL;
12207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012208 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012209
Victor Stinnercc7af722013-04-09 22:39:24 +020012210 if (PyUnicode_IS_ASCII(self)) {
12211 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12212
12213 i = 0;
12214 if (striptype != RIGHTSTRIP) {
12215 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012216 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012217 if (!_Py_ascii_whitespace[ch])
12218 break;
12219 i++;
12220 }
12221 }
12222
12223 j = len;
12224 if (striptype != LEFTSTRIP) {
12225 j--;
12226 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012227 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012228 if (!_Py_ascii_whitespace[ch])
12229 break;
12230 j--;
12231 }
12232 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012233 }
12234 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012235 else {
12236 int kind = PyUnicode_KIND(self);
12237 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012238
Victor Stinnercc7af722013-04-09 22:39:24 +020012239 i = 0;
12240 if (striptype != RIGHTSTRIP) {
12241 while (i < len) {
12242 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12243 if (!Py_UNICODE_ISSPACE(ch))
12244 break;
12245 i++;
12246 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012247 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012248
12249 j = len;
12250 if (striptype != LEFTSTRIP) {
12251 j--;
12252 while (j >= i) {
12253 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12254 if (!Py_UNICODE_ISSPACE(ch))
12255 break;
12256 j--;
12257 }
12258 j++;
12259 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012260 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012261
Victor Stinner7931d9a2011-11-04 00:22:48 +010012262 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263}
12264
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012265
12266static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012267do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012268{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012269 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012270
Serhiy Storchakac6792272013-10-19 21:03:34 +030012271 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012272 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012273
Benjamin Peterson14339b62009-01-31 16:36:08 +000012274 if (sep != NULL && sep != Py_None) {
12275 if (PyUnicode_Check(sep))
12276 return _PyUnicode_XStrip(self, striptype, sep);
12277 else {
12278 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012279 "%s arg must be None or str",
12280 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012281 return NULL;
12282 }
12283 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012284
Benjamin Peterson14339b62009-01-31 16:36:08 +000012285 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012286}
12287
12288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012289PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012290 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012291\n\
12292Return a copy of the string S with leading and trailing\n\
12293whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012294If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012295
12296static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012297unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012298{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012299 if (PyTuple_GET_SIZE(args) == 0)
12300 return do_strip(self, BOTHSTRIP); /* Common case */
12301 else
12302 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012303}
12304
12305
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012306PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012307 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012308\n\
12309Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012310If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012311
12312static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012313unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012314{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012315 if (PyTuple_GET_SIZE(args) == 0)
12316 return do_strip(self, LEFTSTRIP); /* Common case */
12317 else
12318 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012319}
12320
12321
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012322PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012323 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012324\n\
12325Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012326If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012327
12328static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012329unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012330{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012331 if (PyTuple_GET_SIZE(args) == 0)
12332 return do_strip(self, RIGHTSTRIP); /* Common case */
12333 else
12334 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012335}
12336
12337
Guido van Rossumd57fd912000-03-10 22:53:23 +000012338static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012339unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012340{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012341 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012342 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012343
Serhiy Storchaka05997252013-01-26 12:14:02 +020012344 if (len < 1)
12345 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012346
Victor Stinnerc4b49542011-12-11 22:44:26 +010012347 /* no repeat, return original string */
12348 if (len == 1)
12349 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012350
Benjamin Petersonbac79492012-01-14 13:34:47 -050012351 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 return NULL;
12353
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012354 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012355 PyErr_SetString(PyExc_OverflowError,
12356 "repeated string is too long");
12357 return NULL;
12358 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012359 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012360
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012361 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012362 if (!u)
12363 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012364 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 if (PyUnicode_GET_LENGTH(str) == 1) {
12367 const int kind = PyUnicode_KIND(str);
12368 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012369 if (kind == PyUnicode_1BYTE_KIND) {
12370 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012371 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012372 }
12373 else if (kind == PyUnicode_2BYTE_KIND) {
12374 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012375 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012376 ucs2[n] = fill_char;
12377 } else {
12378 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12379 assert(kind == PyUnicode_4BYTE_KIND);
12380 for (n = 0; n < len; ++n)
12381 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012382 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012383 }
12384 else {
12385 /* number of characters copied this far */
12386 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012387 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012388 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012389 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012390 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012391 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012392 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012393 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012394 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012395 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012396 }
12397
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012398 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012399 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012400}
12401
Alexander Belopolsky40018472011-02-26 01:02:56 +000012402PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012403PyUnicode_Replace(PyObject *str,
12404 PyObject *substr,
12405 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012406 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012407{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012408 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12409 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012410 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012411 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012412}
12413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012414PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012415 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012416\n\
12417Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012418old replaced by new. If the optional argument count is\n\
12419given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012420
12421static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012423{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012424 PyObject *str1;
12425 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012426 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012427
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012428 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012429 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012430 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012431 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012432 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012433}
12434
Alexander Belopolsky40018472011-02-26 01:02:56 +000012435static PyObject *
12436unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012437{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012438 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012439 Py_ssize_t isize;
12440 Py_ssize_t osize, squote, dquote, i, o;
12441 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012442 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012446 return NULL;
12447
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 isize = PyUnicode_GET_LENGTH(unicode);
12449 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012450
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012451 /* Compute length of output, quote characters, and
12452 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012453 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012454 max = 127;
12455 squote = dquote = 0;
12456 ikind = PyUnicode_KIND(unicode);
12457 for (i = 0; i < isize; i++) {
12458 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012459 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012460 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012461 case '\'': squote++; break;
12462 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012463 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012464 incr = 2;
12465 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012466 default:
12467 /* Fast-path ASCII */
12468 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012469 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012470 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012471 ;
12472 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012474 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012475 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012477 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012478 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012479 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012481 if (osize > PY_SSIZE_T_MAX - incr) {
12482 PyErr_SetString(PyExc_OverflowError,
12483 "string is too long to generate repr");
12484 return NULL;
12485 }
12486 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012487 }
12488
12489 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012490 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012491 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012492 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012493 if (dquote)
12494 /* Both squote and dquote present. Use squote,
12495 and escape them */
12496 osize += squote;
12497 else
12498 quote = '"';
12499 }
Victor Stinner55c08782013-04-14 18:45:39 +020012500 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012501
12502 repr = PyUnicode_New(osize, max);
12503 if (repr == NULL)
12504 return NULL;
12505 okind = PyUnicode_KIND(repr);
12506 odata = PyUnicode_DATA(repr);
12507
12508 PyUnicode_WRITE(okind, odata, 0, quote);
12509 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012510 if (unchanged) {
12511 _PyUnicode_FastCopyCharacters(repr, 1,
12512 unicode, 0,
12513 isize);
12514 }
12515 else {
12516 for (i = 0, o = 1; i < isize; i++) {
12517 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012518
Victor Stinner55c08782013-04-14 18:45:39 +020012519 /* Escape quotes and backslashes */
12520 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012521 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012522 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012523 continue;
12524 }
12525
12526 /* Map special whitespace to '\t', \n', '\r' */
12527 if (ch == '\t') {
12528 PyUnicode_WRITE(okind, odata, o++, '\\');
12529 PyUnicode_WRITE(okind, odata, o++, 't');
12530 }
12531 else if (ch == '\n') {
12532 PyUnicode_WRITE(okind, odata, o++, '\\');
12533 PyUnicode_WRITE(okind, odata, o++, 'n');
12534 }
12535 else if (ch == '\r') {
12536 PyUnicode_WRITE(okind, odata, o++, '\\');
12537 PyUnicode_WRITE(okind, odata, o++, 'r');
12538 }
12539
12540 /* Map non-printable US ASCII to '\xhh' */
12541 else if (ch < ' ' || ch == 0x7F) {
12542 PyUnicode_WRITE(okind, odata, o++, '\\');
12543 PyUnicode_WRITE(okind, odata, o++, 'x');
12544 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12545 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12546 }
12547
12548 /* Copy ASCII characters as-is */
12549 else if (ch < 0x7F) {
12550 PyUnicode_WRITE(okind, odata, o++, ch);
12551 }
12552
12553 /* Non-ASCII characters */
12554 else {
12555 /* Map Unicode whitespace and control characters
12556 (categories Z* and C* except ASCII space)
12557 */
12558 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12559 PyUnicode_WRITE(okind, odata, o++, '\\');
12560 /* Map 8-bit characters to '\xhh' */
12561 if (ch <= 0xff) {
12562 PyUnicode_WRITE(okind, odata, o++, 'x');
12563 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12564 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12565 }
12566 /* Map 16-bit characters to '\uxxxx' */
12567 else if (ch <= 0xffff) {
12568 PyUnicode_WRITE(okind, odata, o++, 'u');
12569 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12570 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12571 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12572 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12573 }
12574 /* Map 21-bit characters to '\U00xxxxxx' */
12575 else {
12576 PyUnicode_WRITE(okind, odata, o++, 'U');
12577 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12578 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12579 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12580 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12581 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12582 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12583 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12584 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12585 }
12586 }
12587 /* Copy characters as-is */
12588 else {
12589 PyUnicode_WRITE(okind, odata, o++, ch);
12590 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012591 }
12592 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012593 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012594 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012595 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012596 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012597}
12598
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012599PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012600 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012601\n\
12602Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012603such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012604arguments start and end are interpreted as in slice notation.\n\
12605\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012606Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012607
12608static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012609unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012611 /* initialize variables to prevent gcc warning */
12612 PyObject *substring = NULL;
12613 Py_ssize_t start = 0;
12614 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012615 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012616
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012617 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012618 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012620 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012621 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012622
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012623 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012624
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012625 if (result == -2)
12626 return NULL;
12627
Christian Heimes217cfd12007-12-02 14:31:20 +000012628 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629}
12630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012631PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012632 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012634Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635
12636static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012637unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012639 /* initialize variables to prevent gcc warning */
12640 PyObject *substring = NULL;
12641 Py_ssize_t start = 0;
12642 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012643 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012645 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012646 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012648 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012649 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012650
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012651 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 if (result == -2)
12654 return NULL;
12655
Guido van Rossumd57fd912000-03-10 22:53:23 +000012656 if (result < 0) {
12657 PyErr_SetString(PyExc_ValueError, "substring not found");
12658 return NULL;
12659 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660
Christian Heimes217cfd12007-12-02 14:31:20 +000012661 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662}
12663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012664PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012665 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012667Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012668done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012669
12670static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012671unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012672{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012673 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012674 Py_UCS4 fillchar = ' ';
12675
Victor Stinnere9a29352011-10-01 02:14:59 +020012676 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012677 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012678
Benjamin Petersonbac79492012-01-14 13:34:47 -050012679 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680 return NULL;
12681
Victor Stinnerc4b49542011-12-11 22:44:26 +010012682 if (PyUnicode_GET_LENGTH(self) >= width)
12683 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684
Victor Stinnerc4b49542011-12-11 22:44:26 +010012685 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012686}
12687
Alexander Belopolsky40018472011-02-26 01:02:56 +000012688PyObject *
12689PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012691 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012692 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012693
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012694 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695}
12696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012697PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012698 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699\n\
12700Return a list of the words in S, using sep as the\n\
12701delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012702splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012703whitespace string is a separator and empty strings are\n\
12704removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705
12706static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012707unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012709 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012710 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012711 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012713 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12714 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012715 return NULL;
12716
12717 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012718 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012719
12720 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012721 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012722
12723 PyErr_Format(PyExc_TypeError,
12724 "must be str or None, not %.100s",
12725 Py_TYPE(substring)->tp_name);
12726 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012727}
12728
Thomas Wouters477c8d52006-05-27 19:21:47 +000012729PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012730PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012731{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012732 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012733 int kind1, kind2;
12734 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012735 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012736
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012737 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012738 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012739
Victor Stinner14f8f022011-10-05 20:58:25 +020012740 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012741 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012742 len1 = PyUnicode_GET_LENGTH(str_obj);
12743 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012744 if (kind1 < kind2 || len1 < len2) {
12745 _Py_INCREF_UNICODE_EMPTY();
12746 if (!unicode_empty)
12747 out = NULL;
12748 else {
12749 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12750 Py_DECREF(unicode_empty);
12751 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012752 return out;
12753 }
12754 buf1 = PyUnicode_DATA(str_obj);
12755 buf2 = PyUnicode_DATA(sep_obj);
12756 if (kind2 != kind1) {
12757 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12758 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012759 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012760 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012761
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012762 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012763 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012764 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12765 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12766 else
12767 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012768 break;
12769 case PyUnicode_2BYTE_KIND:
12770 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12771 break;
12772 case PyUnicode_4BYTE_KIND:
12773 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12774 break;
12775 default:
12776 assert(0);
12777 out = 0;
12778 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012779
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012780 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012781 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012782
12783 return out;
12784}
12785
12786
12787PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012788PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012789{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012790 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012791 int kind1, kind2;
12792 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012793 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012794
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012795 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012796 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012797
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012798 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012799 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012800 len1 = PyUnicode_GET_LENGTH(str_obj);
12801 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012802 if (kind1 < kind2 || len1 < len2) {
12803 _Py_INCREF_UNICODE_EMPTY();
12804 if (!unicode_empty)
12805 out = NULL;
12806 else {
12807 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12808 Py_DECREF(unicode_empty);
12809 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012810 return out;
12811 }
12812 buf1 = PyUnicode_DATA(str_obj);
12813 buf2 = PyUnicode_DATA(sep_obj);
12814 if (kind2 != kind1) {
12815 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12816 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012817 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012818 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012819
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012820 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012821 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012822 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12823 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12824 else
12825 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012826 break;
12827 case PyUnicode_2BYTE_KIND:
12828 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12829 break;
12830 case PyUnicode_4BYTE_KIND:
12831 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12832 break;
12833 default:
12834 assert(0);
12835 out = 0;
12836 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012837
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012838 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012839 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012840
12841 return out;
12842}
12843
12844PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012845 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012846\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012847Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012848the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012849found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012850
12851static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012852unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012853{
Victor Stinner9310abb2011-10-05 00:59:23 +020012854 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012855}
12856
12857PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012858 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012859\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012860Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012861the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012862separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012863
12864static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012865unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012866{
Victor Stinner9310abb2011-10-05 00:59:23 +020012867 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012868}
12869
Alexander Belopolsky40018472011-02-26 01:02:56 +000012870PyObject *
12871PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012872{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012873 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012874 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012875
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012876 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012877}
12878
12879PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012880 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012881\n\
12882Return a list of the words in S, using sep as the\n\
12883delimiter string, starting at the end of the string and\n\
12884working to the front. If maxsplit is given, at most maxsplit\n\
12885splits are done. If sep is not specified, any whitespace string\n\
12886is a separator.");
12887
12888static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012889unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012890{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012891 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012892 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012893 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012894
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012895 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12896 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012897 return NULL;
12898
12899 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012900 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012901
12902 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012903 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012904
12905 PyErr_Format(PyExc_TypeError,
12906 "must be str or None, not %.100s",
12907 Py_TYPE(substring)->tp_name);
12908 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012909}
12910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012911PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012912 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012913\n\
12914Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012915Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012916is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012917
12918static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012919unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012921 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012922 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012923
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012924 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12925 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012926 return NULL;
12927
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012928 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012929}
12930
12931static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012932PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012933{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012934 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012935}
12936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012937PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012938 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012939\n\
12940Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012941and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012942
12943static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012944unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012945{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012946 if (PyUnicode_READY(self) == -1)
12947 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012948 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012949}
12950
Larry Hastings61272b72014-01-07 12:41:53 -080012951/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012952
Larry Hastings31826802013-10-19 00:09:25 -070012953@staticmethod
12954str.maketrans as unicode_maketrans
12955
12956 x: object
12957
12958 y: unicode=NULL
12959
12960 z: unicode=NULL
12961
12962 /
12963
12964Return a translation table usable for str.translate().
12965
12966If there is only one argument, it must be a dictionary mapping Unicode
12967ordinals (integers) or characters to Unicode ordinals, strings or None.
12968Character keys will be then converted to ordinals.
12969If there are two arguments, they must be strings of equal length, and
12970in the resulting dictionary, each character in x will be mapped to the
12971character at the same position in y. If there is a third argument, it
12972must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012973[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012974
Larry Hastings31826802013-10-19 00:09:25 -070012975static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012976unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012977/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012978{
Georg Brandlceee0772007-11-27 23:48:05 +000012979 PyObject *new = NULL, *key, *value;
12980 Py_ssize_t i = 0;
12981 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012982
Georg Brandlceee0772007-11-27 23:48:05 +000012983 new = PyDict_New();
12984 if (!new)
12985 return NULL;
12986 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012987 int x_kind, y_kind, z_kind;
12988 void *x_data, *y_data, *z_data;
12989
Georg Brandlceee0772007-11-27 23:48:05 +000012990 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012991 if (!PyUnicode_Check(x)) {
12992 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12993 "be a string if there is a second argument");
12994 goto err;
12995 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012996 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012997 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12998 "arguments must have equal length");
12999 goto err;
13000 }
13001 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 x_kind = PyUnicode_KIND(x);
13003 y_kind = PyUnicode_KIND(y);
13004 x_data = PyUnicode_DATA(x);
13005 y_data = PyUnicode_DATA(y);
13006 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13007 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013008 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013009 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013010 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013011 if (!value) {
13012 Py_DECREF(key);
13013 goto err;
13014 }
Georg Brandlceee0772007-11-27 23:48:05 +000013015 res = PyDict_SetItem(new, key, value);
13016 Py_DECREF(key);
13017 Py_DECREF(value);
13018 if (res < 0)
13019 goto err;
13020 }
13021 /* create entries for deleting chars in z */
13022 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 z_kind = PyUnicode_KIND(z);
13024 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013025 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013026 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013027 if (!key)
13028 goto err;
13029 res = PyDict_SetItem(new, key, Py_None);
13030 Py_DECREF(key);
13031 if (res < 0)
13032 goto err;
13033 }
13034 }
13035 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013036 int kind;
13037 void *data;
13038
Georg Brandlceee0772007-11-27 23:48:05 +000013039 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013040 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013041 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13042 "to maketrans it must be a dict");
13043 goto err;
13044 }
13045 /* copy entries into the new dict, converting string keys to int keys */
13046 while (PyDict_Next(x, &i, &key, &value)) {
13047 if (PyUnicode_Check(key)) {
13048 /* convert string keys to integer keys */
13049 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013050 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013051 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13052 "table must be of length 1");
13053 goto err;
13054 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013055 kind = PyUnicode_KIND(key);
13056 data = PyUnicode_DATA(key);
13057 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013058 if (!newkey)
13059 goto err;
13060 res = PyDict_SetItem(new, newkey, value);
13061 Py_DECREF(newkey);
13062 if (res < 0)
13063 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013064 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013065 /* just keep integer keys */
13066 if (PyDict_SetItem(new, key, value) < 0)
13067 goto err;
13068 } else {
13069 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13070 "be strings or integers");
13071 goto err;
13072 }
13073 }
13074 }
13075 return new;
13076 err:
13077 Py_DECREF(new);
13078 return NULL;
13079}
13080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013081PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013082 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013083\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013084Return a copy of the string S in which each character has been mapped\n\
13085through the given translation table. The table must implement\n\
13086lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13087mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13088this operation raises LookupError, the character is left untouched.\n\
13089Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090
13091static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013092unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013094 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095}
13096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013097PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013098 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013100Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013101
13102static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013103unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013105 if (PyUnicode_READY(self) == -1)
13106 return NULL;
13107 if (PyUnicode_IS_ASCII(self))
13108 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013109 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110}
13111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013112PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013113 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013115Pad a numeric string S with zeros on the left, to fill a field\n\
13116of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013117
13118static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013119unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013121 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013122 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013123 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013124 int kind;
13125 void *data;
13126 Py_UCS4 chr;
13127
Martin v. Löwis18e16552006-02-15 17:27:45 +000013128 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013129 return NULL;
13130
Benjamin Petersonbac79492012-01-14 13:34:47 -050013131 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013132 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013133
Victor Stinnerc4b49542011-12-11 22:44:26 +010013134 if (PyUnicode_GET_LENGTH(self) >= width)
13135 return unicode_result_unchanged(self);
13136
13137 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013138
13139 u = pad(self, fill, 0, '0');
13140
Walter Dörwald068325e2002-04-15 13:36:47 +000013141 if (u == NULL)
13142 return NULL;
13143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 kind = PyUnicode_KIND(u);
13145 data = PyUnicode_DATA(u);
13146 chr = PyUnicode_READ(kind, data, fill);
13147
13148 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013149 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013150 PyUnicode_WRITE(kind, data, 0, chr);
13151 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152 }
13153
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013154 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013155 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013156}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013157
13158#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013159static PyObject *
13160unicode__decimal2ascii(PyObject *self)
13161{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013162 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013163}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013164#endif
13165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013166PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013167 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013169Return True if S starts with the specified prefix, False otherwise.\n\
13170With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013171With optional end, stop comparing S at that position.\n\
13172prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013173
13174static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013175unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013176 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013178 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013179 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013180 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013181 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013182 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183
Jesus Ceaac451502011-04-20 17:09:23 +020013184 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013185 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013186 if (PyTuple_Check(subobj)) {
13187 Py_ssize_t i;
13188 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013189 substring = PyTuple_GET_ITEM(subobj, i);
13190 if (!PyUnicode_Check(substring)) {
13191 PyErr_Format(PyExc_TypeError,
13192 "tuple for startswith must only contain str, "
13193 "not %.100s",
13194 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013195 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013196 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013197 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013198 if (result == -1)
13199 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013200 if (result) {
13201 Py_RETURN_TRUE;
13202 }
13203 }
13204 /* nothing matched */
13205 Py_RETURN_FALSE;
13206 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013207 if (!PyUnicode_Check(subobj)) {
13208 PyErr_Format(PyExc_TypeError,
13209 "startswith first arg must be str or "
13210 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013211 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013212 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013213 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013214 if (result == -1)
13215 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013216 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013217}
13218
13219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013220PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013221 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013222\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013223Return True if S ends with the specified suffix, False otherwise.\n\
13224With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013225With optional end, stop comparing S at that position.\n\
13226suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227
13228static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013229unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013230 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013232 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013233 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013234 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013235 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013236 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237
Jesus Ceaac451502011-04-20 17:09:23 +020013238 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013240 if (PyTuple_Check(subobj)) {
13241 Py_ssize_t i;
13242 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013243 substring = PyTuple_GET_ITEM(subobj, i);
13244 if (!PyUnicode_Check(substring)) {
13245 PyErr_Format(PyExc_TypeError,
13246 "tuple for endswith must only contain str, "
13247 "not %.100s",
13248 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013249 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013250 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013251 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013252 if (result == -1)
13253 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013254 if (result) {
13255 Py_RETURN_TRUE;
13256 }
13257 }
13258 Py_RETURN_FALSE;
13259 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013260 if (!PyUnicode_Check(subobj)) {
13261 PyErr_Format(PyExc_TypeError,
13262 "endswith first arg must be str or "
13263 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013264 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013265 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013266 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013267 if (result == -1)
13268 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013269 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270}
13271
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013272static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013273_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013274{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013275 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13276 writer->data = PyUnicode_DATA(writer->buffer);
13277
13278 if (!writer->readonly) {
13279 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013280 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013281 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013282 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013283 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13284 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13285 writer->kind = PyUnicode_WCHAR_KIND;
13286 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13287
Victor Stinner8f674cc2013-04-17 23:02:17 +020013288 /* Copy-on-write mode: set buffer size to 0 so
13289 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13290 * next write. */
13291 writer->size = 0;
13292 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013293}
13294
Victor Stinnerd3f08822012-05-29 12:57:52 +020013295void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013296_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013297{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013298 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013299
13300 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013301 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013302
13303 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13304 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13305 writer->kind = PyUnicode_WCHAR_KIND;
13306 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013307}
13308
Victor Stinnerd3f08822012-05-29 12:57:52 +020013309int
13310_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13311 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013312{
13313 Py_ssize_t newlen;
13314 PyObject *newbuffer;
13315
Victor Stinner2740e462016-09-06 16:58:36 -070013316 assert(maxchar <= MAX_UNICODE);
13317
Victor Stinnerca9381e2015-09-22 00:58:32 +020013318 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013319 assert((maxchar > writer->maxchar && length >= 0)
13320 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013321
Victor Stinner202fdca2012-05-07 12:47:02 +020013322 if (length > PY_SSIZE_T_MAX - writer->pos) {
13323 PyErr_NoMemory();
13324 return -1;
13325 }
13326 newlen = writer->pos + length;
13327
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013328 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013329
Victor Stinnerd3f08822012-05-29 12:57:52 +020013330 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013331 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013332 if (writer->overallocate
13333 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13334 /* overallocate to limit the number of realloc() */
13335 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013336 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013337 if (newlen < writer->min_length)
13338 newlen = writer->min_length;
13339
Victor Stinnerd3f08822012-05-29 12:57:52 +020013340 writer->buffer = PyUnicode_New(newlen, maxchar);
13341 if (writer->buffer == NULL)
13342 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013343 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013344 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013345 if (writer->overallocate
13346 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13347 /* overallocate to limit the number of realloc() */
13348 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013349 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013350 if (newlen < writer->min_length)
13351 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013352
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013353 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013354 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013355 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013356 newbuffer = PyUnicode_New(newlen, maxchar);
13357 if (newbuffer == NULL)
13358 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013359 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13360 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013361 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013362 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013363 }
13364 else {
13365 newbuffer = resize_compact(writer->buffer, newlen);
13366 if (newbuffer == NULL)
13367 return -1;
13368 }
13369 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013370 }
13371 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013372 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013373 newbuffer = PyUnicode_New(writer->size, maxchar);
13374 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013375 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013376 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13377 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013378 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013379 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013380 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013381 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013382
13383#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013384}
13385
Victor Stinnerca9381e2015-09-22 00:58:32 +020013386int
13387_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13388 enum PyUnicode_Kind kind)
13389{
13390 Py_UCS4 maxchar;
13391
13392 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13393 assert(writer->kind < kind);
13394
13395 switch (kind)
13396 {
13397 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13398 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13399 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13400 default:
13401 assert(0 && "invalid kind");
13402 return -1;
13403 }
13404
13405 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13406}
13407
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013408static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013409_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013410{
Victor Stinner2740e462016-09-06 16:58:36 -070013411 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013412 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13413 return -1;
13414 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13415 writer->pos++;
13416 return 0;
13417}
13418
13419int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013420_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13421{
13422 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13423}
13424
13425int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013426_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13427{
13428 Py_UCS4 maxchar;
13429 Py_ssize_t len;
13430
13431 if (PyUnicode_READY(str) == -1)
13432 return -1;
13433 len = PyUnicode_GET_LENGTH(str);
13434 if (len == 0)
13435 return 0;
13436 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13437 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013438 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013439 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013440 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013441 Py_INCREF(str);
13442 writer->buffer = str;
13443 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013444 writer->pos += len;
13445 return 0;
13446 }
13447 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13448 return -1;
13449 }
13450 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13451 str, 0, len);
13452 writer->pos += len;
13453 return 0;
13454}
13455
Victor Stinnere215d962012-10-06 23:03:36 +020013456int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013457_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13458 Py_ssize_t start, Py_ssize_t end)
13459{
13460 Py_UCS4 maxchar;
13461 Py_ssize_t len;
13462
13463 if (PyUnicode_READY(str) == -1)
13464 return -1;
13465
13466 assert(0 <= start);
13467 assert(end <= PyUnicode_GET_LENGTH(str));
13468 assert(start <= end);
13469
13470 if (end == 0)
13471 return 0;
13472
13473 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13474 return _PyUnicodeWriter_WriteStr(writer, str);
13475
13476 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13477 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13478 else
13479 maxchar = writer->maxchar;
13480 len = end - start;
13481
13482 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13483 return -1;
13484
13485 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13486 str, start, len);
13487 writer->pos += len;
13488 return 0;
13489}
13490
13491int
Victor Stinner4a587072013-11-19 12:54:53 +010013492_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13493 const char *ascii, Py_ssize_t len)
13494{
13495 if (len == -1)
13496 len = strlen(ascii);
13497
13498 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13499
13500 if (writer->buffer == NULL && !writer->overallocate) {
13501 PyObject *str;
13502
13503 str = _PyUnicode_FromASCII(ascii, len);
13504 if (str == NULL)
13505 return -1;
13506
13507 writer->readonly = 1;
13508 writer->buffer = str;
13509 _PyUnicodeWriter_Update(writer);
13510 writer->pos += len;
13511 return 0;
13512 }
13513
13514 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13515 return -1;
13516
13517 switch (writer->kind)
13518 {
13519 case PyUnicode_1BYTE_KIND:
13520 {
13521 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13522 Py_UCS1 *data = writer->data;
13523
Christian Heimesf051e432016-09-13 20:22:02 +020013524 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013525 break;
13526 }
13527 case PyUnicode_2BYTE_KIND:
13528 {
13529 _PyUnicode_CONVERT_BYTES(
13530 Py_UCS1, Py_UCS2,
13531 ascii, ascii + len,
13532 (Py_UCS2 *)writer->data + writer->pos);
13533 break;
13534 }
13535 case PyUnicode_4BYTE_KIND:
13536 {
13537 _PyUnicode_CONVERT_BYTES(
13538 Py_UCS1, Py_UCS4,
13539 ascii, ascii + len,
13540 (Py_UCS4 *)writer->data + writer->pos);
13541 break;
13542 }
13543 default:
13544 assert(0);
13545 }
13546
13547 writer->pos += len;
13548 return 0;
13549}
13550
13551int
13552_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13553 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013554{
13555 Py_UCS4 maxchar;
13556
13557 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13558 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13559 return -1;
13560 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13561 writer->pos += len;
13562 return 0;
13563}
13564
Victor Stinnerd3f08822012-05-29 12:57:52 +020013565PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013566_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013567{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013568 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013569 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013570 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013571 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013572 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013573 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013574 str = writer->buffer;
13575 writer->buffer = NULL;
13576 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13577 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013578 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013579 if (writer->pos == 0) {
13580 Py_CLEAR(writer->buffer);
13581
13582 /* Get the empty Unicode string singleton ('') */
13583 _Py_INCREF_UNICODE_EMPTY();
13584 str = unicode_empty;
Victor Stinner202fdca2012-05-07 12:47:02 +020013585 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013586 else {
13587 str = writer->buffer;
13588 writer->buffer = NULL;
13589
13590 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13591 PyObject *str2;
13592 str2 = resize_compact(str, writer->pos);
13593 if (str2 == NULL)
13594 return NULL;
13595 str = str2;
13596 }
13597 }
13598
Victor Stinner15a0bd32013-07-08 22:29:55 +020013599 assert(_PyUnicode_CheckConsistency(str, 1));
13600 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013601}
13602
Victor Stinnerd3f08822012-05-29 12:57:52 +020013603void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013604_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013605{
13606 Py_CLEAR(writer->buffer);
13607}
13608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013609#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013610
13611PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013612 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013613\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013614Return a formatted version of S, using substitutions from args and kwargs.\n\
13615The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013616
Eric Smith27bbca62010-11-04 17:06:58 +000013617PyDoc_STRVAR(format_map__doc__,
13618 "S.format_map(mapping) -> str\n\
13619\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013620Return a formatted version of S, using substitutions from mapping.\n\
13621The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013622
Eric Smith4a7d76d2008-05-30 18:10:19 +000013623static PyObject *
13624unicode__format__(PyObject* self, PyObject* args)
13625{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013626 PyObject *format_spec;
13627 _PyUnicodeWriter writer;
13628 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013629
13630 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13631 return NULL;
13632
Victor Stinnerd3f08822012-05-29 12:57:52 +020013633 if (PyUnicode_READY(self) == -1)
13634 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013635 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013636 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13637 self, format_spec, 0,
13638 PyUnicode_GET_LENGTH(format_spec));
13639 if (ret == -1) {
13640 _PyUnicodeWriter_Dealloc(&writer);
13641 return NULL;
13642 }
13643 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013644}
13645
Eric Smith8c663262007-08-25 02:26:07 +000013646PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013647 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013648\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013649Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013650
13651static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013652unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013653{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013654 Py_ssize_t size;
13655
13656 /* If it's a compact object, account for base structure +
13657 character data. */
13658 if (PyUnicode_IS_COMPACT_ASCII(v))
13659 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13660 else if (PyUnicode_IS_COMPACT(v))
13661 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013662 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013663 else {
13664 /* If it is a two-block object, account for base object, and
13665 for character block if present. */
13666 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013667 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013668 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013669 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013670 }
13671 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013672 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013673 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013674 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013675 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013676 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013677
13678 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013679}
13680
13681PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013682 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013683
13684static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013685unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013686{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013687 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013688 if (!copy)
13689 return NULL;
13690 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013691}
13692
Guido van Rossumd57fd912000-03-10 22:53:23 +000013693static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013694 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013695 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013696 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13697 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013698 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13699 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013700 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013701 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13702 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13703 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013704 {"expandtabs", (PyCFunction) unicode_expandtabs,
13705 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013706 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013707 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013708 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13709 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13710 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013711 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013712 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13713 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13714 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013715 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013716 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013717 {"splitlines", (PyCFunction) unicode_splitlines,
13718 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013719 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013720 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13721 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13722 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13723 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13724 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13725 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13726 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13727 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13728 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13729 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13730 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13731 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13732 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13733 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013734 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013735 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013736 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013737 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013738 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013739 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013740 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013741 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013742#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013743 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013744 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013745#endif
13746
Benjamin Peterson14339b62009-01-31 16:36:08 +000013747 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013748 {NULL, NULL}
13749};
13750
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013751static PyObject *
13752unicode_mod(PyObject *v, PyObject *w)
13753{
Brian Curtindfc80e32011-08-10 20:28:54 -050013754 if (!PyUnicode_Check(v))
13755 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013756 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013757}
13758
13759static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013760 0, /*nb_add*/
13761 0, /*nb_subtract*/
13762 0, /*nb_multiply*/
13763 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013764};
13765
Guido van Rossumd57fd912000-03-10 22:53:23 +000013766static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013767 (lenfunc) unicode_length, /* sq_length */
13768 PyUnicode_Concat, /* sq_concat */
13769 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13770 (ssizeargfunc) unicode_getitem, /* sq_item */
13771 0, /* sq_slice */
13772 0, /* sq_ass_item */
13773 0, /* sq_ass_slice */
13774 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013775};
13776
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013777static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013778unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013779{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013780 if (PyUnicode_READY(self) == -1)
13781 return NULL;
13782
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013783 if (PyIndex_Check(item)) {
13784 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013785 if (i == -1 && PyErr_Occurred())
13786 return NULL;
13787 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013788 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013789 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013790 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013791 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013792 PyObject *result;
13793 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013794 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013795 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013797 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013798 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013799 return NULL;
13800 }
13801
13802 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013803 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013804 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013805 slicelength == PyUnicode_GET_LENGTH(self)) {
13806 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013807 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013808 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013809 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013810 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013811 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013812 src_kind = PyUnicode_KIND(self);
13813 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013814 if (!PyUnicode_IS_ASCII(self)) {
13815 kind_limit = kind_maxchar_limit(src_kind);
13816 max_char = 0;
13817 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13818 ch = PyUnicode_READ(src_kind, src_data, cur);
13819 if (ch > max_char) {
13820 max_char = ch;
13821 if (max_char >= kind_limit)
13822 break;
13823 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013824 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013825 }
Victor Stinner55c99112011-10-13 01:17:06 +020013826 else
13827 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013828 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013829 if (result == NULL)
13830 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013831 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013832 dest_data = PyUnicode_DATA(result);
13833
13834 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013835 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13836 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013837 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013838 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013839 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013840 } else {
13841 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13842 return NULL;
13843 }
13844}
13845
13846static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013847 (lenfunc)unicode_length, /* mp_length */
13848 (binaryfunc)unicode_subscript, /* mp_subscript */
13849 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013850};
13851
Guido van Rossumd57fd912000-03-10 22:53:23 +000013852
Guido van Rossumd57fd912000-03-10 22:53:23 +000013853/* Helpers for PyUnicode_Format() */
13854
Victor Stinnera47082312012-10-04 02:19:54 +020013855struct unicode_formatter_t {
13856 PyObject *args;
13857 int args_owned;
13858 Py_ssize_t arglen, argidx;
13859 PyObject *dict;
13860
13861 enum PyUnicode_Kind fmtkind;
13862 Py_ssize_t fmtcnt, fmtpos;
13863 void *fmtdata;
13864 PyObject *fmtstr;
13865
13866 _PyUnicodeWriter writer;
13867};
13868
13869struct unicode_format_arg_t {
13870 Py_UCS4 ch;
13871 int flags;
13872 Py_ssize_t width;
13873 int prec;
13874 int sign;
13875};
13876
Guido van Rossumd57fd912000-03-10 22:53:23 +000013877static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013878unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013879{
Victor Stinnera47082312012-10-04 02:19:54 +020013880 Py_ssize_t argidx = ctx->argidx;
13881
13882 if (argidx < ctx->arglen) {
13883 ctx->argidx++;
13884 if (ctx->arglen < 0)
13885 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013886 else
Victor Stinnera47082312012-10-04 02:19:54 +020013887 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013888 }
13889 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013890 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013891 return NULL;
13892}
13893
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013894/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013895
Victor Stinnera47082312012-10-04 02:19:54 +020013896/* Format a float into the writer if the writer is not NULL, or into *p_output
13897 otherwise.
13898
13899 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013900static int
Victor Stinnera47082312012-10-04 02:19:54 +020013901formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13902 PyObject **p_output,
13903 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013904{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013905 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013906 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013907 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013908 int prec;
13909 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013910
Guido van Rossumd57fd912000-03-10 22:53:23 +000013911 x = PyFloat_AsDouble(v);
13912 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013913 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013914
Victor Stinnera47082312012-10-04 02:19:54 +020013915 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013916 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013917 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013918
Victor Stinnera47082312012-10-04 02:19:54 +020013919 if (arg->flags & F_ALT)
13920 dtoa_flags = Py_DTSF_ALT;
13921 else
13922 dtoa_flags = 0;
13923 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013924 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013925 return -1;
13926 len = strlen(p);
13927 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013928 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013929 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013930 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013931 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013932 }
13933 else
13934 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013935 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013936 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013937}
13938
Victor Stinnerd0880d52012-04-27 23:40:13 +020013939/* formatlong() emulates the format codes d, u, o, x and X, and
13940 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13941 * Python's regular ints.
13942 * Return value: a new PyUnicodeObject*, or NULL if error.
13943 * The output string is of the form
13944 * "-"? ("0x" | "0X")? digit+
13945 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13946 * set in flags. The case of hex digits will be correct,
13947 * There will be at least prec digits, zero-filled on the left if
13948 * necessary to get that many.
13949 * val object to be converted
13950 * flags bitmask of format flags; only F_ALT is looked at
13951 * prec minimum number of digits; 0-fill on left if needed
13952 * type a character in [duoxX]; u acts the same as d
13953 *
13954 * CAUTION: o, x and X conversions on regular ints can never
13955 * produce a '-' sign, but can for Python's unbounded ints.
13956 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013957PyObject *
13958_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013959{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013960 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013961 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013962 Py_ssize_t i;
13963 int sign; /* 1 if '-', else 0 */
13964 int len; /* number of characters */
13965 Py_ssize_t llen;
13966 int numdigits; /* len == numnondigits + numdigits */
13967 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013968
Victor Stinnerd0880d52012-04-27 23:40:13 +020013969 /* Avoid exceeding SSIZE_T_MAX */
13970 if (prec > INT_MAX-3) {
13971 PyErr_SetString(PyExc_OverflowError,
13972 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013973 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013974 }
13975
13976 assert(PyLong_Check(val));
13977
13978 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013979 default:
13980 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013981 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013982 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013983 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013984 /* int and int subclasses should print numerically when a numeric */
13985 /* format code is used (see issue18780) */
13986 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013987 break;
13988 case 'o':
13989 numnondigits = 2;
13990 result = PyNumber_ToBase(val, 8);
13991 break;
13992 case 'x':
13993 case 'X':
13994 numnondigits = 2;
13995 result = PyNumber_ToBase(val, 16);
13996 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013997 }
13998 if (!result)
13999 return NULL;
14000
14001 assert(unicode_modifiable(result));
14002 assert(PyUnicode_IS_READY(result));
14003 assert(PyUnicode_IS_ASCII(result));
14004
14005 /* To modify the string in-place, there can only be one reference. */
14006 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014007 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014008 PyErr_BadInternalCall();
14009 return NULL;
14010 }
14011 buf = PyUnicode_DATA(result);
14012 llen = PyUnicode_GET_LENGTH(result);
14013 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014014 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014015 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014016 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014017 return NULL;
14018 }
14019 len = (int)llen;
14020 sign = buf[0] == '-';
14021 numnondigits += sign;
14022 numdigits = len - numnondigits;
14023 assert(numdigits > 0);
14024
14025 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014026 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014027 (type == 'o' || type == 'x' || type == 'X'))) {
14028 assert(buf[sign] == '0');
14029 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14030 buf[sign+1] == 'o');
14031 numnondigits -= 2;
14032 buf += 2;
14033 len -= 2;
14034 if (sign)
14035 buf[0] = '-';
14036 assert(len == numnondigits + numdigits);
14037 assert(numdigits > 0);
14038 }
14039
14040 /* Fill with leading zeroes to meet minimum width. */
14041 if (prec > numdigits) {
14042 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14043 numnondigits + prec);
14044 char *b1;
14045 if (!r1) {
14046 Py_DECREF(result);
14047 return NULL;
14048 }
14049 b1 = PyBytes_AS_STRING(r1);
14050 for (i = 0; i < numnondigits; ++i)
14051 *b1++ = *buf++;
14052 for (i = 0; i < prec - numdigits; i++)
14053 *b1++ = '0';
14054 for (i = 0; i < numdigits; i++)
14055 *b1++ = *buf++;
14056 *b1 = '\0';
14057 Py_DECREF(result);
14058 result = r1;
14059 buf = PyBytes_AS_STRING(result);
14060 len = numnondigits + prec;
14061 }
14062
14063 /* Fix up case for hex conversions. */
14064 if (type == 'X') {
14065 /* Need to convert all lower case letters to upper case.
14066 and need to convert 0x to 0X (and -0x to -0X). */
14067 for (i = 0; i < len; i++)
14068 if (buf[i] >= 'a' && buf[i] <= 'x')
14069 buf[i] -= 'a'-'A';
14070 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014071 if (!PyUnicode_Check(result)
14072 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014073 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014074 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014075 Py_DECREF(result);
14076 result = unicode;
14077 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014078 else if (len != PyUnicode_GET_LENGTH(result)) {
14079 if (PyUnicode_Resize(&result, len) < 0)
14080 Py_CLEAR(result);
14081 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014082 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014083}
14084
Ethan Furmandf3ed242014-01-05 06:50:30 -080014085/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014086 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014087 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014088 * -1 and raise an exception on error */
14089static int
Victor Stinnera47082312012-10-04 02:19:54 +020014090mainformatlong(PyObject *v,
14091 struct unicode_format_arg_t *arg,
14092 PyObject **p_output,
14093 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014094{
14095 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014096 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014097
14098 if (!PyNumber_Check(v))
14099 goto wrongtype;
14100
Ethan Furman9ab74802014-03-21 06:38:46 -070014101 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014102 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014103 if (type == 'o' || type == 'x' || type == 'X') {
14104 iobj = PyNumber_Index(v);
14105 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014106 if (PyErr_ExceptionMatches(PyExc_TypeError))
14107 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014108 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014109 }
14110 }
14111 else {
14112 iobj = PyNumber_Long(v);
14113 if (iobj == NULL ) {
14114 if (PyErr_ExceptionMatches(PyExc_TypeError))
14115 goto wrongtype;
14116 return -1;
14117 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014118 }
14119 assert(PyLong_Check(iobj));
14120 }
14121 else {
14122 iobj = v;
14123 Py_INCREF(iobj);
14124 }
14125
14126 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014127 && arg->width == -1 && arg->prec == -1
14128 && !(arg->flags & (F_SIGN | F_BLANK))
14129 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014130 {
14131 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014132 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014133 int base;
14134
Victor Stinnera47082312012-10-04 02:19:54 +020014135 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014136 {
14137 default:
14138 assert(0 && "'type' not in [diuoxX]");
14139 case 'd':
14140 case 'i':
14141 case 'u':
14142 base = 10;
14143 break;
14144 case 'o':
14145 base = 8;
14146 break;
14147 case 'x':
14148 case 'X':
14149 base = 16;
14150 break;
14151 }
14152
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014153 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14154 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014155 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014156 }
14157 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014158 return 1;
14159 }
14160
Ethan Furmanb95b5612015-01-23 20:05:18 -080014161 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014162 Py_DECREF(iobj);
14163 if (res == NULL)
14164 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014165 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014166 return 0;
14167
14168wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014169 switch(type)
14170 {
14171 case 'o':
14172 case 'x':
14173 case 'X':
14174 PyErr_Format(PyExc_TypeError,
14175 "%%%c format: an integer is required, "
14176 "not %.200s",
14177 type, Py_TYPE(v)->tp_name);
14178 break;
14179 default:
14180 PyErr_Format(PyExc_TypeError,
14181 "%%%c format: a number is required, "
14182 "not %.200s",
14183 type, Py_TYPE(v)->tp_name);
14184 break;
14185 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014186 return -1;
14187}
14188
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014189static Py_UCS4
14190formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014191{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014192 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014193 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014194 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014195 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014196 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014197 goto onError;
14198 }
14199 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014200 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014201 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014202 /* make sure number is a type of integer */
14203 if (!PyLong_Check(v)) {
14204 iobj = PyNumber_Index(v);
14205 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014206 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014207 }
14208 v = iobj;
14209 Py_DECREF(iobj);
14210 }
14211 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014212 x = PyLong_AsLong(v);
14213 if (x == -1 && PyErr_Occurred())
14214 goto onError;
14215
Victor Stinner8faf8212011-12-08 22:14:11 +010014216 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014217 PyErr_SetString(PyExc_OverflowError,
14218 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014219 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014220 }
14221
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014222 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014223 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014224
Benjamin Peterson29060642009-01-31 22:14:21 +000014225 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014226 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014227 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014228 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014229}
14230
Victor Stinnera47082312012-10-04 02:19:54 +020014231/* Parse options of an argument: flags, width, precision.
14232 Handle also "%(name)" syntax.
14233
14234 Return 0 if the argument has been formatted into arg->str.
14235 Return 1 if the argument has been written into ctx->writer,
14236 Raise an exception and return -1 on error. */
14237static int
14238unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14239 struct unicode_format_arg_t *arg)
14240{
14241#define FORMAT_READ(ctx) \
14242 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14243
14244 PyObject *v;
14245
Victor Stinnera47082312012-10-04 02:19:54 +020014246 if (arg->ch == '(') {
14247 /* Get argument value from a dictionary. Example: "%(name)s". */
14248 Py_ssize_t keystart;
14249 Py_ssize_t keylen;
14250 PyObject *key;
14251 int pcount = 1;
14252
14253 if (ctx->dict == NULL) {
14254 PyErr_SetString(PyExc_TypeError,
14255 "format requires a mapping");
14256 return -1;
14257 }
14258 ++ctx->fmtpos;
14259 --ctx->fmtcnt;
14260 keystart = ctx->fmtpos;
14261 /* Skip over balanced parentheses */
14262 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14263 arg->ch = FORMAT_READ(ctx);
14264 if (arg->ch == ')')
14265 --pcount;
14266 else if (arg->ch == '(')
14267 ++pcount;
14268 ctx->fmtpos++;
14269 }
14270 keylen = ctx->fmtpos - keystart - 1;
14271 if (ctx->fmtcnt < 0 || pcount > 0) {
14272 PyErr_SetString(PyExc_ValueError,
14273 "incomplete format key");
14274 return -1;
14275 }
14276 key = PyUnicode_Substring(ctx->fmtstr,
14277 keystart, keystart + keylen);
14278 if (key == NULL)
14279 return -1;
14280 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014281 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014282 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014283 }
14284 ctx->args = PyObject_GetItem(ctx->dict, key);
14285 Py_DECREF(key);
14286 if (ctx->args == NULL)
14287 return -1;
14288 ctx->args_owned = 1;
14289 ctx->arglen = -1;
14290 ctx->argidx = -2;
14291 }
14292
14293 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014294 while (--ctx->fmtcnt >= 0) {
14295 arg->ch = FORMAT_READ(ctx);
14296 ctx->fmtpos++;
14297 switch (arg->ch) {
14298 case '-': arg->flags |= F_LJUST; continue;
14299 case '+': arg->flags |= F_SIGN; continue;
14300 case ' ': arg->flags |= F_BLANK; continue;
14301 case '#': arg->flags |= F_ALT; continue;
14302 case '0': arg->flags |= F_ZERO; continue;
14303 }
14304 break;
14305 }
14306
14307 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014308 if (arg->ch == '*') {
14309 v = unicode_format_getnextarg(ctx);
14310 if (v == NULL)
14311 return -1;
14312 if (!PyLong_Check(v)) {
14313 PyErr_SetString(PyExc_TypeError,
14314 "* wants int");
14315 return -1;
14316 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014317 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014318 if (arg->width == -1 && PyErr_Occurred())
14319 return -1;
14320 if (arg->width < 0) {
14321 arg->flags |= F_LJUST;
14322 arg->width = -arg->width;
14323 }
14324 if (--ctx->fmtcnt >= 0) {
14325 arg->ch = FORMAT_READ(ctx);
14326 ctx->fmtpos++;
14327 }
14328 }
14329 else if (arg->ch >= '0' && arg->ch <= '9') {
14330 arg->width = arg->ch - '0';
14331 while (--ctx->fmtcnt >= 0) {
14332 arg->ch = FORMAT_READ(ctx);
14333 ctx->fmtpos++;
14334 if (arg->ch < '0' || arg->ch > '9')
14335 break;
14336 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14337 mixing signed and unsigned comparison. Since arg->ch is between
14338 '0' and '9', casting to int is safe. */
14339 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14340 PyErr_SetString(PyExc_ValueError,
14341 "width too big");
14342 return -1;
14343 }
14344 arg->width = arg->width*10 + (arg->ch - '0');
14345 }
14346 }
14347
14348 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014349 if (arg->ch == '.') {
14350 arg->prec = 0;
14351 if (--ctx->fmtcnt >= 0) {
14352 arg->ch = FORMAT_READ(ctx);
14353 ctx->fmtpos++;
14354 }
14355 if (arg->ch == '*') {
14356 v = unicode_format_getnextarg(ctx);
14357 if (v == NULL)
14358 return -1;
14359 if (!PyLong_Check(v)) {
14360 PyErr_SetString(PyExc_TypeError,
14361 "* wants int");
14362 return -1;
14363 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014364 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014365 if (arg->prec == -1 && PyErr_Occurred())
14366 return -1;
14367 if (arg->prec < 0)
14368 arg->prec = 0;
14369 if (--ctx->fmtcnt >= 0) {
14370 arg->ch = FORMAT_READ(ctx);
14371 ctx->fmtpos++;
14372 }
14373 }
14374 else if (arg->ch >= '0' && arg->ch <= '9') {
14375 arg->prec = arg->ch - '0';
14376 while (--ctx->fmtcnt >= 0) {
14377 arg->ch = FORMAT_READ(ctx);
14378 ctx->fmtpos++;
14379 if (arg->ch < '0' || arg->ch > '9')
14380 break;
14381 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14382 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014383 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014384 return -1;
14385 }
14386 arg->prec = arg->prec*10 + (arg->ch - '0');
14387 }
14388 }
14389 }
14390
14391 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14392 if (ctx->fmtcnt >= 0) {
14393 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14394 if (--ctx->fmtcnt >= 0) {
14395 arg->ch = FORMAT_READ(ctx);
14396 ctx->fmtpos++;
14397 }
14398 }
14399 }
14400 if (ctx->fmtcnt < 0) {
14401 PyErr_SetString(PyExc_ValueError,
14402 "incomplete format");
14403 return -1;
14404 }
14405 return 0;
14406
14407#undef FORMAT_READ
14408}
14409
14410/* Format one argument. Supported conversion specifiers:
14411
14412 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014413 - "i", "d", "u": int or float
14414 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014415 - "e", "E", "f", "F", "g", "G": float
14416 - "c": int or str (1 character)
14417
Victor Stinner8dbd4212012-12-04 09:30:24 +010014418 When possible, the output is written directly into the Unicode writer
14419 (ctx->writer). A string is created when padding is required.
14420
Victor Stinnera47082312012-10-04 02:19:54 +020014421 Return 0 if the argument has been formatted into *p_str,
14422 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014423 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014424static int
14425unicode_format_arg_format(struct unicode_formatter_t *ctx,
14426 struct unicode_format_arg_t *arg,
14427 PyObject **p_str)
14428{
14429 PyObject *v;
14430 _PyUnicodeWriter *writer = &ctx->writer;
14431
14432 if (ctx->fmtcnt == 0)
14433 ctx->writer.overallocate = 0;
14434
14435 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014436 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014437 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014438 return 1;
14439 }
14440
14441 v = unicode_format_getnextarg(ctx);
14442 if (v == NULL)
14443 return -1;
14444
Victor Stinnera47082312012-10-04 02:19:54 +020014445
14446 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014447 case 's':
14448 case 'r':
14449 case 'a':
14450 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14451 /* Fast path */
14452 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14453 return -1;
14454 return 1;
14455 }
14456
14457 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14458 *p_str = v;
14459 Py_INCREF(*p_str);
14460 }
14461 else {
14462 if (arg->ch == 's')
14463 *p_str = PyObject_Str(v);
14464 else if (arg->ch == 'r')
14465 *p_str = PyObject_Repr(v);
14466 else
14467 *p_str = PyObject_ASCII(v);
14468 }
14469 break;
14470
14471 case 'i':
14472 case 'd':
14473 case 'u':
14474 case 'o':
14475 case 'x':
14476 case 'X':
14477 {
14478 int ret = mainformatlong(v, arg, p_str, writer);
14479 if (ret != 0)
14480 return ret;
14481 arg->sign = 1;
14482 break;
14483 }
14484
14485 case 'e':
14486 case 'E':
14487 case 'f':
14488 case 'F':
14489 case 'g':
14490 case 'G':
14491 if (arg->width == -1 && arg->prec == -1
14492 && !(arg->flags & (F_SIGN | F_BLANK)))
14493 {
14494 /* Fast path */
14495 if (formatfloat(v, arg, NULL, writer) == -1)
14496 return -1;
14497 return 1;
14498 }
14499
14500 arg->sign = 1;
14501 if (formatfloat(v, arg, p_str, NULL) == -1)
14502 return -1;
14503 break;
14504
14505 case 'c':
14506 {
14507 Py_UCS4 ch = formatchar(v);
14508 if (ch == (Py_UCS4) -1)
14509 return -1;
14510 if (arg->width == -1 && arg->prec == -1) {
14511 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014512 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014513 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014514 return 1;
14515 }
14516 *p_str = PyUnicode_FromOrdinal(ch);
14517 break;
14518 }
14519
14520 default:
14521 PyErr_Format(PyExc_ValueError,
14522 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014523 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014524 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14525 (int)arg->ch,
14526 ctx->fmtpos - 1);
14527 return -1;
14528 }
14529 if (*p_str == NULL)
14530 return -1;
14531 assert (PyUnicode_Check(*p_str));
14532 return 0;
14533}
14534
14535static int
14536unicode_format_arg_output(struct unicode_formatter_t *ctx,
14537 struct unicode_format_arg_t *arg,
14538 PyObject *str)
14539{
14540 Py_ssize_t len;
14541 enum PyUnicode_Kind kind;
14542 void *pbuf;
14543 Py_ssize_t pindex;
14544 Py_UCS4 signchar;
14545 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014546 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014547 Py_ssize_t sublen;
14548 _PyUnicodeWriter *writer = &ctx->writer;
14549 Py_UCS4 fill;
14550
14551 fill = ' ';
14552 if (arg->sign && arg->flags & F_ZERO)
14553 fill = '0';
14554
14555 if (PyUnicode_READY(str) == -1)
14556 return -1;
14557
14558 len = PyUnicode_GET_LENGTH(str);
14559 if ((arg->width == -1 || arg->width <= len)
14560 && (arg->prec == -1 || arg->prec >= len)
14561 && !(arg->flags & (F_SIGN | F_BLANK)))
14562 {
14563 /* Fast path */
14564 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14565 return -1;
14566 return 0;
14567 }
14568
14569 /* Truncate the string for "s", "r" and "a" formats
14570 if the precision is set */
14571 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14572 if (arg->prec >= 0 && len > arg->prec)
14573 len = arg->prec;
14574 }
14575
14576 /* Adjust sign and width */
14577 kind = PyUnicode_KIND(str);
14578 pbuf = PyUnicode_DATA(str);
14579 pindex = 0;
14580 signchar = '\0';
14581 if (arg->sign) {
14582 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14583 if (ch == '-' || ch == '+') {
14584 signchar = ch;
14585 len--;
14586 pindex++;
14587 }
14588 else if (arg->flags & F_SIGN)
14589 signchar = '+';
14590 else if (arg->flags & F_BLANK)
14591 signchar = ' ';
14592 else
14593 arg->sign = 0;
14594 }
14595 if (arg->width < len)
14596 arg->width = len;
14597
14598 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014599 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014600 if (!(arg->flags & F_LJUST)) {
14601 if (arg->sign) {
14602 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014603 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014604 }
14605 else {
14606 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014607 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014608 }
14609 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014610 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14611 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014612 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014613 }
14614
Victor Stinnera47082312012-10-04 02:19:54 +020014615 buflen = arg->width;
14616 if (arg->sign && len == arg->width)
14617 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014618 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014619 return -1;
14620
14621 /* Write the sign if needed */
14622 if (arg->sign) {
14623 if (fill != ' ') {
14624 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14625 writer->pos += 1;
14626 }
14627 if (arg->width > len)
14628 arg->width--;
14629 }
14630
14631 /* Write the numeric prefix for "x", "X" and "o" formats
14632 if the alternate form is used.
14633 For example, write "0x" for the "%#x" format. */
14634 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14635 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14636 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14637 if (fill != ' ') {
14638 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14639 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14640 writer->pos += 2;
14641 pindex += 2;
14642 }
14643 arg->width -= 2;
14644 if (arg->width < 0)
14645 arg->width = 0;
14646 len -= 2;
14647 }
14648
14649 /* Pad left with the fill character if needed */
14650 if (arg->width > len && !(arg->flags & F_LJUST)) {
14651 sublen = arg->width - len;
14652 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14653 writer->pos += sublen;
14654 arg->width = len;
14655 }
14656
14657 /* If padding with spaces: write sign if needed and/or numeric prefix if
14658 the alternate form is used */
14659 if (fill == ' ') {
14660 if (arg->sign) {
14661 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14662 writer->pos += 1;
14663 }
14664 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14665 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14666 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14667 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14668 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14669 writer->pos += 2;
14670 pindex += 2;
14671 }
14672 }
14673
14674 /* Write characters */
14675 if (len) {
14676 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14677 str, pindex, len);
14678 writer->pos += len;
14679 }
14680
14681 /* Pad right with the fill character if needed */
14682 if (arg->width > len) {
14683 sublen = arg->width - len;
14684 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14685 writer->pos += sublen;
14686 }
14687 return 0;
14688}
14689
14690/* Helper of PyUnicode_Format(): format one arg.
14691 Return 0 on success, raise an exception and return -1 on error. */
14692static int
14693unicode_format_arg(struct unicode_formatter_t *ctx)
14694{
14695 struct unicode_format_arg_t arg;
14696 PyObject *str;
14697 int ret;
14698
Victor Stinner8dbd4212012-12-04 09:30:24 +010014699 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14700 arg.flags = 0;
14701 arg.width = -1;
14702 arg.prec = -1;
14703 arg.sign = 0;
14704 str = NULL;
14705
Victor Stinnera47082312012-10-04 02:19:54 +020014706 ret = unicode_format_arg_parse(ctx, &arg);
14707 if (ret == -1)
14708 return -1;
14709
14710 ret = unicode_format_arg_format(ctx, &arg, &str);
14711 if (ret == -1)
14712 return -1;
14713
14714 if (ret != 1) {
14715 ret = unicode_format_arg_output(ctx, &arg, str);
14716 Py_DECREF(str);
14717 if (ret == -1)
14718 return -1;
14719 }
14720
14721 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14722 PyErr_SetString(PyExc_TypeError,
14723 "not all arguments converted during string formatting");
14724 return -1;
14725 }
14726 return 0;
14727}
14728
Alexander Belopolsky40018472011-02-26 01:02:56 +000014729PyObject *
14730PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014731{
Victor Stinnera47082312012-10-04 02:19:54 +020014732 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014733
Guido van Rossumd57fd912000-03-10 22:53:23 +000014734 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014735 PyErr_BadInternalCall();
14736 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014737 }
Victor Stinnera47082312012-10-04 02:19:54 +020014738
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014739 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014740 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014741
14742 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014743 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14744 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14745 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14746 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014747
Victor Stinner8f674cc2013-04-17 23:02:17 +020014748 _PyUnicodeWriter_Init(&ctx.writer);
14749 ctx.writer.min_length = ctx.fmtcnt + 100;
14750 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014751
Guido van Rossumd57fd912000-03-10 22:53:23 +000014752 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014753 ctx.arglen = PyTuple_Size(args);
14754 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014755 }
14756 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014757 ctx.arglen = -1;
14758 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014759 }
Victor Stinnera47082312012-10-04 02:19:54 +020014760 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014761 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014762 ctx.dict = args;
14763 else
14764 ctx.dict = NULL;
14765 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014766
Victor Stinnera47082312012-10-04 02:19:54 +020014767 while (--ctx.fmtcnt >= 0) {
14768 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014769 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014770
14771 nonfmtpos = ctx.fmtpos++;
14772 while (ctx.fmtcnt >= 0 &&
14773 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14774 ctx.fmtpos++;
14775 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014776 }
Victor Stinnera47082312012-10-04 02:19:54 +020014777 if (ctx.fmtcnt < 0) {
14778 ctx.fmtpos--;
14779 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014780 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014781
Victor Stinnercfc4c132013-04-03 01:48:39 +020014782 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14783 nonfmtpos, ctx.fmtpos) < 0)
14784 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014785 }
14786 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014787 ctx.fmtpos++;
14788 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014789 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014790 }
14791 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014792
Victor Stinnera47082312012-10-04 02:19:54 +020014793 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014794 PyErr_SetString(PyExc_TypeError,
14795 "not all arguments converted during string formatting");
14796 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014797 }
14798
Victor Stinnera47082312012-10-04 02:19:54 +020014799 if (ctx.args_owned) {
14800 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014801 }
Victor Stinnera47082312012-10-04 02:19:54 +020014802 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014803
Benjamin Peterson29060642009-01-31 22:14:21 +000014804 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014805 _PyUnicodeWriter_Dealloc(&ctx.writer);
14806 if (ctx.args_owned) {
14807 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014808 }
14809 return NULL;
14810}
14811
Jeremy Hylton938ace62002-07-17 16:30:39 +000014812static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014813unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14814
Tim Peters6d6c1a32001-08-02 04:15:00 +000014815static PyObject *
14816unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14817{
Benjamin Peterson29060642009-01-31 22:14:21 +000014818 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014819 static char *kwlist[] = {"object", "encoding", "errors", 0};
14820 char *encoding = NULL;
14821 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014822
Benjamin Peterson14339b62009-01-31 16:36:08 +000014823 if (type != &PyUnicode_Type)
14824 return unicode_subtype_new(type, args, kwds);
14825 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014826 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014827 return NULL;
14828 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014829 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014830 if (encoding == NULL && errors == NULL)
14831 return PyObject_Str(x);
14832 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014833 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014834}
14835
Guido van Rossume023fe02001-08-30 03:12:59 +000014836static PyObject *
14837unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14838{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014839 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014840 Py_ssize_t length, char_size;
14841 int share_wstr, share_utf8;
14842 unsigned int kind;
14843 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014844
Benjamin Peterson14339b62009-01-31 16:36:08 +000014845 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014846
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014847 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014848 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014849 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014850 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014851 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014852 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014853 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014854 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014855
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014856 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014857 if (self == NULL) {
14858 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014859 return NULL;
14860 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014861 kind = PyUnicode_KIND(unicode);
14862 length = PyUnicode_GET_LENGTH(unicode);
14863
14864 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014865#ifdef Py_DEBUG
14866 _PyUnicode_HASH(self) = -1;
14867#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014868 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014869#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014870 _PyUnicode_STATE(self).interned = 0;
14871 _PyUnicode_STATE(self).kind = kind;
14872 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014873 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014874 _PyUnicode_STATE(self).ready = 1;
14875 _PyUnicode_WSTR(self) = NULL;
14876 _PyUnicode_UTF8_LENGTH(self) = 0;
14877 _PyUnicode_UTF8(self) = NULL;
14878 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014879 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014880
14881 share_utf8 = 0;
14882 share_wstr = 0;
14883 if (kind == PyUnicode_1BYTE_KIND) {
14884 char_size = 1;
14885 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14886 share_utf8 = 1;
14887 }
14888 else if (kind == PyUnicode_2BYTE_KIND) {
14889 char_size = 2;
14890 if (sizeof(wchar_t) == 2)
14891 share_wstr = 1;
14892 }
14893 else {
14894 assert(kind == PyUnicode_4BYTE_KIND);
14895 char_size = 4;
14896 if (sizeof(wchar_t) == 4)
14897 share_wstr = 1;
14898 }
14899
14900 /* Ensure we won't overflow the length. */
14901 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14902 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014903 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014904 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014905 data = PyObject_MALLOC((length + 1) * char_size);
14906 if (data == NULL) {
14907 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014908 goto onError;
14909 }
14910
Victor Stinnerc3c74152011-10-02 20:39:55 +020014911 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014912 if (share_utf8) {
14913 _PyUnicode_UTF8_LENGTH(self) = length;
14914 _PyUnicode_UTF8(self) = data;
14915 }
14916 if (share_wstr) {
14917 _PyUnicode_WSTR_LENGTH(self) = length;
14918 _PyUnicode_WSTR(self) = (wchar_t *)data;
14919 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014920
Christian Heimesf051e432016-09-13 20:22:02 +020014921 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014922 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014923 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014924#ifdef Py_DEBUG
14925 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14926#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014927 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014928 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014929
14930onError:
14931 Py_DECREF(unicode);
14932 Py_DECREF(self);
14933 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014934}
14935
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014936PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014937"str(object='') -> str\n\
14938str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014939\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014940Create a new string object from the given object. If encoding or\n\
14941errors is specified, then the object must expose a data buffer\n\
14942that will be decoded using the given encoding and error handler.\n\
14943Otherwise, returns the result of object.__str__() (if defined)\n\
14944or repr(object).\n\
14945encoding defaults to sys.getdefaultencoding().\n\
14946errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014947
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014948static PyObject *unicode_iter(PyObject *seq);
14949
Guido van Rossumd57fd912000-03-10 22:53:23 +000014950PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014951 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014952 "str", /* tp_name */
14953 sizeof(PyUnicodeObject), /* tp_size */
14954 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014955 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014956 (destructor)unicode_dealloc, /* tp_dealloc */
14957 0, /* tp_print */
14958 0, /* tp_getattr */
14959 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014960 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014961 unicode_repr, /* tp_repr */
14962 &unicode_as_number, /* tp_as_number */
14963 &unicode_as_sequence, /* tp_as_sequence */
14964 &unicode_as_mapping, /* tp_as_mapping */
14965 (hashfunc) unicode_hash, /* tp_hash*/
14966 0, /* tp_call*/
14967 (reprfunc) unicode_str, /* tp_str */
14968 PyObject_GenericGetAttr, /* tp_getattro */
14969 0, /* tp_setattro */
14970 0, /* tp_as_buffer */
14971 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014972 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014973 unicode_doc, /* tp_doc */
14974 0, /* tp_traverse */
14975 0, /* tp_clear */
14976 PyUnicode_RichCompare, /* tp_richcompare */
14977 0, /* tp_weaklistoffset */
14978 unicode_iter, /* tp_iter */
14979 0, /* tp_iternext */
14980 unicode_methods, /* tp_methods */
14981 0, /* tp_members */
14982 0, /* tp_getset */
14983 &PyBaseObject_Type, /* tp_base */
14984 0, /* tp_dict */
14985 0, /* tp_descr_get */
14986 0, /* tp_descr_set */
14987 0, /* tp_dictoffset */
14988 0, /* tp_init */
14989 0, /* tp_alloc */
14990 unicode_new, /* tp_new */
14991 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014992};
14993
14994/* Initialize the Unicode implementation */
14995
Victor Stinner3a50e702011-10-18 21:21:00 +020014996int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014997{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014998 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014999 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015000 0x000A, /* LINE FEED */
15001 0x000D, /* CARRIAGE RETURN */
15002 0x001C, /* FILE SEPARATOR */
15003 0x001D, /* GROUP SEPARATOR */
15004 0x001E, /* RECORD SEPARATOR */
15005 0x0085, /* NEXT LINE */
15006 0x2028, /* LINE SEPARATOR */
15007 0x2029, /* PARAGRAPH SEPARATOR */
15008 };
15009
Fred Drakee4315f52000-05-09 19:53:39 +000015010 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015011 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015012 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015013 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015014 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015015
Guido van Rossumcacfc072002-05-24 19:01:59 +000015016 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015017 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015018
15019 /* initialize the linebreak bloom filter */
15020 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015021 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015022 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015023
Christian Heimes26532f72013-07-20 14:57:16 +020015024 if (PyType_Ready(&EncodingMapType) < 0)
15025 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015026
Benjamin Petersonc4311282012-10-30 23:21:10 -040015027 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15028 Py_FatalError("Can't initialize field name iterator type");
15029
15030 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15031 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015032
Victor Stinner3a50e702011-10-18 21:21:00 +020015033 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015034}
15035
15036/* Finalize the Unicode implementation */
15037
Christian Heimesa156e092008-02-16 07:38:31 +000015038int
15039PyUnicode_ClearFreeList(void)
15040{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015041 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015042}
15043
Guido van Rossumd57fd912000-03-10 22:53:23 +000015044void
Thomas Wouters78890102000-07-22 19:25:51 +000015045_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015046{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015047 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015048
Serhiy Storchaka05997252013-01-26 12:14:02 +020015049 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015050
Serhiy Storchaka05997252013-01-26 12:14:02 +020015051 for (i = 0; i < 256; i++)
15052 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015053 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015054 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015055}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015056
Walter Dörwald16807132007-05-25 13:52:07 +000015057void
15058PyUnicode_InternInPlace(PyObject **p)
15059{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015060 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015061 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015062#ifdef Py_DEBUG
15063 assert(s != NULL);
15064 assert(_PyUnicode_CHECK(s));
15065#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015066 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015067 return;
15068#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015069 /* If it's a subclass, we don't really know what putting
15070 it in the interned dict might do. */
15071 if (!PyUnicode_CheckExact(s))
15072 return;
15073 if (PyUnicode_CHECK_INTERNED(s))
15074 return;
15075 if (interned == NULL) {
15076 interned = PyDict_New();
15077 if (interned == NULL) {
15078 PyErr_Clear(); /* Don't leave an exception */
15079 return;
15080 }
15081 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015082 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015083 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015084 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015085 if (t == NULL) {
15086 PyErr_Clear();
15087 return;
15088 }
15089 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015090 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015091 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015092 return;
15093 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015094 /* The two references in interned are not counted by refcnt.
15095 The deallocator will take care of this */
15096 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015097 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015098}
15099
15100void
15101PyUnicode_InternImmortal(PyObject **p)
15102{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015103 PyUnicode_InternInPlace(p);
15104 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015105 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015106 Py_INCREF(*p);
15107 }
Walter Dörwald16807132007-05-25 13:52:07 +000015108}
15109
15110PyObject *
15111PyUnicode_InternFromString(const char *cp)
15112{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015113 PyObject *s = PyUnicode_FromString(cp);
15114 if (s == NULL)
15115 return NULL;
15116 PyUnicode_InternInPlace(&s);
15117 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015118}
15119
Alexander Belopolsky40018472011-02-26 01:02:56 +000015120void
15121_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015122{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015123 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015124 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015125 Py_ssize_t i, n;
15126 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015127
Benjamin Peterson14339b62009-01-31 16:36:08 +000015128 if (interned == NULL || !PyDict_Check(interned))
15129 return;
15130 keys = PyDict_Keys(interned);
15131 if (keys == NULL || !PyList_Check(keys)) {
15132 PyErr_Clear();
15133 return;
15134 }
Walter Dörwald16807132007-05-25 13:52:07 +000015135
Benjamin Peterson14339b62009-01-31 16:36:08 +000015136 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15137 detector, interned unicode strings are not forcibly deallocated;
15138 rather, we give them their stolen references back, and then clear
15139 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015140
Benjamin Peterson14339b62009-01-31 16:36:08 +000015141 n = PyList_GET_SIZE(keys);
15142 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015143 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015144 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015145 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015146 if (PyUnicode_READY(s) == -1) {
15147 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015148 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015149 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015150 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015151 case SSTATE_NOT_INTERNED:
15152 /* XXX Shouldn't happen */
15153 break;
15154 case SSTATE_INTERNED_IMMORTAL:
15155 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015156 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015157 break;
15158 case SSTATE_INTERNED_MORTAL:
15159 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015160 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015161 break;
15162 default:
15163 Py_FatalError("Inconsistent interned string state.");
15164 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015165 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015166 }
15167 fprintf(stderr, "total size of all interned strings: "
15168 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15169 "mortal/immortal\n", mortal_size, immortal_size);
15170 Py_DECREF(keys);
15171 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015172 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015173}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015174
15175
15176/********************* Unicode Iterator **************************/
15177
15178typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015179 PyObject_HEAD
15180 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015181 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015182} unicodeiterobject;
15183
15184static void
15185unicodeiter_dealloc(unicodeiterobject *it)
15186{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015187 _PyObject_GC_UNTRACK(it);
15188 Py_XDECREF(it->it_seq);
15189 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015190}
15191
15192static int
15193unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15194{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015195 Py_VISIT(it->it_seq);
15196 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015197}
15198
15199static PyObject *
15200unicodeiter_next(unicodeiterobject *it)
15201{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015202 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015203
Benjamin Peterson14339b62009-01-31 16:36:08 +000015204 assert(it != NULL);
15205 seq = it->it_seq;
15206 if (seq == NULL)
15207 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015208 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015210 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15211 int kind = PyUnicode_KIND(seq);
15212 void *data = PyUnicode_DATA(seq);
15213 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15214 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015215 if (item != NULL)
15216 ++it->it_index;
15217 return item;
15218 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015219
Benjamin Peterson14339b62009-01-31 16:36:08 +000015220 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015221 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015222 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015223}
15224
15225static PyObject *
15226unicodeiter_len(unicodeiterobject *it)
15227{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015228 Py_ssize_t len = 0;
15229 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015230 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015231 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015232}
15233
15234PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15235
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015236static PyObject *
15237unicodeiter_reduce(unicodeiterobject *it)
15238{
15239 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015240 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015241 it->it_seq, it->it_index);
15242 } else {
15243 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15244 if (u == NULL)
15245 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015246 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015247 }
15248}
15249
15250PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15251
15252static PyObject *
15253unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15254{
15255 Py_ssize_t index = PyLong_AsSsize_t(state);
15256 if (index == -1 && PyErr_Occurred())
15257 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015258 if (it->it_seq != NULL) {
15259 if (index < 0)
15260 index = 0;
15261 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15262 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15263 it->it_index = index;
15264 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015265 Py_RETURN_NONE;
15266}
15267
15268PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15269
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015270static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015271 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015272 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015273 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15274 reduce_doc},
15275 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15276 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015277 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015278};
15279
15280PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015281 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15282 "str_iterator", /* tp_name */
15283 sizeof(unicodeiterobject), /* tp_basicsize */
15284 0, /* tp_itemsize */
15285 /* methods */
15286 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15287 0, /* tp_print */
15288 0, /* tp_getattr */
15289 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015290 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015291 0, /* tp_repr */
15292 0, /* tp_as_number */
15293 0, /* tp_as_sequence */
15294 0, /* tp_as_mapping */
15295 0, /* tp_hash */
15296 0, /* tp_call */
15297 0, /* tp_str */
15298 PyObject_GenericGetAttr, /* tp_getattro */
15299 0, /* tp_setattro */
15300 0, /* tp_as_buffer */
15301 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15302 0, /* tp_doc */
15303 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15304 0, /* tp_clear */
15305 0, /* tp_richcompare */
15306 0, /* tp_weaklistoffset */
15307 PyObject_SelfIter, /* tp_iter */
15308 (iternextfunc)unicodeiter_next, /* tp_iternext */
15309 unicodeiter_methods, /* tp_methods */
15310 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015311};
15312
15313static PyObject *
15314unicode_iter(PyObject *seq)
15315{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015316 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015317
Benjamin Peterson14339b62009-01-31 16:36:08 +000015318 if (!PyUnicode_Check(seq)) {
15319 PyErr_BadInternalCall();
15320 return NULL;
15321 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015322 if (PyUnicode_READY(seq) == -1)
15323 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015324 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15325 if (it == NULL)
15326 return NULL;
15327 it->it_index = 0;
15328 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015329 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015330 _PyObject_GC_TRACK(it);
15331 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015332}
15333
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015334
15335size_t
15336Py_UNICODE_strlen(const Py_UNICODE *u)
15337{
15338 int res = 0;
15339 while(*u++)
15340 res++;
15341 return res;
15342}
15343
15344Py_UNICODE*
15345Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15346{
15347 Py_UNICODE *u = s1;
15348 while ((*u++ = *s2++));
15349 return s1;
15350}
15351
15352Py_UNICODE*
15353Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15354{
15355 Py_UNICODE *u = s1;
15356 while ((*u++ = *s2++))
15357 if (n-- == 0)
15358 break;
15359 return s1;
15360}
15361
15362Py_UNICODE*
15363Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15364{
15365 Py_UNICODE *u1 = s1;
15366 u1 += Py_UNICODE_strlen(u1);
15367 Py_UNICODE_strcpy(u1, s2);
15368 return s1;
15369}
15370
15371int
15372Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15373{
15374 while (*s1 && *s2 && *s1 == *s2)
15375 s1++, s2++;
15376 if (*s1 && *s2)
15377 return (*s1 < *s2) ? -1 : +1;
15378 if (*s1)
15379 return 1;
15380 if (*s2)
15381 return -1;
15382 return 0;
15383}
15384
15385int
15386Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15387{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015388 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015389 for (; n != 0; n--) {
15390 u1 = *s1;
15391 u2 = *s2;
15392 if (u1 != u2)
15393 return (u1 < u2) ? -1 : +1;
15394 if (u1 == '\0')
15395 return 0;
15396 s1++;
15397 s2++;
15398 }
15399 return 0;
15400}
15401
15402Py_UNICODE*
15403Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15404{
15405 const Py_UNICODE *p;
15406 for (p = s; *p; p++)
15407 if (*p == c)
15408 return (Py_UNICODE*)p;
15409 return NULL;
15410}
15411
15412Py_UNICODE*
15413Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15414{
15415 const Py_UNICODE *p;
15416 p = s + Py_UNICODE_strlen(s);
15417 while (p != s) {
15418 p--;
15419 if (*p == c)
15420 return (Py_UNICODE*)p;
15421 }
15422 return NULL;
15423}
Victor Stinner331ea922010-08-10 16:37:20 +000015424
Victor Stinner71133ff2010-09-01 23:43:53 +000015425Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015426PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015427{
Victor Stinner577db2c2011-10-11 22:12:48 +020015428 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015429 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015431 if (!PyUnicode_Check(unicode)) {
15432 PyErr_BadArgument();
15433 return NULL;
15434 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015435 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015436 if (u == NULL)
15437 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015438 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015439 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015440 PyErr_NoMemory();
15441 return NULL;
15442 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015443 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015444 size *= sizeof(Py_UNICODE);
15445 copy = PyMem_Malloc(size);
15446 if (copy == NULL) {
15447 PyErr_NoMemory();
15448 return NULL;
15449 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015450 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015451 return copy;
15452}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015453
Georg Brandl66c221e2010-10-14 07:04:07 +000015454/* A _string module, to export formatter_parser and formatter_field_name_split
15455 to the string.Formatter class implemented in Python. */
15456
15457static PyMethodDef _string_methods[] = {
15458 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15459 METH_O, PyDoc_STR("split the argument as a field name")},
15460 {"formatter_parser", (PyCFunction) formatter_parser,
15461 METH_O, PyDoc_STR("parse the argument as a format string")},
15462 {NULL, NULL}
15463};
15464
15465static struct PyModuleDef _string_module = {
15466 PyModuleDef_HEAD_INIT,
15467 "_string",
15468 PyDoc_STR("string helper module"),
15469 0,
15470 _string_methods,
15471 NULL,
15472 NULL,
15473 NULL,
15474 NULL
15475};
15476
15477PyMODINIT_FUNC
15478PyInit__string(void)
15479{
15480 return PyModule_Create(&_string_module);
15481}
15482
15483
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015484#ifdef __cplusplus
15485}
15486#endif