blob: 02f726d0ce1decdd71beb0837ce3fb515eb06a70 [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{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003235 if (!PyUnicode_Check(unicode)) {
3236 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003237 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003238 }
3239
Serhiy Storchaka00939072016-10-27 21:05:49 +03003240 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3241 "PyUnicode_AsDecodedObject() is deprecated; "
3242 "use PyCodec_Decode() to decode from str", 1) < 0)
3243 return NULL;
3244
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003245 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003246 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003247
3248 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003249 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003250}
3251
Alexander Belopolsky40018472011-02-26 01:02:56 +00003252PyObject *
3253PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003254 const char *encoding,
3255 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003256{
3257 PyObject *v;
3258
3259 if (!PyUnicode_Check(unicode)) {
3260 PyErr_BadArgument();
3261 goto onError;
3262 }
3263
Serhiy Storchaka00939072016-10-27 21:05:49 +03003264 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3265 "PyUnicode_AsDecodedUnicode() is deprecated; "
3266 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3267 return NULL;
3268
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003269 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003270 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003271
3272 /* Decode via the codec registry */
3273 v = PyCodec_Decode(unicode, encoding, errors);
3274 if (v == NULL)
3275 goto onError;
3276 if (!PyUnicode_Check(v)) {
3277 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003278 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3279 "use codecs.decode() to decode to arbitrary types",
3280 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003281 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003282 Py_DECREF(v);
3283 goto onError;
3284 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003285 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003286
Benjamin Peterson29060642009-01-31 22:14:21 +00003287 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003288 return NULL;
3289}
3290
Alexander Belopolsky40018472011-02-26 01:02:56 +00003291PyObject *
3292PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003293 Py_ssize_t size,
3294 const char *encoding,
3295 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003296{
3297 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003298
Guido van Rossumd57fd912000-03-10 22:53:23 +00003299 unicode = PyUnicode_FromUnicode(s, size);
3300 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003301 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003302 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3303 Py_DECREF(unicode);
3304 return v;
3305}
3306
Alexander Belopolsky40018472011-02-26 01:02:56 +00003307PyObject *
3308PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003309 const char *encoding,
3310 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003311{
3312 PyObject *v;
3313
3314 if (!PyUnicode_Check(unicode)) {
3315 PyErr_BadArgument();
3316 goto onError;
3317 }
3318
Serhiy Storchaka00939072016-10-27 21:05:49 +03003319 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3320 "PyUnicode_AsEncodedObject() is deprecated; "
3321 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3322 "or PyCodec_Encode() for generic encoding", 1) < 0)
3323 return NULL;
3324
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003325 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003326 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003327
3328 /* Encode via the codec registry */
3329 v = PyCodec_Encode(unicode, encoding, errors);
3330 if (v == NULL)
3331 goto onError;
3332 return v;
3333
Benjamin Peterson29060642009-01-31 22:14:21 +00003334 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003335 return NULL;
3336}
3337
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003338static size_t
3339wcstombs_errorpos(const wchar_t *wstr)
3340{
3341 size_t len;
3342#if SIZEOF_WCHAR_T == 2
3343 wchar_t buf[3];
3344#else
3345 wchar_t buf[2];
3346#endif
3347 char outbuf[MB_LEN_MAX];
3348 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003349
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003350#if SIZEOF_WCHAR_T == 2
3351 buf[2] = 0;
3352#else
3353 buf[1] = 0;
3354#endif
3355 start = wstr;
3356 while (*wstr != L'\0')
3357 {
3358 previous = wstr;
3359#if SIZEOF_WCHAR_T == 2
3360 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3361 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3362 {
3363 buf[0] = wstr[0];
3364 buf[1] = wstr[1];
3365 wstr += 2;
3366 }
3367 else {
3368 buf[0] = *wstr;
3369 buf[1] = 0;
3370 wstr++;
3371 }
3372#else
3373 buf[0] = *wstr;
3374 wstr++;
3375#endif
3376 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003377 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003378 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003379 }
3380
3381 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003382 return 0;
3383}
3384
Victor Stinner1b579672011-12-17 05:47:23 +01003385static int
3386locale_error_handler(const char *errors, int *surrogateescape)
3387{
Victor Stinner50149202015-09-22 00:26:54 +02003388 _Py_error_handler error_handler = get_error_handler(errors);
3389 switch (error_handler)
3390 {
3391 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003392 *surrogateescape = 0;
3393 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003394 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003395 *surrogateescape = 1;
3396 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003397 default:
3398 PyErr_Format(PyExc_ValueError,
3399 "only 'strict' and 'surrogateescape' error handlers "
3400 "are supported, not '%s'",
3401 errors);
3402 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003403 }
Victor Stinner1b579672011-12-17 05:47:23 +01003404}
3405
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003406PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003407PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003408{
3409 Py_ssize_t wlen, wlen2;
3410 wchar_t *wstr;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003411 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003412 PyObject *bytes, *reason, *exc;
3413 size_t error_pos, errlen;
Victor Stinner1b579672011-12-17 05:47:23 +01003414 int surrogateescape;
3415
3416 if (locale_error_handler(errors, &surrogateescape) < 0)
3417 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003418
3419 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3420 if (wstr == NULL)
3421 return NULL;
3422
3423 wlen2 = wcslen(wstr);
3424 if (wlen2 != wlen) {
3425 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003426 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003427 return NULL;
3428 }
3429
3430 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003431 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003432 char *str;
3433
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003434 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003435 if (str == NULL) {
3436 if (error_pos == (size_t)-1) {
3437 PyErr_NoMemory();
3438 PyMem_Free(wstr);
3439 return NULL;
3440 }
3441 else {
3442 goto encode_error;
3443 }
3444 }
3445 PyMem_Free(wstr);
3446
3447 bytes = PyBytes_FromString(str);
3448 PyMem_Free(str);
3449 }
3450 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003451 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003452 size_t len, len2;
3453
3454 len = wcstombs(NULL, wstr, 0);
3455 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003456 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003457 goto encode_error;
3458 }
3459
3460 bytes = PyBytes_FromStringAndSize(NULL, len);
3461 if (bytes == NULL) {
3462 PyMem_Free(wstr);
3463 return NULL;
3464 }
3465
3466 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3467 if (len2 == (size_t)-1 || len2 > len) {
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003468 Py_DECREF(bytes);
Victor Stinner2f197072011-12-17 07:08:30 +01003469 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003470 goto encode_error;
3471 }
3472 PyMem_Free(wstr);
3473 }
3474 return bytes;
3475
3476encode_error:
3477 errmsg = strerror(errno);
3478 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003479
3480 if (error_pos == (size_t)-1)
3481 error_pos = wcstombs_errorpos(wstr);
3482
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003483 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003484
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003485 wstr = Py_DecodeLocale(errmsg, &errlen);
3486 if (wstr != NULL) {
3487 reason = PyUnicode_FromWideChar(wstr, errlen);
3488 PyMem_RawFree(wstr);
3489 } else {
3490 errmsg = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003491 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003492
Victor Stinner2f197072011-12-17 07:08:30 +01003493 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003494 reason = PyUnicode_FromString(
3495 "wcstombs() encountered an unencodable "
3496 "wide character");
3497 if (reason == NULL)
3498 return NULL;
3499
3500 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3501 "locale", unicode,
3502 (Py_ssize_t)error_pos,
3503 (Py_ssize_t)(error_pos+1),
3504 reason);
3505 Py_DECREF(reason);
3506 if (exc != NULL) {
3507 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003508 Py_DECREF(exc);
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003509 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003510 return NULL;
3511}
3512
Victor Stinnerad158722010-10-27 00:25:46 +00003513PyObject *
3514PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003515{
Steve Dowercc16be82016-09-08 10:35:16 -07003516#if defined(__APPLE__)
3517 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003518#else
Victor Stinner793b5312011-04-27 00:24:21 +02003519 PyInterpreterState *interp = PyThreadState_GET()->interp;
3520 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3521 cannot use it to encode and decode filenames before it is loaded. Load
3522 the Python codec requires to encode at least its own filename. Use the C
3523 version of the locale codec until the codec registry is initialized and
3524 the Python codec is loaded.
3525
3526 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3527 cannot only rely on it: check also interp->fscodec_initialized for
3528 subinterpreters. */
3529 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003530 return PyUnicode_AsEncodedString(unicode,
3531 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003532 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003533 }
3534 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003535 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003536 }
Victor Stinnerad158722010-10-27 00:25:46 +00003537#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003538}
3539
Alexander Belopolsky40018472011-02-26 01:02:56 +00003540PyObject *
3541PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003542 const char *encoding,
3543 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003544{
3545 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003546 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003547
Guido van Rossumd57fd912000-03-10 22:53:23 +00003548 if (!PyUnicode_Check(unicode)) {
3549 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003550 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003551 }
Fred Drakee4315f52000-05-09 19:53:39 +00003552
Victor Stinner942889a2016-09-05 15:40:10 -07003553 if (encoding == NULL) {
3554 return _PyUnicode_AsUTF8String(unicode, errors);
3555 }
3556
Fred Drakee4315f52000-05-09 19:53:39 +00003557 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003558 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3559 char *lower = buflower;
3560
3561 /* Fast paths */
3562 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3563 lower += 3;
3564 if (*lower == '_') {
3565 /* Match "utf8" and "utf_8" */
3566 lower++;
3567 }
3568
3569 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003570 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003571 }
3572 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3573 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3574 }
3575 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3576 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3577 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003578 }
Victor Stinner942889a2016-09-05 15:40:10 -07003579 else {
3580 if (strcmp(lower, "ascii") == 0
3581 || strcmp(lower, "us_ascii") == 0) {
3582 return _PyUnicode_AsASCIIString(unicode, errors);
3583 }
Steve Dowercc16be82016-09-08 10:35:16 -07003584#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003585 else if (strcmp(lower, "mbcs") == 0) {
3586 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3587 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003588#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003589 else if (strcmp(lower, "latin1") == 0 ||
3590 strcmp(lower, "latin_1") == 0 ||
3591 strcmp(lower, "iso_8859_1") == 0 ||
3592 strcmp(lower, "iso8859_1") == 0) {
3593 return _PyUnicode_AsLatin1String(unicode, errors);
3594 }
3595 }
Victor Stinner37296e82010-06-10 13:36:23 +00003596 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003597
3598 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003599 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003600 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003601 return NULL;
3602
3603 /* The normal path */
3604 if (PyBytes_Check(v))
3605 return v;
3606
3607 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003608 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003609 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003610 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003611
3612 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003613 "encoder %s returned bytearray instead of bytes; "
3614 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003615 encoding);
3616 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003617 Py_DECREF(v);
3618 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003619 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003620
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003621 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3622 Py_DECREF(v);
3623 return b;
3624 }
3625
3626 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003627 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3628 "use codecs.encode() to encode to arbitrary types",
3629 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003630 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003631 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003632 return NULL;
3633}
3634
Alexander Belopolsky40018472011-02-26 01:02:56 +00003635PyObject *
3636PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003637 const char *encoding,
3638 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003639{
3640 PyObject *v;
3641
3642 if (!PyUnicode_Check(unicode)) {
3643 PyErr_BadArgument();
3644 goto onError;
3645 }
3646
Serhiy Storchaka00939072016-10-27 21:05:49 +03003647 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3648 "PyUnicode_AsEncodedUnicode() is deprecated; "
3649 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3650 return NULL;
3651
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003652 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003654
3655 /* Encode via the codec registry */
3656 v = PyCodec_Encode(unicode, encoding, errors);
3657 if (v == NULL)
3658 goto onError;
3659 if (!PyUnicode_Check(v)) {
3660 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003661 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3662 "use codecs.encode() to encode to arbitrary types",
3663 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003664 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003665 Py_DECREF(v);
3666 goto onError;
3667 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003668 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003669
Benjamin Peterson29060642009-01-31 22:14:21 +00003670 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003671 return NULL;
3672}
3673
Victor Stinner2f197072011-12-17 07:08:30 +01003674static size_t
3675mbstowcs_errorpos(const char *str, size_t len)
3676{
3677#ifdef HAVE_MBRTOWC
3678 const char *start = str;
3679 mbstate_t mbs;
3680 size_t converted;
3681 wchar_t ch;
3682
3683 memset(&mbs, 0, sizeof mbs);
3684 while (len)
3685 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003686 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003687 if (converted == 0)
3688 /* Reached end of string */
3689 break;
3690 if (converted == (size_t)-1 || converted == (size_t)-2) {
3691 /* Conversion error or incomplete character */
3692 return str - start;
3693 }
3694 else {
3695 str += converted;
3696 len -= converted;
3697 }
3698 }
3699 /* failed to find the undecodable byte sequence */
3700 return 0;
3701#endif
3702 return 0;
3703}
3704
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003705PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003706PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003707 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003708{
3709 wchar_t smallbuf[256];
3710 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3711 wchar_t *wstr;
3712 size_t wlen, wlen2;
3713 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003714 int surrogateescape;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003715 size_t error_pos, errlen;
Victor Stinner2f197072011-12-17 07:08:30 +01003716 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003717 PyObject *exc, *reason = NULL; /* initialize to prevent gcc warning */
Victor Stinner1b579672011-12-17 05:47:23 +01003718
3719 if (locale_error_handler(errors, &surrogateescape) < 0)
3720 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003721
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003722 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3723 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003724 return NULL;
3725 }
3726
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003727 if (surrogateescape) {
3728 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003729 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003730 if (wstr == NULL) {
3731 if (wlen == (size_t)-1)
3732 PyErr_NoMemory();
3733 else
3734 PyErr_SetFromErrno(PyExc_OSError);
3735 return NULL;
3736 }
3737
3738 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003739 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003740 }
3741 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003742 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003743#ifndef HAVE_BROKEN_MBSTOWCS
3744 wlen = mbstowcs(NULL, str, 0);
3745#else
3746 wlen = len;
3747#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003748 if (wlen == (size_t)-1)
3749 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003750 if (wlen+1 <= smallbuf_len) {
3751 wstr = smallbuf;
3752 }
3753 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003754 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003755 if (!wstr)
3756 return PyErr_NoMemory();
3757 }
3758
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003759 wlen2 = mbstowcs(wstr, str, wlen+1);
3760 if (wlen2 == (size_t)-1) {
3761 if (wstr != smallbuf)
3762 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003763 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003764 }
3765#ifdef HAVE_BROKEN_MBSTOWCS
3766 assert(wlen2 == wlen);
3767#endif
3768 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3769 if (wstr != smallbuf)
3770 PyMem_Free(wstr);
3771 }
3772 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003773
3774decode_error:
3775 errmsg = strerror(errno);
3776 assert(errmsg != NULL);
3777
3778 error_pos = mbstowcs_errorpos(str, len);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003779 wstr = Py_DecodeLocale(errmsg, &errlen);
3780 if (wstr != NULL) {
3781 reason = PyUnicode_FromWideChar(wstr, errlen);
3782 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003783 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003784
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003785 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003786 reason = PyUnicode_FromString(
3787 "mbstowcs() encountered an invalid multibyte sequence");
3788 if (reason == NULL)
3789 return NULL;
3790
3791 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3792 "locale", str, len,
3793 (Py_ssize_t)error_pos,
3794 (Py_ssize_t)(error_pos+1),
3795 reason);
3796 Py_DECREF(reason);
3797 if (exc != NULL) {
3798 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003799 Py_DECREF(exc);
Victor Stinner2f197072011-12-17 07:08:30 +01003800 }
3801 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003802}
3803
3804PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003805PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003806{
3807 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003808 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003809}
3810
3811
3812PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003813PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003814 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003815 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3816}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003817
Christian Heimes5894ba72007-11-04 11:43:14 +00003818PyObject*
3819PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3820{
Steve Dowercc16be82016-09-08 10:35:16 -07003821#if defined(__APPLE__)
3822 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003823#else
Victor Stinner793b5312011-04-27 00:24:21 +02003824 PyInterpreterState *interp = PyThreadState_GET()->interp;
3825 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3826 cannot use it to encode and decode filenames before it is loaded. Load
3827 the Python codec requires to encode at least its own filename. Use the C
3828 version of the locale codec until the codec registry is initialized and
3829 the Python codec is loaded.
3830
3831 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3832 cannot only rely on it: check also interp->fscodec_initialized for
3833 subinterpreters. */
3834 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003835 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003836 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003837 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003838 }
3839 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003840 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003841 }
Victor Stinnerad158722010-10-27 00:25:46 +00003842#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003843}
3844
Martin v. Löwis011e8422009-05-05 04:43:17 +00003845
3846int
3847PyUnicode_FSConverter(PyObject* arg, void* addr)
3848{
Brett Cannonec6ce872016-09-06 15:50:29 -07003849 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003850 PyObject *output = NULL;
3851 Py_ssize_t size;
3852 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003853 if (arg == NULL) {
3854 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003855 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003856 return 1;
3857 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003858 path = PyOS_FSPath(arg);
3859 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003860 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003861 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003862 if (PyBytes_Check(path)) {
3863 output = path;
3864 }
3865 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3866 output = PyUnicode_EncodeFSDefault(path);
3867 Py_DECREF(path);
3868 if (!output) {
3869 return 0;
3870 }
3871 assert(PyBytes_Check(output));
3872 }
3873
Victor Stinner0ea2a462010-04-30 00:22:08 +00003874 size = PyBytes_GET_SIZE(output);
3875 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003876 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003877 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003878 Py_DECREF(output);
3879 return 0;
3880 }
3881 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003882 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003883}
3884
3885
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003886int
3887PyUnicode_FSDecoder(PyObject* arg, void* addr)
3888{
Brett Cannona5711202016-09-06 19:36:01 -07003889 int is_buffer = 0;
3890 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003891 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003892 if (arg == NULL) {
3893 Py_DECREF(*(PyObject**)addr);
3894 return 1;
3895 }
Brett Cannona5711202016-09-06 19:36:01 -07003896
3897 is_buffer = PyObject_CheckBuffer(arg);
3898 if (!is_buffer) {
3899 path = PyOS_FSPath(arg);
3900 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003901 return 0;
3902 }
Brett Cannona5711202016-09-06 19:36:01 -07003903 }
3904 else {
3905 path = arg;
3906 Py_INCREF(arg);
3907 }
3908
3909 if (PyUnicode_Check(path)) {
3910 if (PyUnicode_READY(path) == -1) {
3911 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003912 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003913 }
3914 output = path;
3915 }
3916 else if (PyBytes_Check(path) || is_buffer) {
3917 PyObject *path_bytes = NULL;
3918
3919 if (!PyBytes_Check(path) &&
3920 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3921 "path should be string, bytes, or os.PathLike, not %.200s",
3922 Py_TYPE(arg)->tp_name)) {
3923 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003924 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003925 }
3926 path_bytes = PyBytes_FromObject(path);
3927 Py_DECREF(path);
3928 if (!path_bytes) {
3929 return 0;
3930 }
3931 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3932 PyBytes_GET_SIZE(path_bytes));
3933 Py_DECREF(path_bytes);
3934 if (!output) {
3935 return 0;
3936 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003937 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003938 else {
3939 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003940 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003941 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003942 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003943 return 0;
3944 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003945 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003946 Py_DECREF(output);
3947 return 0;
3948 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003949 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003950 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003951 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003952 Py_DECREF(output);
3953 return 0;
3954 }
3955 *(PyObject**)addr = output;
3956 return Py_CLEANUP_SUPPORTED;
3957}
3958
3959
Martin v. Löwis5b222132007-06-10 09:51:05 +00003960char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003961PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003962{
Christian Heimesf3863112007-11-22 07:46:41 +00003963 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003964
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003965 if (!PyUnicode_Check(unicode)) {
3966 PyErr_BadArgument();
3967 return NULL;
3968 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003969 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003970 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003971
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003972 if (PyUnicode_UTF8(unicode) == NULL) {
3973 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003974 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003975 if (bytes == NULL)
3976 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003977 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3978 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003979 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003980 Py_DECREF(bytes);
3981 return NULL;
3982 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003983 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003984 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003985 PyBytes_AS_STRING(bytes),
3986 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003987 Py_DECREF(bytes);
3988 }
3989
3990 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003991 *psize = PyUnicode_UTF8_LENGTH(unicode);
3992 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003993}
3994
3995char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003996PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003997{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003998 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3999}
4000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004001Py_UNICODE *
4002PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4003{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004 const unsigned char *one_byte;
4005#if SIZEOF_WCHAR_T == 4
4006 const Py_UCS2 *two_bytes;
4007#else
4008 const Py_UCS4 *four_bytes;
4009 const Py_UCS4 *ucs4_end;
4010 Py_ssize_t num_surrogates;
4011#endif
4012 wchar_t *w;
4013 wchar_t *wchar_end;
4014
4015 if (!PyUnicode_Check(unicode)) {
4016 PyErr_BadArgument();
4017 return NULL;
4018 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004019 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004020 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004021 assert(_PyUnicode_KIND(unicode) != 0);
4022 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004023
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004024 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004025#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004026 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4027 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004028 num_surrogates = 0;
4029
4030 for (; four_bytes < ucs4_end; ++four_bytes) {
4031 if (*four_bytes > 0xFFFF)
4032 ++num_surrogates;
4033 }
4034
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004035 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4036 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4037 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038 PyErr_NoMemory();
4039 return NULL;
4040 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004041 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004042
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004043 w = _PyUnicode_WSTR(unicode);
4044 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4045 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004046 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4047 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004048 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004049 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004050 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4051 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004052 }
4053 else
4054 *w = *four_bytes;
4055
4056 if (w > wchar_end) {
4057 assert(0 && "Miscalculated string end");
4058 }
4059 }
4060 *w = 0;
4061#else
4062 /* sizeof(wchar_t) == 4 */
4063 Py_FatalError("Impossible unicode object state, wstr and str "
4064 "should share memory already.");
4065 return NULL;
4066#endif
4067 }
4068 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004069 if ((size_t)_PyUnicode_LENGTH(unicode) >
4070 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4071 PyErr_NoMemory();
4072 return NULL;
4073 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004074 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4075 (_PyUnicode_LENGTH(unicode) + 1));
4076 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004077 PyErr_NoMemory();
4078 return NULL;
4079 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004080 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4081 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4082 w = _PyUnicode_WSTR(unicode);
4083 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004084
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004085 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4086 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004087 for (; w < wchar_end; ++one_byte, ++w)
4088 *w = *one_byte;
4089 /* null-terminate the wstr */
4090 *w = 0;
4091 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004092 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004093#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004094 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004095 for (; w < wchar_end; ++two_bytes, ++w)
4096 *w = *two_bytes;
4097 /* null-terminate the wstr */
4098 *w = 0;
4099#else
4100 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004101 PyObject_FREE(_PyUnicode_WSTR(unicode));
4102 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004103 Py_FatalError("Impossible unicode object state, wstr "
4104 "and str should share memory already.");
4105 return NULL;
4106#endif
4107 }
4108 else {
4109 assert(0 && "This should never happen.");
4110 }
4111 }
4112 }
4113 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004114 *size = PyUnicode_WSTR_LENGTH(unicode);
4115 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004116}
4117
Alexander Belopolsky40018472011-02-26 01:02:56 +00004118Py_UNICODE *
4119PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004120{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004121 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004122}
4123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004124
Alexander Belopolsky40018472011-02-26 01:02:56 +00004125Py_ssize_t
4126PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004127{
4128 if (!PyUnicode_Check(unicode)) {
4129 PyErr_BadArgument();
4130 goto onError;
4131 }
4132 return PyUnicode_GET_SIZE(unicode);
4133
Benjamin Peterson29060642009-01-31 22:14:21 +00004134 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004135 return -1;
4136}
4137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004138Py_ssize_t
4139PyUnicode_GetLength(PyObject *unicode)
4140{
Victor Stinner07621332012-06-16 04:53:46 +02004141 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004142 PyErr_BadArgument();
4143 return -1;
4144 }
Victor Stinner07621332012-06-16 04:53:46 +02004145 if (PyUnicode_READY(unicode) == -1)
4146 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004147 return PyUnicode_GET_LENGTH(unicode);
4148}
4149
4150Py_UCS4
4151PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4152{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004153 void *data;
4154 int kind;
4155
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004156 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4157 PyErr_BadArgument();
4158 return (Py_UCS4)-1;
4159 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004160 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004161 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004162 return (Py_UCS4)-1;
4163 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004164 data = PyUnicode_DATA(unicode);
4165 kind = PyUnicode_KIND(unicode);
4166 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004167}
4168
4169int
4170PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4171{
4172 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004173 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004174 return -1;
4175 }
Victor Stinner488fa492011-12-12 00:01:39 +01004176 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004177 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004178 PyErr_SetString(PyExc_IndexError, "string index out of range");
4179 return -1;
4180 }
Victor Stinner488fa492011-12-12 00:01:39 +01004181 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004182 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004183 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4184 PyErr_SetString(PyExc_ValueError, "character out of range");
4185 return -1;
4186 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004187 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4188 index, ch);
4189 return 0;
4190}
4191
Alexander Belopolsky40018472011-02-26 01:02:56 +00004192const char *
4193PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004194{
Victor Stinner42cb4622010-09-01 19:39:01 +00004195 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004196}
4197
Victor Stinner554f3f02010-06-16 23:33:54 +00004198/* create or adjust a UnicodeDecodeError */
4199static void
4200make_decode_exception(PyObject **exceptionObject,
4201 const char *encoding,
4202 const char *input, Py_ssize_t length,
4203 Py_ssize_t startpos, Py_ssize_t endpos,
4204 const char *reason)
4205{
4206 if (*exceptionObject == NULL) {
4207 *exceptionObject = PyUnicodeDecodeError_Create(
4208 encoding, input, length, startpos, endpos, reason);
4209 }
4210 else {
4211 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4212 goto onError;
4213 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4214 goto onError;
4215 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4216 goto onError;
4217 }
4218 return;
4219
4220onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004221 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004222}
4223
Steve Dowercc16be82016-09-08 10:35:16 -07004224#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004225/* error handling callback helper:
4226 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004227 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004228 and adjust various state variables.
4229 return 0 on success, -1 on error
4230*/
4231
Alexander Belopolsky40018472011-02-26 01:02:56 +00004232static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004233unicode_decode_call_errorhandler_wchar(
4234 const char *errors, PyObject **errorHandler,
4235 const char *encoding, const char *reason,
4236 const char **input, const char **inend, Py_ssize_t *startinpos,
4237 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4238 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004239{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004240 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004241
4242 PyObject *restuple = NULL;
4243 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004244 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004245 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004246 Py_ssize_t requiredsize;
4247 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004248 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004249 wchar_t *repwstr;
4250 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004251
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004252 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4253 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004254
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004255 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004256 *errorHandler = PyCodec_LookupError(errors);
4257 if (*errorHandler == NULL)
4258 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004259 }
4260
Victor Stinner554f3f02010-06-16 23:33:54 +00004261 make_decode_exception(exceptionObject,
4262 encoding,
4263 *input, *inend - *input,
4264 *startinpos, *endinpos,
4265 reason);
4266 if (*exceptionObject == NULL)
4267 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004268
4269 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4270 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004271 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004272 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004273 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004274 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004275 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004276 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004277 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004278
4279 /* Copy back the bytes variables, which might have been modified by the
4280 callback */
4281 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4282 if (!inputobj)
4283 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004284 *input = PyBytes_AS_STRING(inputobj);
4285 insize = PyBytes_GET_SIZE(inputobj);
4286 *inend = *input + insize;
4287 /* we can DECREF safely, as the exception has another reference,
4288 so the object won't go away. */
4289 Py_DECREF(inputobj);
4290
4291 if (newpos<0)
4292 newpos = insize+newpos;
4293 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004294 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004295 goto onError;
4296 }
4297
4298 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4299 if (repwstr == NULL)
4300 goto onError;
4301 /* need more space? (at least enough for what we
4302 have+the replacement+the rest of the string (starting
4303 at the new input position), so we won't have to check space
4304 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004305 requiredsize = *outpos;
4306 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4307 goto overflow;
4308 requiredsize += repwlen;
4309 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4310 goto overflow;
4311 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004312 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004313 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004314 requiredsize = 2*outsize;
4315 if (unicode_resize(output, requiredsize) < 0)
4316 goto onError;
4317 }
4318 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4319 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004320 *endinpos = newpos;
4321 *inptr = *input + newpos;
4322
4323 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004324 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004325 return 0;
4326
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004327 overflow:
4328 PyErr_SetString(PyExc_OverflowError,
4329 "decoded result is too long for a Python string");
4330
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004331 onError:
4332 Py_XDECREF(restuple);
4333 return -1;
4334}
Steve Dowercc16be82016-09-08 10:35:16 -07004335#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004336
4337static int
4338unicode_decode_call_errorhandler_writer(
4339 const char *errors, PyObject **errorHandler,
4340 const char *encoding, const char *reason,
4341 const char **input, const char **inend, Py_ssize_t *startinpos,
4342 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4343 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4344{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004345 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004346
4347 PyObject *restuple = NULL;
4348 PyObject *repunicode = NULL;
4349 Py_ssize_t insize;
4350 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004351 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004352 PyObject *inputobj = NULL;
4353
4354 if (*errorHandler == NULL) {
4355 *errorHandler = PyCodec_LookupError(errors);
4356 if (*errorHandler == NULL)
4357 goto onError;
4358 }
4359
4360 make_decode_exception(exceptionObject,
4361 encoding,
4362 *input, *inend - *input,
4363 *startinpos, *endinpos,
4364 reason);
4365 if (*exceptionObject == NULL)
4366 goto onError;
4367
4368 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4369 if (restuple == NULL)
4370 goto onError;
4371 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004372 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004373 goto onError;
4374 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004375 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004376 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004377
4378 /* Copy back the bytes variables, which might have been modified by the
4379 callback */
4380 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4381 if (!inputobj)
4382 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004383 *input = PyBytes_AS_STRING(inputobj);
4384 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004385 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004386 /* we can DECREF safely, as the exception has another reference,
4387 so the object won't go away. */
4388 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004389
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004390 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004391 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004392 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004393 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004394 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004395 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004396
Victor Stinner170ca6f2013-04-18 00:25:28 +02004397 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004398 if (replen > 1) {
4399 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004400 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004401 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4402 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4403 goto onError;
4404 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004405 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004406 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004407
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004408 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004409 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004410
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004411 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004412 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004413 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004414
Benjamin Peterson29060642009-01-31 22:14:21 +00004415 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004416 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004417 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004418}
4419
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004420/* --- UTF-7 Codec -------------------------------------------------------- */
4421
Antoine Pitrou244651a2009-05-04 18:56:13 +00004422/* See RFC2152 for details. We encode conservatively and decode liberally. */
4423
4424/* Three simple macros defining base-64. */
4425
4426/* Is c a base-64 character? */
4427
4428#define IS_BASE64(c) \
4429 (((c) >= 'A' && (c) <= 'Z') || \
4430 ((c) >= 'a' && (c) <= 'z') || \
4431 ((c) >= '0' && (c) <= '9') || \
4432 (c) == '+' || (c) == '/')
4433
4434/* given that c is a base-64 character, what is its base-64 value? */
4435
4436#define FROM_BASE64(c) \
4437 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4438 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4439 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4440 (c) == '+' ? 62 : 63)
4441
4442/* What is the base-64 character of the bottom 6 bits of n? */
4443
4444#define TO_BASE64(n) \
4445 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4446
4447/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4448 * decoded as itself. We are permissive on decoding; the only ASCII
4449 * byte not decoding to itself is the + which begins a base64
4450 * string. */
4451
4452#define DECODE_DIRECT(c) \
4453 ((c) <= 127 && (c) != '+')
4454
4455/* The UTF-7 encoder treats ASCII characters differently according to
4456 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4457 * the above). See RFC2152. This array identifies these different
4458 * sets:
4459 * 0 : "Set D"
4460 * alphanumeric and '(),-./:?
4461 * 1 : "Set O"
4462 * !"#$%&*;<=>@[]^_`{|}
4463 * 2 : "whitespace"
4464 * ht nl cr sp
4465 * 3 : special (must be base64 encoded)
4466 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4467 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004468
Tim Petersced69f82003-09-16 20:30:58 +00004469static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470char utf7_category[128] = {
4471/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4472 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4473/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4474 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4475/* sp ! " # $ % & ' ( ) * + , - . / */
4476 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4477/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4478 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4479/* @ A B C D E F G H I J K L M N O */
4480 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4481/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4482 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4483/* ` a b c d e f g h i j k l m n o */
4484 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4485/* p q r s t u v w x y z { | } ~ del */
4486 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004487};
4488
Antoine Pitrou244651a2009-05-04 18:56:13 +00004489/* ENCODE_DIRECT: this character should be encoded as itself. The
4490 * answer depends on whether we are encoding set O as itself, and also
4491 * on whether we are encoding whitespace as itself. RFC2152 makes it
4492 * clear that the answers to these questions vary between
4493 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004494
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495#define ENCODE_DIRECT(c, directO, directWS) \
4496 ((c) < 128 && (c) > 0 && \
4497 ((utf7_category[(c)] == 0) || \
4498 (directWS && (utf7_category[(c)] == 2)) || \
4499 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004500
Alexander Belopolsky40018472011-02-26 01:02:56 +00004501PyObject *
4502PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004503 Py_ssize_t size,
4504 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004506 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4507}
4508
Antoine Pitrou244651a2009-05-04 18:56:13 +00004509/* The decoder. The only state we preserve is our read position,
4510 * i.e. how many characters we have consumed. So if we end in the
4511 * middle of a shift sequence we have to back off the read position
4512 * and the output to the beginning of the sequence, otherwise we lose
4513 * all the shift state (seen bits, number of bits seen, high
4514 * surrogate). */
4515
Alexander Belopolsky40018472011-02-26 01:02:56 +00004516PyObject *
4517PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004518 Py_ssize_t size,
4519 const char *errors,
4520 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004521{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004522 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004523 Py_ssize_t startinpos;
4524 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004526 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004527 const char *errmsg = "";
4528 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004529 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004530 unsigned int base64bits = 0;
4531 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004532 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004533 PyObject *errorHandler = NULL;
4534 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004535
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004536 if (size == 0) {
4537 if (consumed)
4538 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004539 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004540 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004541
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004542 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004543 _PyUnicodeWriter_Init(&writer);
4544 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004545
4546 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004547 e = s + size;
4548
4549 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004550 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004551 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004552 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004553
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554 if (inShift) { /* in a base-64 section */
4555 if (IS_BASE64(ch)) { /* consume a base-64 character */
4556 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4557 base64bits += 6;
4558 s++;
4559 if (base64bits >= 16) {
4560 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004561 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004562 base64bits -= 16;
4563 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004564 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004565 if (surrogate) {
4566 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004567 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4568 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004569 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004570 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004571 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004572 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 }
4574 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004575 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004576 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004578 }
4579 }
Victor Stinner551ac952011-11-29 22:58:13 +01004580 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 /* first surrogate */
4582 surrogate = outCh;
4583 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004585 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004586 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004587 }
4588 }
4589 }
4590 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004591 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004592 if (base64bits > 0) { /* left-over bits */
4593 if (base64bits >= 6) {
4594 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004595 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 errmsg = "partial character in shift sequence";
4597 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004598 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004599 else {
4600 /* Some bits remain; they should be zero */
4601 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004602 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004603 errmsg = "non-zero padding bits in shift sequence";
4604 goto utf7Error;
4605 }
4606 }
4607 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004608 if (surrogate && DECODE_DIRECT(ch)) {
4609 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4610 goto onError;
4611 }
4612 surrogate = 0;
4613 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004614 /* '-' is absorbed; other terminating
4615 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004616 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004617 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004618 }
4619 }
4620 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004621 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004622 s++; /* consume '+' */
4623 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004624 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004625 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004626 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004627 }
4628 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004629 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004630 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004631 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004632 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004633 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004634 }
4635 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004636 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004637 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004638 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004639 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004640 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004641 else {
4642 startinpos = s-starts;
4643 s++;
4644 errmsg = "unexpected special character";
4645 goto utf7Error;
4646 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004647 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004648utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004649 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004650 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004651 errors, &errorHandler,
4652 "utf7", errmsg,
4653 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004654 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004655 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004656 }
4657
Antoine Pitrou244651a2009-05-04 18:56:13 +00004658 /* end of string */
4659
4660 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4661 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004662 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004663 if (surrogate ||
4664 (base64bits >= 6) ||
4665 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004666 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004667 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004668 errors, &errorHandler,
4669 "utf7", "unterminated shift sequence",
4670 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004671 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004672 goto onError;
4673 if (s < e)
4674 goto restart;
4675 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004676 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004677
4678 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004679 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004680 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004681 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004682 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004683 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004684 writer.kind, writer.data, shiftOutStart);
4685 Py_XDECREF(errorHandler);
4686 Py_XDECREF(exc);
4687 _PyUnicodeWriter_Dealloc(&writer);
4688 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004689 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004690 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004691 }
4692 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004693 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004694 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004695 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004696
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004697 Py_XDECREF(errorHandler);
4698 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004699 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004700
Benjamin Peterson29060642009-01-31 22:14:21 +00004701 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004702 Py_XDECREF(errorHandler);
4703 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004704 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004705 return NULL;
4706}
4707
4708
Alexander Belopolsky40018472011-02-26 01:02:56 +00004709PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004710_PyUnicode_EncodeUTF7(PyObject *str,
4711 int base64SetO,
4712 int base64WhiteSpace,
4713 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004714{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004715 int kind;
4716 void *data;
4717 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004718 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004719 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004720 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004721 unsigned int base64bits = 0;
4722 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004723 char * out;
4724 char * start;
4725
Benjamin Petersonbac79492012-01-14 13:34:47 -05004726 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004727 return NULL;
4728 kind = PyUnicode_KIND(str);
4729 data = PyUnicode_DATA(str);
4730 len = PyUnicode_GET_LENGTH(str);
4731
4732 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004733 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004734
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004735 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004736 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004737 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004738 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004739 if (v == NULL)
4740 return NULL;
4741
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004742 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004743 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004744 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004745
Antoine Pitrou244651a2009-05-04 18:56:13 +00004746 if (inShift) {
4747 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4748 /* shifting out */
4749 if (base64bits) { /* output remaining bits */
4750 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4751 base64buffer = 0;
4752 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004753 }
4754 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004755 /* Characters not in the BASE64 set implicitly unshift the sequence
4756 so no '-' is required, except if the character is itself a '-' */
4757 if (IS_BASE64(ch) || ch == '-') {
4758 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004759 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004760 *out++ = (char) ch;
4761 }
4762 else {
4763 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004764 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004765 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004766 else { /* not in a shift sequence */
4767 if (ch == '+') {
4768 *out++ = '+';
4769 *out++ = '-';
4770 }
4771 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4772 *out++ = (char) ch;
4773 }
4774 else {
4775 *out++ = '+';
4776 inShift = 1;
4777 goto encode_char;
4778 }
4779 }
4780 continue;
4781encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004782 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004783 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004784
Antoine Pitrou244651a2009-05-04 18:56:13 +00004785 /* code first surrogate */
4786 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004787 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004788 while (base64bits >= 6) {
4789 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4790 base64bits -= 6;
4791 }
4792 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004793 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004794 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004795 base64bits += 16;
4796 base64buffer = (base64buffer << 16) | ch;
4797 while (base64bits >= 6) {
4798 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4799 base64bits -= 6;
4800 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004801 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004802 if (base64bits)
4803 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4804 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004805 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004806 if (_PyBytes_Resize(&v, out - start) < 0)
4807 return NULL;
4808 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004809}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004810PyObject *
4811PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4812 Py_ssize_t size,
4813 int base64SetO,
4814 int base64WhiteSpace,
4815 const char *errors)
4816{
4817 PyObject *result;
4818 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4819 if (tmp == NULL)
4820 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004821 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004822 base64WhiteSpace, errors);
4823 Py_DECREF(tmp);
4824 return result;
4825}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004826
Antoine Pitrou244651a2009-05-04 18:56:13 +00004827#undef IS_BASE64
4828#undef FROM_BASE64
4829#undef TO_BASE64
4830#undef DECODE_DIRECT
4831#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004832
Guido van Rossumd57fd912000-03-10 22:53:23 +00004833/* --- UTF-8 Codec -------------------------------------------------------- */
4834
Alexander Belopolsky40018472011-02-26 01:02:56 +00004835PyObject *
4836PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004837 Py_ssize_t size,
4838 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004839{
Walter Dörwald69652032004-09-07 20:24:22 +00004840 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4841}
4842
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843#include "stringlib/asciilib.h"
4844#include "stringlib/codecs.h"
4845#include "stringlib/undef.h"
4846
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004847#include "stringlib/ucs1lib.h"
4848#include "stringlib/codecs.h"
4849#include "stringlib/undef.h"
4850
4851#include "stringlib/ucs2lib.h"
4852#include "stringlib/codecs.h"
4853#include "stringlib/undef.h"
4854
4855#include "stringlib/ucs4lib.h"
4856#include "stringlib/codecs.h"
4857#include "stringlib/undef.h"
4858
Antoine Pitrouab868312009-01-10 15:40:25 +00004859/* Mask to quickly check whether a C 'long' contains a
4860 non-ASCII, UTF8-encoded char. */
4861#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004862# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004863#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004864# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004865#else
4866# error C 'long' size should be either 4 or 8!
4867#endif
4868
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004869static Py_ssize_t
4870ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004871{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004872 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004873 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004874
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004875 /*
4876 * Issue #17237: m68k is a bit different from most architectures in
4877 * that objects do not use "natural alignment" - for example, int and
4878 * long are only aligned at 2-byte boundaries. Therefore the assert()
4879 * won't work; also, tests have shown that skipping the "optimised
4880 * version" will even speed up m68k.
4881 */
4882#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004883#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004884 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4885 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004886 /* Fast path, see in STRINGLIB(utf8_decode) for
4887 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004888 /* Help allocation */
4889 const char *_p = p;
4890 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004891 while (_p < aligned_end) {
4892 unsigned long value = *(const unsigned long *) _p;
4893 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004894 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004895 *((unsigned long *)q) = value;
4896 _p += SIZEOF_LONG;
4897 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004898 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004899 p = _p;
4900 while (p < end) {
4901 if ((unsigned char)*p & 0x80)
4902 break;
4903 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004904 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004905 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004906 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004907#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004908#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004909 while (p < end) {
4910 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4911 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004912 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004913 /* Help allocation */
4914 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004915 while (_p < aligned_end) {
4916 unsigned long value = *(unsigned long *) _p;
4917 if (value & ASCII_CHAR_MASK)
4918 break;
4919 _p += SIZEOF_LONG;
4920 }
4921 p = _p;
4922 if (_p == end)
4923 break;
4924 }
4925 if ((unsigned char)*p & 0x80)
4926 break;
4927 ++p;
4928 }
4929 memcpy(dest, start, p - start);
4930 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004931}
Antoine Pitrouab868312009-01-10 15:40:25 +00004932
Victor Stinner785938e2011-12-11 20:09:03 +01004933PyObject *
4934PyUnicode_DecodeUTF8Stateful(const char *s,
4935 Py_ssize_t size,
4936 const char *errors,
4937 Py_ssize_t *consumed)
4938{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004939 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004940 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004941 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004942
4943 Py_ssize_t startinpos;
4944 Py_ssize_t endinpos;
4945 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004946 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004947 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004948 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004949
4950 if (size == 0) {
4951 if (consumed)
4952 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004953 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004954 }
4955
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004956 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4957 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004958 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004959 *consumed = 1;
4960 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004961 }
4962
Victor Stinner8f674cc2013-04-17 23:02:17 +02004963 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004964 writer.min_length = size;
4965 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004966 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004967
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004968 writer.pos = ascii_decode(s, end, writer.data);
4969 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004970 while (s < end) {
4971 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004972 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004973
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004974 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004975 if (PyUnicode_IS_ASCII(writer.buffer))
4976 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004977 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004978 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004979 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004980 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004981 } else {
4982 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004983 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004984 }
4985
4986 switch (ch) {
4987 case 0:
4988 if (s == end || consumed)
4989 goto End;
4990 errmsg = "unexpected end of data";
4991 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004992 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004993 break;
4994 case 1:
4995 errmsg = "invalid start byte";
4996 startinpos = s - starts;
4997 endinpos = startinpos + 1;
4998 break;
4999 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005000 case 3:
5001 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005002 errmsg = "invalid continuation byte";
5003 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005004 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005005 break;
5006 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005007 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005008 goto onError;
5009 continue;
5010 }
5011
Victor Stinner1d65d912015-10-05 13:43:50 +02005012 if (error_handler == _Py_ERROR_UNKNOWN)
5013 error_handler = get_error_handler(errors);
5014
5015 switch (error_handler) {
5016 case _Py_ERROR_IGNORE:
5017 s += (endinpos - startinpos);
5018 break;
5019
5020 case _Py_ERROR_REPLACE:
5021 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5022 goto onError;
5023 s += (endinpos - startinpos);
5024 break;
5025
5026 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005027 {
5028 Py_ssize_t i;
5029
Victor Stinner1d65d912015-10-05 13:43:50 +02005030 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5031 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005032 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005033 ch = (Py_UCS4)(unsigned char)(starts[i]);
5034 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5035 ch + 0xdc00);
5036 writer.pos++;
5037 }
5038 s += (endinpos - startinpos);
5039 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005040 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005041
5042 default:
5043 if (unicode_decode_call_errorhandler_writer(
5044 errors, &error_handler_obj,
5045 "utf-8", errmsg,
5046 &starts, &end, &startinpos, &endinpos, &exc, &s,
5047 &writer))
5048 goto onError;
5049 }
Victor Stinner785938e2011-12-11 20:09:03 +01005050 }
5051
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005052End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005053 if (consumed)
5054 *consumed = s - starts;
5055
Victor Stinner1d65d912015-10-05 13:43:50 +02005056 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005057 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005058 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005059
5060onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005061 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005062 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005063 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005064 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005065}
5066
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005067#ifdef __APPLE__
5068
5069/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005070 used to decode the command line arguments on Mac OS X.
5071
5072 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005073 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005074
5075wchar_t*
5076_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5077{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005078 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005079 wchar_t *unicode;
5080 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005081
5082 /* Note: size will always be longer than the resulting Unicode
5083 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005084 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005085 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005086 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005087 if (!unicode)
5088 return NULL;
5089
5090 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005091 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005092 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005093 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005094 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005095#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005096 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005097#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005098 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005099#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005100 if (ch > 0xFF) {
5101#if SIZEOF_WCHAR_T == 4
5102 assert(0);
5103#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005104 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005105 /* compute and append the two surrogates: */
5106 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5107 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5108#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005109 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005110 else {
5111 if (!ch && s == e)
5112 break;
5113 /* surrogateescape */
5114 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5115 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005116 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005117 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005118 return unicode;
5119}
5120
5121#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005123/* Primary internal function which creates utf8 encoded bytes objects.
5124
5125 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005126 and allocate exactly as much space needed at the end. Else allocate the
5127 maximum possible needed (4 result bytes per Unicode character), and return
5128 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005129*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005130PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005131_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005132{
Victor Stinner6099a032011-12-18 14:22:26 +01005133 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005134 void *data;
5135 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005137 if (!PyUnicode_Check(unicode)) {
5138 PyErr_BadArgument();
5139 return NULL;
5140 }
5141
5142 if (PyUnicode_READY(unicode) == -1)
5143 return NULL;
5144
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005145 if (PyUnicode_UTF8(unicode))
5146 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5147 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005148
5149 kind = PyUnicode_KIND(unicode);
5150 data = PyUnicode_DATA(unicode);
5151 size = PyUnicode_GET_LENGTH(unicode);
5152
Benjamin Petersonead6b532011-12-20 17:23:42 -06005153 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005154 default:
5155 assert(0);
5156 case PyUnicode_1BYTE_KIND:
5157 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5158 assert(!PyUnicode_IS_ASCII(unicode));
5159 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5160 case PyUnicode_2BYTE_KIND:
5161 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5162 case PyUnicode_4BYTE_KIND:
5163 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005164 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005165}
5166
Alexander Belopolsky40018472011-02-26 01:02:56 +00005167PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005168PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5169 Py_ssize_t size,
5170 const char *errors)
5171{
5172 PyObject *v, *unicode;
5173
5174 unicode = PyUnicode_FromUnicode(s, size);
5175 if (unicode == NULL)
5176 return NULL;
5177 v = _PyUnicode_AsUTF8String(unicode, errors);
5178 Py_DECREF(unicode);
5179 return v;
5180}
5181
5182PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005183PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005184{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005185 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005186}
5187
Walter Dörwald41980ca2007-08-16 21:55:45 +00005188/* --- UTF-32 Codec ------------------------------------------------------- */
5189
5190PyObject *
5191PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005192 Py_ssize_t size,
5193 const char *errors,
5194 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005195{
5196 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5197}
5198
5199PyObject *
5200PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005201 Py_ssize_t size,
5202 const char *errors,
5203 int *byteorder,
5204 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005205{
5206 const char *starts = s;
5207 Py_ssize_t startinpos;
5208 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005209 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005210 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005211 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005212 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005213 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005214 PyObject *errorHandler = NULL;
5215 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005216
Walter Dörwald41980ca2007-08-16 21:55:45 +00005217 q = (unsigned char *)s;
5218 e = q + size;
5219
5220 if (byteorder)
5221 bo = *byteorder;
5222
5223 /* Check for BOM marks (U+FEFF) in the input and adjust current
5224 byte order setting accordingly. In native mode, the leading BOM
5225 mark is skipped, in all other modes, it is copied to the output
5226 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005227 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005228 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005229 if (bom == 0x0000FEFF) {
5230 bo = -1;
5231 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005232 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005233 else if (bom == 0xFFFE0000) {
5234 bo = 1;
5235 q += 4;
5236 }
5237 if (byteorder)
5238 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005239 }
5240
Victor Stinnere64322e2012-10-30 23:12:47 +01005241 if (q == e) {
5242 if (consumed)
5243 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005244 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005245 }
5246
Victor Stinnere64322e2012-10-30 23:12:47 +01005247#ifdef WORDS_BIGENDIAN
5248 le = bo < 0;
5249#else
5250 le = bo <= 0;
5251#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005252 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005253
Victor Stinner8f674cc2013-04-17 23:02:17 +02005254 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005255 writer.min_length = (e - q + 3) / 4;
5256 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005257 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005258
Victor Stinnere64322e2012-10-30 23:12:47 +01005259 while (1) {
5260 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005261 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005262
Victor Stinnere64322e2012-10-30 23:12:47 +01005263 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005264 enum PyUnicode_Kind kind = writer.kind;
5265 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005266 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005267 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005268 if (le) {
5269 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005270 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005271 if (ch > maxch)
5272 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005273 if (kind != PyUnicode_1BYTE_KIND &&
5274 Py_UNICODE_IS_SURROGATE(ch))
5275 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005276 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005277 q += 4;
5278 } while (q <= last);
5279 }
5280 else {
5281 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005282 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005283 if (ch > maxch)
5284 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005285 if (kind != PyUnicode_1BYTE_KIND &&
5286 Py_UNICODE_IS_SURROGATE(ch))
5287 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005288 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005289 q += 4;
5290 } while (q <= last);
5291 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005292 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005293 }
5294
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005295 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005296 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005297 startinpos = ((const char *)q) - starts;
5298 endinpos = startinpos + 4;
5299 }
5300 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005301 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005302 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005303 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005304 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005305 startinpos = ((const char *)q) - starts;
5306 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005307 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005308 else {
5309 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005310 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005311 goto onError;
5312 q += 4;
5313 continue;
5314 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005315 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005316 startinpos = ((const char *)q) - starts;
5317 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005318 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005319
5320 /* The remaining input chars are ignored if the callback
5321 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005322 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005323 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005324 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005325 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005326 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005328 }
5329
Walter Dörwald41980ca2007-08-16 21:55:45 +00005330 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005331 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005332
Walter Dörwald41980ca2007-08-16 21:55:45 +00005333 Py_XDECREF(errorHandler);
5334 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005335 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005336
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005338 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005339 Py_XDECREF(errorHandler);
5340 Py_XDECREF(exc);
5341 return NULL;
5342}
5343
5344PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005345_PyUnicode_EncodeUTF32(PyObject *str,
5346 const char *errors,
5347 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005348{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005349 enum PyUnicode_Kind kind;
5350 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005351 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005352 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005353 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005354#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005355 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005356#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005357 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005358#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005359 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005360 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005361 PyObject *errorHandler = NULL;
5362 PyObject *exc = NULL;
5363 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005364
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005365 if (!PyUnicode_Check(str)) {
5366 PyErr_BadArgument();
5367 return NULL;
5368 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005369 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005370 return NULL;
5371 kind = PyUnicode_KIND(str);
5372 data = PyUnicode_DATA(str);
5373 len = PyUnicode_GET_LENGTH(str);
5374
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005375 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005376 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005377 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005378 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005379 if (v == NULL)
5380 return NULL;
5381
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005382 /* output buffer is 4-bytes aligned */
5383 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005384 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005385 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005386 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005387 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005388 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005389
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005390 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005391 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005392 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005393 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005394 else
5395 encoding = "utf-32";
5396
5397 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005398 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5399 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005400 }
5401
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005402 pos = 0;
5403 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005404 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005405
5406 if (kind == PyUnicode_2BYTE_KIND) {
5407 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5408 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005409 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005410 else {
5411 assert(kind == PyUnicode_4BYTE_KIND);
5412 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5413 &out, native_ordering);
5414 }
5415 if (pos == len)
5416 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005417
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005418 rep = unicode_encode_call_errorhandler(
5419 errors, &errorHandler,
5420 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005421 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005422 if (!rep)
5423 goto error;
5424
5425 if (PyBytes_Check(rep)) {
5426 repsize = PyBytes_GET_SIZE(rep);
5427 if (repsize & 3) {
5428 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005429 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005430 "surrogates not allowed");
5431 goto error;
5432 }
5433 moreunits = repsize / 4;
5434 }
5435 else {
5436 assert(PyUnicode_Check(rep));
5437 if (PyUnicode_READY(rep) < 0)
5438 goto error;
5439 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5440 if (!PyUnicode_IS_ASCII(rep)) {
5441 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005442 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005443 "surrogates not allowed");
5444 goto error;
5445 }
5446 }
5447
5448 /* four bytes are reserved for each surrogate */
5449 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005450 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005451 Py_ssize_t morebytes = 4 * (moreunits - 1);
5452 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5453 /* integer overflow */
5454 PyErr_NoMemory();
5455 goto error;
5456 }
5457 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5458 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005459 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005460 }
5461
5462 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005463 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005464 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005465 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005466 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005467 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5468 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 }
5470
5471 Py_CLEAR(rep);
5472 }
5473
5474 /* Cut back to size actually needed. This is necessary for, for example,
5475 encoding of a string containing isolated surrogates and the 'ignore'
5476 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005477 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005478 if (nsize != PyBytes_GET_SIZE(v))
5479 _PyBytes_Resize(&v, nsize);
5480 Py_XDECREF(errorHandler);
5481 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005482 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005483 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005484 error:
5485 Py_XDECREF(rep);
5486 Py_XDECREF(errorHandler);
5487 Py_XDECREF(exc);
5488 Py_XDECREF(v);
5489 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005490}
5491
Alexander Belopolsky40018472011-02-26 01:02:56 +00005492PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005493PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5494 Py_ssize_t size,
5495 const char *errors,
5496 int byteorder)
5497{
5498 PyObject *result;
5499 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5500 if (tmp == NULL)
5501 return NULL;
5502 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5503 Py_DECREF(tmp);
5504 return result;
5505}
5506
5507PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005508PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005509{
Victor Stinnerb960b342011-11-20 19:12:52 +01005510 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005511}
5512
Guido van Rossumd57fd912000-03-10 22:53:23 +00005513/* --- UTF-16 Codec ------------------------------------------------------- */
5514
Tim Peters772747b2001-08-09 22:21:55 +00005515PyObject *
5516PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005517 Py_ssize_t size,
5518 const char *errors,
5519 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005520{
Walter Dörwald69652032004-09-07 20:24:22 +00005521 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5522}
5523
5524PyObject *
5525PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005526 Py_ssize_t size,
5527 const char *errors,
5528 int *byteorder,
5529 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005530{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005531 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005532 Py_ssize_t startinpos;
5533 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005534 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005535 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005536 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005537 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005538 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005539 PyObject *errorHandler = NULL;
5540 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005541 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005542
Tim Peters772747b2001-08-09 22:21:55 +00005543 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005544 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545
5546 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005547 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005548
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005549 /* Check for BOM marks (U+FEFF) in the input and adjust current
5550 byte order setting accordingly. In native mode, the leading BOM
5551 mark is skipped, in all other modes, it is copied to the output
5552 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005553 if (bo == 0 && size >= 2) {
5554 const Py_UCS4 bom = (q[1] << 8) | q[0];
5555 if (bom == 0xFEFF) {
5556 q += 2;
5557 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005558 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005559 else if (bom == 0xFFFE) {
5560 q += 2;
5561 bo = 1;
5562 }
5563 if (byteorder)
5564 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005565 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005566
Antoine Pitrou63065d72012-05-15 23:48:04 +02005567 if (q == e) {
5568 if (consumed)
5569 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005570 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005571 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005572
Christian Heimes743e0cd2012-10-17 23:52:17 +02005573#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005574 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005575 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005576#else
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-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005579#endif
Tim Peters772747b2001-08-09 22:21:55 +00005580
Antoine Pitrou63065d72012-05-15 23:48:04 +02005581 /* Note: size will always be longer than the resulting Unicode
5582 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005583 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005584 writer.min_length = (e - q + 1) / 2;
5585 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005586 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005587
Antoine Pitrou63065d72012-05-15 23:48:04 +02005588 while (1) {
5589 Py_UCS4 ch = 0;
5590 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005591 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005592 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005593 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005594 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005595 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005596 native_ordering);
5597 else
5598 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005599 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005600 native_ordering);
5601 } else if (kind == PyUnicode_2BYTE_KIND) {
5602 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005603 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005604 native_ordering);
5605 } else {
5606 assert(kind == PyUnicode_4BYTE_KIND);
5607 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005608 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005609 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005610 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005611 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005612
Antoine Pitrou63065d72012-05-15 23:48:04 +02005613 switch (ch)
5614 {
5615 case 0:
5616 /* remaining byte at the end? (size should be even) */
5617 if (q == e || consumed)
5618 goto End;
5619 errmsg = "truncated data";
5620 startinpos = ((const char *)q) - starts;
5621 endinpos = ((const char *)e) - starts;
5622 break;
5623 /* The remaining input chars are ignored if the callback
5624 chooses to skip the input */
5625 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005626 q -= 2;
5627 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005628 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005629 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005630 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005631 endinpos = ((const char *)e) - starts;
5632 break;
5633 case 2:
5634 errmsg = "illegal encoding";
5635 startinpos = ((const char *)q) - 2 - starts;
5636 endinpos = startinpos + 2;
5637 break;
5638 case 3:
5639 errmsg = "illegal UTF-16 surrogate";
5640 startinpos = ((const char *)q) - 4 - starts;
5641 endinpos = startinpos + 2;
5642 break;
5643 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005644 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005645 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005646 continue;
5647 }
5648
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005649 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005650 errors,
5651 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005652 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005653 &starts,
5654 (const char **)&e,
5655 &startinpos,
5656 &endinpos,
5657 &exc,
5658 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005659 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005660 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005661 }
5662
Antoine Pitrou63065d72012-05-15 23:48:04 +02005663End:
Walter Dörwald69652032004-09-07 20:24:22 +00005664 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005665 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005666
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005667 Py_XDECREF(errorHandler);
5668 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005669 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005670
Benjamin Peterson29060642009-01-31 22:14:21 +00005671 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005672 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005673 Py_XDECREF(errorHandler);
5674 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675 return NULL;
5676}
5677
Tim Peters772747b2001-08-09 22:21:55 +00005678PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005679_PyUnicode_EncodeUTF16(PyObject *str,
5680 const char *errors,
5681 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005682{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005683 enum PyUnicode_Kind kind;
5684 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005685 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005686 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005687 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005688 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005689#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005690 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005691#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005692 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005693#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005694 const char *encoding;
5695 Py_ssize_t nsize, pos;
5696 PyObject *errorHandler = NULL;
5697 PyObject *exc = NULL;
5698 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005699
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005700 if (!PyUnicode_Check(str)) {
5701 PyErr_BadArgument();
5702 return NULL;
5703 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005704 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005705 return NULL;
5706 kind = PyUnicode_KIND(str);
5707 data = PyUnicode_DATA(str);
5708 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005709
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005710 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005711 if (kind == PyUnicode_4BYTE_KIND) {
5712 const Py_UCS4 *in = (const Py_UCS4 *)data;
5713 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005714 while (in < end) {
5715 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005716 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005717 }
5718 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005719 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005720 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005721 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005722 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005723 nsize = len + pairs + (byteorder == 0);
5724 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005725 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005727 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005729 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005730 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005731 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005732 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005733 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005734 }
5735 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005736 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005737 }
Tim Peters772747b2001-08-09 22:21:55 +00005738
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005739 if (kind == PyUnicode_1BYTE_KIND) {
5740 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5741 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005742 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005743
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005744 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005745 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005746 }
5747 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005748 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005749 }
5750 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005751 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005752 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005753
5754 pos = 0;
5755 while (pos < len) {
5756 Py_ssize_t repsize, moreunits;
5757
5758 if (kind == PyUnicode_2BYTE_KIND) {
5759 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5760 &out, native_ordering);
5761 }
5762 else {
5763 assert(kind == PyUnicode_4BYTE_KIND);
5764 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5765 &out, native_ordering);
5766 }
5767 if (pos == len)
5768 break;
5769
5770 rep = unicode_encode_call_errorhandler(
5771 errors, &errorHandler,
5772 encoding, "surrogates not allowed",
5773 str, &exc, pos, pos + 1, &pos);
5774 if (!rep)
5775 goto error;
5776
5777 if (PyBytes_Check(rep)) {
5778 repsize = PyBytes_GET_SIZE(rep);
5779 if (repsize & 1) {
5780 raise_encode_exception(&exc, encoding,
5781 str, pos - 1, pos,
5782 "surrogates not allowed");
5783 goto error;
5784 }
5785 moreunits = repsize / 2;
5786 }
5787 else {
5788 assert(PyUnicode_Check(rep));
5789 if (PyUnicode_READY(rep) < 0)
5790 goto error;
5791 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5792 if (!PyUnicode_IS_ASCII(rep)) {
5793 raise_encode_exception(&exc, encoding,
5794 str, pos - 1, pos,
5795 "surrogates not allowed");
5796 goto error;
5797 }
5798 }
5799
5800 /* two bytes are reserved for each surrogate */
5801 if (moreunits > 1) {
5802 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5803 Py_ssize_t morebytes = 2 * (moreunits - 1);
5804 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5805 /* integer overflow */
5806 PyErr_NoMemory();
5807 goto error;
5808 }
5809 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5810 goto error;
5811 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5812 }
5813
5814 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005815 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005816 out += moreunits;
5817 } else /* rep is unicode */ {
5818 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5819 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5820 &out, native_ordering);
5821 }
5822
5823 Py_CLEAR(rep);
5824 }
5825
5826 /* Cut back to size actually needed. This is necessary for, for example,
5827 encoding of a string containing isolated surrogates and the 'ignore' handler
5828 is used. */
5829 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5830 if (nsize != PyBytes_GET_SIZE(v))
5831 _PyBytes_Resize(&v, nsize);
5832 Py_XDECREF(errorHandler);
5833 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005834 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005835 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005836 error:
5837 Py_XDECREF(rep);
5838 Py_XDECREF(errorHandler);
5839 Py_XDECREF(exc);
5840 Py_XDECREF(v);
5841 return NULL;
5842#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005843}
5844
Alexander Belopolsky40018472011-02-26 01:02:56 +00005845PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005846PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5847 Py_ssize_t size,
5848 const char *errors,
5849 int byteorder)
5850{
5851 PyObject *result;
5852 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5853 if (tmp == NULL)
5854 return NULL;
5855 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5856 Py_DECREF(tmp);
5857 return result;
5858}
5859
5860PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005861PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005863 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005864}
5865
5866/* --- Unicode Escape Codec ----------------------------------------------- */
5867
Fredrik Lundh06d12682001-01-24 07:59:11 +00005868static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005869
Alexander Belopolsky40018472011-02-26 01:02:56 +00005870PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005871_PyUnicode_DecodeUnicodeEscape(const char *s,
5872 Py_ssize_t size,
5873 const char *errors,
5874 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005876 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005877 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005879 PyObject *errorHandler = NULL;
5880 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005881
Eric V. Smith42454af2016-10-31 09:22:08 -04005882 // so we can remember if we've seen an invalid escape char or not
5883 *first_invalid_escape = NULL;
5884
Victor Stinner62ec3312016-09-06 17:04:34 -07005885 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005886 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005887 }
5888 /* Escaped strings will always be longer than the resulting
5889 Unicode string, so we start with size here and then reduce the
5890 length after conversion to the true value.
5891 (but if the error callback returns a long replacement string
5892 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005893 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005894 writer.min_length = size;
5895 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5896 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005897 }
5898
Guido van Rossumd57fd912000-03-10 22:53:23 +00005899 end = s + size;
5900 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005901 unsigned char c = (unsigned char) *s++;
5902 Py_UCS4 ch;
5903 int count;
5904 Py_ssize_t startinpos;
5905 Py_ssize_t endinpos;
5906 const char *message;
5907
5908#define WRITE_ASCII_CHAR(ch) \
5909 do { \
5910 assert(ch <= 127); \
5911 assert(writer.pos < writer.size); \
5912 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5913 } while(0)
5914
5915#define WRITE_CHAR(ch) \
5916 do { \
5917 if (ch <= writer.maxchar) { \
5918 assert(writer.pos < writer.size); \
5919 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5920 } \
5921 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5922 goto onError; \
5923 } \
5924 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925
5926 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005927 if (c != '\\') {
5928 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 continue;
5930 }
5931
Victor Stinner62ec3312016-09-06 17:04:34 -07005932 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005934 if (s >= end) {
5935 message = "\\ at end of string";
5936 goto error;
5937 }
5938 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005939
Victor Stinner62ec3312016-09-06 17:04:34 -07005940 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005941 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005942
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005944 case '\n': continue;
5945 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5946 case '\'': WRITE_ASCII_CHAR('\''); continue;
5947 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5948 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005949 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005950 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5951 case 't': WRITE_ASCII_CHAR('\t'); continue;
5952 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5953 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005954 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005955 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005956 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005957 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960 case '0': case '1': case '2': case '3':
5961 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005962 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005963 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005964 ch = (ch<<3) + *s++ - '0';
5965 if (s < end && '0' <= *s && *s <= '7') {
5966 ch = (ch<<3) + *s++ - '0';
5967 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005969 WRITE_CHAR(ch);
5970 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971
Benjamin Peterson29060642009-01-31 22:14:21 +00005972 /* hex escapes */
5973 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005975 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005976 message = "truncated \\xXX escape";
5977 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978
Benjamin Peterson29060642009-01-31 22:14:21 +00005979 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005981 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005982 message = "truncated \\uXXXX escape";
5983 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005984
Benjamin Peterson29060642009-01-31 22:14:21 +00005985 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005986 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005987 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005988 message = "truncated \\UXXXXXXXX escape";
5989 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07005990 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02005991 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07005992 ch <<= 4;
5993 if (c >= '0' && c <= '9') {
5994 ch += c - '0';
5995 }
5996 else if (c >= 'a' && c <= 'f') {
5997 ch += c - ('a' - 10);
5998 }
5999 else if (c >= 'A' && c <= 'F') {
6000 ch += c - ('A' - 10);
6001 }
6002 else {
6003 break;
6004 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006005 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006006 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006007 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006008 }
6009
6010 /* when we get here, ch is a 32-bit unicode character */
6011 if (ch > MAX_UNICODE) {
6012 message = "illegal Unicode character";
6013 goto error;
6014 }
6015
6016 WRITE_CHAR(ch);
6017 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006018
Benjamin Peterson29060642009-01-31 22:14:21 +00006019 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006020 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006021 if (ucnhash_CAPI == NULL) {
6022 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006023 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6024 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006025 if (ucnhash_CAPI == NULL) {
6026 PyErr_SetString(
6027 PyExc_UnicodeError,
6028 "\\N escapes not supported (can't load unicodedata module)"
6029 );
6030 goto onError;
6031 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006032 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006033
6034 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006035 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006036 const char *start = ++s;
6037 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006038 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006039 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006040 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006041 namelen = s - start;
6042 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006043 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006044 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006045 ch = 0xffffffff; /* in case 'getcode' messes up */
6046 if (namelen <= INT_MAX &&
6047 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6048 &ch, 0)) {
6049 assert(ch <= MAX_UNICODE);
6050 WRITE_CHAR(ch);
6051 continue;
6052 }
6053 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006054 }
6055 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006056 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006057
6058 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006059 if (*first_invalid_escape == NULL) {
6060 *first_invalid_escape = s-1; /* Back up one char, since we've
6061 already incremented s. */
6062 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006063 WRITE_ASCII_CHAR('\\');
6064 WRITE_CHAR(c);
6065 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006066 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006067
6068 error:
6069 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006070 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006071 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006072 errors, &errorHandler,
6073 "unicodeescape", message,
6074 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006075 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006076 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006077 }
6078 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6079 goto onError;
6080 }
6081
6082#undef WRITE_ASCII_CHAR
6083#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006084 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006085
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006086 Py_XDECREF(errorHandler);
6087 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006088 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006089
Benjamin Peterson29060642009-01-31 22:14:21 +00006090 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006091 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006092 Py_XDECREF(errorHandler);
6093 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006094 return NULL;
6095}
6096
Eric V. Smith42454af2016-10-31 09:22:08 -04006097PyObject *
6098PyUnicode_DecodeUnicodeEscape(const char *s,
6099 Py_ssize_t size,
6100 const char *errors)
6101{
6102 const char *first_invalid_escape;
6103 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6104 &first_invalid_escape);
6105 if (result == NULL)
6106 return NULL;
6107 if (first_invalid_escape != NULL) {
6108 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6109 "invalid escape sequence '\\%c'",
6110 *first_invalid_escape) < 0) {
6111 Py_DECREF(result);
6112 return NULL;
6113 }
6114 }
6115 return result;
6116}
6117
Guido van Rossumd57fd912000-03-10 22:53:23 +00006118/* Return a Unicode-Escape string version of the Unicode object.
6119
6120 If quotes is true, the string is enclosed in u"" or u'' quotes as
6121 appropriate.
6122
6123*/
6124
Alexander Belopolsky40018472011-02-26 01:02:56 +00006125PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006126PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006127{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006128 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006129 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006131 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006132 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006133 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006134
Ezio Melottie7f90372012-10-05 03:33:31 +03006135 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006136 escape.
6137
Ezio Melottie7f90372012-10-05 03:33:31 +03006138 For UCS1 strings it's '\xxx', 4 bytes per source character.
6139 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6140 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006141 */
6142
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006143 if (!PyUnicode_Check(unicode)) {
6144 PyErr_BadArgument();
6145 return NULL;
6146 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006147 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006148 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006149 }
Victor Stinner358af132015-10-12 22:36:57 +02006150
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006151 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006152 if (len == 0) {
6153 return PyBytes_FromStringAndSize(NULL, 0);
6154 }
6155
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006156 kind = PyUnicode_KIND(unicode);
6157 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006158 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6159 bytes, and 1 byte characters 4. */
6160 expandsize = kind * 2 + 2;
6161 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize) {
6162 return PyErr_NoMemory();
6163 }
6164 repr = PyBytes_FromStringAndSize(NULL, 2 + expandsize * len + 1);
6165 if (repr == NULL) {
6166 return NULL;
6167 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006168
Victor Stinner62ec3312016-09-06 17:04:34 -07006169 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006170 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006171 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006172
Victor Stinner62ec3312016-09-06 17:04:34 -07006173 /* U+0000-U+00ff range */
6174 if (ch < 0x100) {
6175 if (ch >= ' ' && ch < 127) {
6176 if (ch != '\\') {
6177 /* Copy printable US ASCII as-is */
6178 *p++ = (char) ch;
6179 }
6180 /* Escape backslashes */
6181 else {
6182 *p++ = '\\';
6183 *p++ = '\\';
6184 }
6185 }
Victor Stinner358af132015-10-12 22:36:57 +02006186
Victor Stinner62ec3312016-09-06 17:04:34 -07006187 /* Map special whitespace to '\t', \n', '\r' */
6188 else if (ch == '\t') {
6189 *p++ = '\\';
6190 *p++ = 't';
6191 }
6192 else if (ch == '\n') {
6193 *p++ = '\\';
6194 *p++ = 'n';
6195 }
6196 else if (ch == '\r') {
6197 *p++ = '\\';
6198 *p++ = 'r';
6199 }
6200
6201 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6202 else {
6203 *p++ = '\\';
6204 *p++ = 'x';
6205 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6206 *p++ = Py_hexdigits[ch & 0x000F];
6207 }
Tim Petersced69f82003-09-16 20:30:58 +00006208 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006209 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6210 else if (ch < 0x10000) {
6211 /* U+0100-U+ffff */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006212 *p++ = '\\';
6213 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006214 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6215 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6216 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6217 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006218 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006219 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6220 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006221
Victor Stinner62ec3312016-09-06 17:04:34 -07006222 /* Make sure that the first two digits are zero */
6223 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006224 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006225 *p++ = 'U';
6226 *p++ = '0';
6227 *p++ = '0';
6228 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6229 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6230 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6231 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6232 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6233 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006234 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006235 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236
Victor Stinner62ec3312016-09-06 17:04:34 -07006237 assert(p - PyBytes_AS_STRING(repr) > 0);
6238 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6239 return NULL;
6240 }
6241 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006242}
6243
Alexander Belopolsky40018472011-02-26 01:02:56 +00006244PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006245PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6246 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006247{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006248 PyObject *result;
6249 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006250 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006251 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006252 }
6253
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006254 result = PyUnicode_AsUnicodeEscapeString(tmp);
6255 Py_DECREF(tmp);
6256 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006257}
6258
6259/* --- Raw Unicode Escape Codec ------------------------------------------- */
6260
Alexander Belopolsky40018472011-02-26 01:02:56 +00006261PyObject *
6262PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006263 Py_ssize_t size,
6264 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006265{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006266 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006267 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006268 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006269 PyObject *errorHandler = NULL;
6270 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006271
Victor Stinner62ec3312016-09-06 17:04:34 -07006272 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006273 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006274 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006275
Guido van Rossumd57fd912000-03-10 22:53:23 +00006276 /* Escaped strings will always be longer than the resulting
6277 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006278 length after conversion to the true value. (But decoding error
6279 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006280 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006281 writer.min_length = size;
6282 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6283 goto onError;
6284 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006285
Guido van Rossumd57fd912000-03-10 22:53:23 +00006286 end = s + size;
6287 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006288 unsigned char c = (unsigned char) *s++;
6289 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006290 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006291 Py_ssize_t startinpos;
6292 Py_ssize_t endinpos;
6293 const char *message;
6294
6295#define WRITE_CHAR(ch) \
6296 do { \
6297 if (ch <= writer.maxchar) { \
6298 assert(writer.pos < writer.size); \
6299 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6300 } \
6301 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6302 goto onError; \
6303 } \
6304 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305
Benjamin Peterson29060642009-01-31 22:14:21 +00006306 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006307 if (c != '\\' || s >= end) {
6308 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006309 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006310 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006311
Victor Stinner62ec3312016-09-06 17:04:34 -07006312 c = (unsigned char) *s++;
6313 if (c == 'u') {
6314 count = 4;
6315 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006316 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006317 else if (c == 'U') {
6318 count = 8;
6319 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006320 }
6321 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006322 assert(writer.pos < writer.size);
6323 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6324 WRITE_CHAR(c);
6325 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006326 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006327 startinpos = s - starts - 2;
6328
6329 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6330 for (ch = 0; count && s < end; ++s, --count) {
6331 c = (unsigned char)*s;
6332 ch <<= 4;
6333 if (c >= '0' && c <= '9') {
6334 ch += c - '0';
6335 }
6336 else if (c >= 'a' && c <= 'f') {
6337 ch += c - ('a' - 10);
6338 }
6339 else if (c >= 'A' && c <= 'F') {
6340 ch += c - ('A' - 10);
6341 }
6342 else {
6343 break;
6344 }
6345 }
6346 if (!count) {
6347 if (ch <= MAX_UNICODE) {
6348 WRITE_CHAR(ch);
6349 continue;
6350 }
6351 message = "\\Uxxxxxxxx out of range";
6352 }
6353
6354 endinpos = s-starts;
6355 writer.min_length = end - s + writer.pos;
6356 if (unicode_decode_call_errorhandler_writer(
6357 errors, &errorHandler,
6358 "rawunicodeescape", message,
6359 &starts, &end, &startinpos, &endinpos, &exc, &s,
6360 &writer)) {
6361 goto onError;
6362 }
6363 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6364 goto onError;
6365 }
6366
6367#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006368 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006369 Py_XDECREF(errorHandler);
6370 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006371 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006372
Benjamin Peterson29060642009-01-31 22:14:21 +00006373 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006374 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006375 Py_XDECREF(errorHandler);
6376 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006377 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006378
Guido van Rossumd57fd912000-03-10 22:53:23 +00006379}
6380
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006381
Alexander Belopolsky40018472011-02-26 01:02:56 +00006382PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006383PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006384{
Victor Stinner62ec3312016-09-06 17:04:34 -07006385 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006387 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006388 int kind;
6389 void *data;
6390 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006391
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006392 if (!PyUnicode_Check(unicode)) {
6393 PyErr_BadArgument();
6394 return NULL;
6395 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006396 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006397 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006398 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006399 kind = PyUnicode_KIND(unicode);
6400 data = PyUnicode_DATA(unicode);
6401 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006402 if (kind == PyUnicode_1BYTE_KIND) {
6403 return PyBytes_FromStringAndSize(data, len);
6404 }
Victor Stinner0e368262011-11-10 20:12:49 +01006405
Victor Stinner62ec3312016-09-06 17:04:34 -07006406 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6407 bytes, and 1 byte characters 4. */
6408 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006409
Victor Stinner62ec3312016-09-06 17:04:34 -07006410 if (len > PY_SSIZE_T_MAX / expandsize) {
6411 return PyErr_NoMemory();
6412 }
6413 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6414 if (repr == NULL) {
6415 return NULL;
6416 }
6417 if (len == 0) {
6418 return repr;
6419 }
6420
6421 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006422 for (pos = 0; pos < len; pos++) {
6423 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006424
Victor Stinner62ec3312016-09-06 17:04:34 -07006425 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6426 if (ch < 0x100) {
6427 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006428 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006429 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6430 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006431 *p++ = '\\';
6432 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006433 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6434 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6435 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6436 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006437 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006438 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6439 else {
6440 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6441 *p++ = '\\';
6442 *p++ = 'U';
6443 *p++ = '0';
6444 *p++ = '0';
6445 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6446 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6447 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6448 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6449 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6450 *p++ = Py_hexdigits[ch & 15];
6451 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006452 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006453
Victor Stinner62ec3312016-09-06 17:04:34 -07006454 assert(p > PyBytes_AS_STRING(repr));
6455 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6456 return NULL;
6457 }
6458 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006459}
6460
Alexander Belopolsky40018472011-02-26 01:02:56 +00006461PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006462PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6463 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006464{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006465 PyObject *result;
6466 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6467 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006468 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006469 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6470 Py_DECREF(tmp);
6471 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006472}
6473
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006474/* --- Unicode Internal Codec ------------------------------------------- */
6475
Alexander Belopolsky40018472011-02-26 01:02:56 +00006476PyObject *
6477_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006478 Py_ssize_t size,
6479 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006480{
6481 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006482 Py_ssize_t startinpos;
6483 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006484 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006485 const char *end;
6486 const char *reason;
6487 PyObject *errorHandler = NULL;
6488 PyObject *exc = NULL;
6489
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006490 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006491 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006492 1))
6493 return NULL;
6494
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006495 if (size == 0)
6496 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006497
Victor Stinner8f674cc2013-04-17 23:02:17 +02006498 _PyUnicodeWriter_Init(&writer);
6499 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6500 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006502 }
6503 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006504
Victor Stinner8f674cc2013-04-17 23:02:17 +02006505 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006506 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006507 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006508 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006509 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006510 endinpos = end-starts;
6511 reason = "truncated input";
6512 goto error;
6513 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006514 /* We copy the raw representation one byte at a time because the
6515 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006516 ((char *) &uch)[0] = s[0];
6517 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006518#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006519 ((char *) &uch)[2] = s[2];
6520 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006521#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006522 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006523#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006524 /* We have to sanity check the raw data, otherwise doom looms for
6525 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006526 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006527 endinpos = s - starts + Py_UNICODE_SIZE;
6528 reason = "illegal code point (> 0x10FFFF)";
6529 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006530 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006531#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006532 s += Py_UNICODE_SIZE;
6533#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006534 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006535 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006536 Py_UNICODE uch2;
6537 ((char *) &uch2)[0] = s[0];
6538 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006539 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006540 {
Victor Stinner551ac952011-11-29 22:58:13 +01006541 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006542 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006543 }
6544 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006545#endif
6546
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006547 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006548 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006549 continue;
6550
6551 error:
6552 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006553 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006554 errors, &errorHandler,
6555 "unicode_internal", reason,
6556 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006557 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006558 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006559 }
6560
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006561 Py_XDECREF(errorHandler);
6562 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006563 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006564
Benjamin Peterson29060642009-01-31 22:14:21 +00006565 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006566 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006567 Py_XDECREF(errorHandler);
6568 Py_XDECREF(exc);
6569 return NULL;
6570}
6571
Guido van Rossumd57fd912000-03-10 22:53:23 +00006572/* --- Latin-1 Codec ------------------------------------------------------ */
6573
Alexander Belopolsky40018472011-02-26 01:02:56 +00006574PyObject *
6575PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006576 Py_ssize_t size,
6577 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006578{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006579 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006580 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006581}
6582
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006583/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006584static void
6585make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006586 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006587 PyObject *unicode,
6588 Py_ssize_t startpos, Py_ssize_t endpos,
6589 const char *reason)
6590{
6591 if (*exceptionObject == NULL) {
6592 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006593 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006594 encoding, unicode, startpos, endpos, reason);
6595 }
6596 else {
6597 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6598 goto onError;
6599 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6600 goto onError;
6601 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6602 goto onError;
6603 return;
6604 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006605 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006606 }
6607}
6608
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006609/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006610static void
6611raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006612 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006613 PyObject *unicode,
6614 Py_ssize_t startpos, Py_ssize_t endpos,
6615 const char *reason)
6616{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006617 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006618 encoding, unicode, startpos, endpos, reason);
6619 if (*exceptionObject != NULL)
6620 PyCodec_StrictErrors(*exceptionObject);
6621}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006622
6623/* error handling callback helper:
6624 build arguments, call the callback and check the arguments,
6625 put the result into newpos and return the replacement string, which
6626 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006627static PyObject *
6628unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006629 PyObject **errorHandler,
6630 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006631 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006632 Py_ssize_t startpos, Py_ssize_t endpos,
6633 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006634{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006635 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006636 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006637 PyObject *restuple;
6638 PyObject *resunicode;
6639
6640 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006643 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644 }
6645
Benjamin Petersonbac79492012-01-14 13:34:47 -05006646 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006647 return NULL;
6648 len = PyUnicode_GET_LENGTH(unicode);
6649
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006650 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006651 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006652 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006653 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006654
6655 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006656 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006657 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006658 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006660 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006661 Py_DECREF(restuple);
6662 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006663 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006664 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 &resunicode, newpos)) {
6666 Py_DECREF(restuple);
6667 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006669 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6670 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6671 Py_DECREF(restuple);
6672 return NULL;
6673 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006674 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006675 *newpos = len + *newpos;
6676 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006677 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006678 Py_DECREF(restuple);
6679 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006680 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006681 Py_INCREF(resunicode);
6682 Py_DECREF(restuple);
6683 return resunicode;
6684}
6685
Alexander Belopolsky40018472011-02-26 01:02:56 +00006686static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006687unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006688 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006689 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006690{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006691 /* input state */
6692 Py_ssize_t pos=0, size;
6693 int kind;
6694 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006695 /* pointer into the output */
6696 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006697 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6698 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006699 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006700 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006701 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006702 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006703 /* output object */
6704 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006705
Benjamin Petersonbac79492012-01-14 13:34:47 -05006706 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006707 return NULL;
6708 size = PyUnicode_GET_LENGTH(unicode);
6709 kind = PyUnicode_KIND(unicode);
6710 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006711 /* allocate enough for a simple encoding without
6712 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006713 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006714 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006715
6716 _PyBytesWriter_Init(&writer);
6717 str = _PyBytesWriter_Alloc(&writer, size);
6718 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006719 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006720
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006721 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006722 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006723
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006725 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006727 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006728 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006729 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006730 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006731 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006732 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006733 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006734 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006736
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006737 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006738 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006739
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006740 /* Only overallocate the buffer if it's not the last write */
6741 writer.overallocate = (collend < size);
6742
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006744 if (error_handler == _Py_ERROR_UNKNOWN)
6745 error_handler = get_error_handler(errors);
6746
6747 switch (error_handler) {
6748 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006749 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006750 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006751
6752 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006753 memset(str, '?', collend - collstart);
6754 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006755 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006756 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006757 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 break;
Victor Stinner50149202015-09-22 00:26:54 +02006759
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006760 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006761 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006762 writer.min_size -= (collend - collstart);
6763 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006764 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006765 if (str == NULL)
6766 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006767 pos = collend;
6768 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006769
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006770 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006771 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006772 writer.min_size -= (collend - collstart);
6773 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006774 unicode, collstart, collend);
6775 if (str == NULL)
6776 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006777 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006778 break;
Victor Stinner50149202015-09-22 00:26:54 +02006779
Victor Stinnerc3713e92015-09-29 12:32:13 +02006780 case _Py_ERROR_SURROGATEESCAPE:
6781 for (i = collstart; i < collend; ++i) {
6782 ch = PyUnicode_READ(kind, data, i);
6783 if (ch < 0xdc80 || 0xdcff < ch) {
6784 /* Not a UTF-8b surrogate */
6785 break;
6786 }
6787 *str++ = (char)(ch - 0xdc00);
6788 ++pos;
6789 }
6790 if (i >= collend)
6791 break;
6792 collstart = pos;
6793 assert(collstart != collend);
6794 /* fallback to general error handling */
6795
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006797 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6798 encoding, reason, unicode, &exc,
6799 collstart, collend, &newpos);
6800 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006801 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006802
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006803 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006804 writer.min_size -= 1;
6805
Victor Stinner6bd525b2015-10-09 13:10:05 +02006806 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006807 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006808 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006809 PyBytes_AS_STRING(rep),
6810 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006811 if (str == NULL)
6812 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006813 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006814 else {
6815 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006816
Victor Stinner6bd525b2015-10-09 13:10:05 +02006817 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006818 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006819
6820 if (PyUnicode_IS_ASCII(rep)) {
6821 /* Fast path: all characters are smaller than limit */
6822 assert(limit >= 128);
6823 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6824 str = _PyBytesWriter_WriteBytes(&writer, str,
6825 PyUnicode_DATA(rep),
6826 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006827 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006828 else {
6829 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6830
6831 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6832 if (str == NULL)
6833 goto onError;
6834
6835 /* check if there is anything unencodable in the
6836 replacement and copy it to the output */
6837 for (i = 0; repsize-->0; ++i, ++str) {
6838 ch = PyUnicode_READ_CHAR(rep, i);
6839 if (ch >= limit) {
6840 raise_encode_exception(&exc, encoding, unicode,
6841 pos, pos+1, reason);
6842 goto onError;
6843 }
6844 *str = (char)ch;
6845 }
6846 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006847 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006848 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006849 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006850 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006851
6852 /* If overallocation was disabled, ensure that it was the last
6853 write. Otherwise, we missed an optimization */
6854 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006855 }
6856 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006857
Victor Stinner50149202015-09-22 00:26:54 +02006858 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006859 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006860 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006861
6862 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006863 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006864 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006865 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006866 Py_XDECREF(exc);
6867 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006868}
6869
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006870/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006871PyObject *
6872PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006873 Py_ssize_t size,
6874 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006875{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006876 PyObject *result;
6877 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6878 if (unicode == NULL)
6879 return NULL;
6880 result = unicode_encode_ucs1(unicode, errors, 256);
6881 Py_DECREF(unicode);
6882 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006883}
6884
Alexander Belopolsky40018472011-02-26 01:02:56 +00006885PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006886_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006887{
6888 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006889 PyErr_BadArgument();
6890 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006891 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006892 if (PyUnicode_READY(unicode) == -1)
6893 return NULL;
6894 /* Fast path: if it is a one-byte string, construct
6895 bytes object directly. */
6896 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6897 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6898 PyUnicode_GET_LENGTH(unicode));
6899 /* Non-Latin-1 characters present. Defer to above function to
6900 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006901 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006902}
6903
6904PyObject*
6905PyUnicode_AsLatin1String(PyObject *unicode)
6906{
6907 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006908}
6909
6910/* --- 7-bit ASCII Codec -------------------------------------------------- */
6911
Alexander Belopolsky40018472011-02-26 01:02:56 +00006912PyObject *
6913PyUnicode_DecodeASCII(const char *s,
6914 Py_ssize_t size,
6915 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006916{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006917 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006918 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006919 int kind;
6920 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006921 Py_ssize_t startinpos;
6922 Py_ssize_t endinpos;
6923 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006924 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006925 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006926 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006927 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006928
Guido van Rossumd57fd912000-03-10 22:53:23 +00006929 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006930 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006931
Guido van Rossumd57fd912000-03-10 22:53:23 +00006932 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006933 if (size == 1 && (unsigned char)s[0] < 128)
6934 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006935
Victor Stinner8f674cc2013-04-17 23:02:17 +02006936 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006937 writer.min_length = size;
6938 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006939 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006940
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006941 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006942 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006943 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006944 writer.pos = outpos;
6945 if (writer.pos == size)
6946 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006947
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006948 s += writer.pos;
6949 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006950 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006951 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006952 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006953 PyUnicode_WRITE(kind, data, writer.pos, c);
6954 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006955 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006956 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006957 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006958
6959 /* byte outsize range 0x00..0x7f: call the error handler */
6960
6961 if (error_handler == _Py_ERROR_UNKNOWN)
6962 error_handler = get_error_handler(errors);
6963
6964 switch (error_handler)
6965 {
6966 case _Py_ERROR_REPLACE:
6967 case _Py_ERROR_SURROGATEESCAPE:
6968 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006969 but we may switch to UCS2 at the first write */
6970 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6971 goto onError;
6972 kind = writer.kind;
6973 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006974
6975 if (error_handler == _Py_ERROR_REPLACE)
6976 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6977 else
6978 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6979 writer.pos++;
6980 ++s;
6981 break;
6982
6983 case _Py_ERROR_IGNORE:
6984 ++s;
6985 break;
6986
6987 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006988 startinpos = s-starts;
6989 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006990 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006991 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006992 "ascii", "ordinal not in range(128)",
6993 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006994 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006995 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006996 kind = writer.kind;
6997 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006998 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006999 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007000 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007001 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007002 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007003
Benjamin Peterson29060642009-01-31 22:14:21 +00007004 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007005 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007006 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007007 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007008 return NULL;
7009}
7010
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007011/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007012PyObject *
7013PyUnicode_EncodeASCII(const Py_UNICODE *p,
7014 Py_ssize_t size,
7015 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007016{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007017 PyObject *result;
7018 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7019 if (unicode == NULL)
7020 return NULL;
7021 result = unicode_encode_ucs1(unicode, errors, 128);
7022 Py_DECREF(unicode);
7023 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007024}
7025
Alexander Belopolsky40018472011-02-26 01:02:56 +00007026PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007027_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007028{
7029 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007030 PyErr_BadArgument();
7031 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007032 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007033 if (PyUnicode_READY(unicode) == -1)
7034 return NULL;
7035 /* Fast path: if it is an ASCII-only string, construct bytes object
7036 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007037 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007038 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7039 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007040 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007041}
7042
7043PyObject *
7044PyUnicode_AsASCIIString(PyObject *unicode)
7045{
7046 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007047}
7048
Steve Dowercc16be82016-09-08 10:35:16 -07007049#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007050
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007051/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007052
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007053#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007054#define NEED_RETRY
7055#endif
7056
Victor Stinner3a50e702011-10-18 21:21:00 +02007057#ifndef WC_ERR_INVALID_CHARS
7058# define WC_ERR_INVALID_CHARS 0x0080
7059#endif
7060
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007061static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007062code_page_name(UINT code_page, PyObject **obj)
7063{
7064 *obj = NULL;
7065 if (code_page == CP_ACP)
7066 return "mbcs";
7067 if (code_page == CP_UTF7)
7068 return "CP_UTF7";
7069 if (code_page == CP_UTF8)
7070 return "CP_UTF8";
7071
7072 *obj = PyBytes_FromFormat("cp%u", code_page);
7073 if (*obj == NULL)
7074 return NULL;
7075 return PyBytes_AS_STRING(*obj);
7076}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007077
Victor Stinner3a50e702011-10-18 21:21:00 +02007078static DWORD
7079decode_code_page_flags(UINT code_page)
7080{
7081 if (code_page == CP_UTF7) {
7082 /* The CP_UTF7 decoder only supports flags=0 */
7083 return 0;
7084 }
7085 else
7086 return MB_ERR_INVALID_CHARS;
7087}
7088
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007090 * Decode a byte string from a Windows code page into unicode object in strict
7091 * mode.
7092 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007093 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7094 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007095 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007096static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007097decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007098 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 const char *in,
7100 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007101{
Victor Stinner3a50e702011-10-18 21:21:00 +02007102 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007103 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105
7106 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007107 assert(insize > 0);
7108 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7109 if (outsize <= 0)
7110 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007111
7112 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007113 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007114 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007115 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007116 if (*v == NULL)
7117 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007118 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007119 }
7120 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007121 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007122 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007123 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007124 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007125 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007126 }
7127
7128 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007129 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7130 if (outsize <= 0)
7131 goto error;
7132 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007133
Victor Stinner3a50e702011-10-18 21:21:00 +02007134error:
7135 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7136 return -2;
7137 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007138 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007139}
7140
Victor Stinner3a50e702011-10-18 21:21:00 +02007141/*
7142 * Decode a byte string from a code page into unicode object with an error
7143 * handler.
7144 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007145 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007146 * UnicodeDecodeError exception and returns -1 on error.
7147 */
7148static int
7149decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007150 PyObject **v,
7151 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007152 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007153{
7154 const char *startin = in;
7155 const char *endin = in + size;
7156 const DWORD flags = decode_code_page_flags(code_page);
7157 /* Ideally, we should get reason from FormatMessage. This is the Windows
7158 2000 English version of the message. */
7159 const char *reason = "No mapping for the Unicode character exists "
7160 "in the target code page.";
7161 /* each step cannot decode more than 1 character, but a character can be
7162 represented as a surrogate pair */
7163 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007164 int insize;
7165 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007166 PyObject *errorHandler = NULL;
7167 PyObject *exc = NULL;
7168 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007169 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007170 DWORD err;
7171 int ret = -1;
7172
7173 assert(size > 0);
7174
7175 encoding = code_page_name(code_page, &encoding_obj);
7176 if (encoding == NULL)
7177 return -1;
7178
Victor Stinner7d00cc12014-03-17 23:08:06 +01007179 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7181 UnicodeDecodeError. */
7182 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7183 if (exc != NULL) {
7184 PyCodec_StrictErrors(exc);
7185 Py_CLEAR(exc);
7186 }
7187 goto error;
7188 }
7189
7190 if (*v == NULL) {
7191 /* Create unicode object */
7192 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7193 PyErr_NoMemory();
7194 goto error;
7195 }
Victor Stinnerab595942011-12-17 04:59:06 +01007196 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007197 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007198 if (*v == NULL)
7199 goto error;
7200 startout = PyUnicode_AS_UNICODE(*v);
7201 }
7202 else {
7203 /* Extend unicode object */
7204 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7205 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7206 PyErr_NoMemory();
7207 goto error;
7208 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007209 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007210 goto error;
7211 startout = PyUnicode_AS_UNICODE(*v) + n;
7212 }
7213
7214 /* Decode the byte string character per character */
7215 out = startout;
7216 while (in < endin)
7217 {
7218 /* Decode a character */
7219 insize = 1;
7220 do
7221 {
7222 outsize = MultiByteToWideChar(code_page, flags,
7223 in, insize,
7224 buffer, Py_ARRAY_LENGTH(buffer));
7225 if (outsize > 0)
7226 break;
7227 err = GetLastError();
7228 if (err != ERROR_NO_UNICODE_TRANSLATION
7229 && err != ERROR_INSUFFICIENT_BUFFER)
7230 {
7231 PyErr_SetFromWindowsErr(0);
7232 goto error;
7233 }
7234 insize++;
7235 }
7236 /* 4=maximum length of a UTF-8 sequence */
7237 while (insize <= 4 && (in + insize) <= endin);
7238
7239 if (outsize <= 0) {
7240 Py_ssize_t startinpos, endinpos, outpos;
7241
Victor Stinner7d00cc12014-03-17 23:08:06 +01007242 /* last character in partial decode? */
7243 if (in + insize >= endin && !final)
7244 break;
7245
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 startinpos = in - startin;
7247 endinpos = startinpos + 1;
7248 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007249 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 errors, &errorHandler,
7251 encoding, reason,
7252 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007253 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007254 {
7255 goto error;
7256 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007257 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007258 }
7259 else {
7260 in += insize;
7261 memcpy(out, buffer, outsize * sizeof(wchar_t));
7262 out += outsize;
7263 }
7264 }
7265
7266 /* write a NUL character at the end */
7267 *out = 0;
7268
7269 /* Extend unicode object */
7270 outsize = out - startout;
7271 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007272 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007273 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007274 /* (in - startin) <= size and size is an int */
7275 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007276
7277error:
7278 Py_XDECREF(encoding_obj);
7279 Py_XDECREF(errorHandler);
7280 Py_XDECREF(exc);
7281 return ret;
7282}
7283
Victor Stinner3a50e702011-10-18 21:21:00 +02007284static PyObject *
7285decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007286 const char *s, Py_ssize_t size,
7287 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007288{
Victor Stinner76a31a62011-11-04 00:05:13 +01007289 PyObject *v = NULL;
7290 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007291
Victor Stinner3a50e702011-10-18 21:21:00 +02007292 if (code_page < 0) {
7293 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7294 return NULL;
7295 }
7296
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007297 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007298 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007299
Victor Stinner76a31a62011-11-04 00:05:13 +01007300 do
7301 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007302#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007303 if (size > INT_MAX) {
7304 chunk_size = INT_MAX;
7305 final = 0;
7306 done = 0;
7307 }
7308 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007309#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007310 {
7311 chunk_size = (int)size;
7312 final = (consumed == NULL);
7313 done = 1;
7314 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007315
Victor Stinner76a31a62011-11-04 00:05:13 +01007316 if (chunk_size == 0 && done) {
7317 if (v != NULL)
7318 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007319 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007320 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007321
Victor Stinner76a31a62011-11-04 00:05:13 +01007322 converted = decode_code_page_strict(code_page, &v,
7323 s, chunk_size);
7324 if (converted == -2)
7325 converted = decode_code_page_errors(code_page, &v,
7326 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007327 errors, final);
7328 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007329
7330 if (converted < 0) {
7331 Py_XDECREF(v);
7332 return NULL;
7333 }
7334
7335 if (consumed)
7336 *consumed += converted;
7337
7338 s += converted;
7339 size -= converted;
7340 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007341
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007342 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007343}
7344
Alexander Belopolsky40018472011-02-26 01:02:56 +00007345PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007346PyUnicode_DecodeCodePageStateful(int code_page,
7347 const char *s,
7348 Py_ssize_t size,
7349 const char *errors,
7350 Py_ssize_t *consumed)
7351{
7352 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7353}
7354
7355PyObject *
7356PyUnicode_DecodeMBCSStateful(const char *s,
7357 Py_ssize_t size,
7358 const char *errors,
7359 Py_ssize_t *consumed)
7360{
7361 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7362}
7363
7364PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007365PyUnicode_DecodeMBCS(const char *s,
7366 Py_ssize_t size,
7367 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007368{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007369 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7370}
7371
Victor Stinner3a50e702011-10-18 21:21:00 +02007372static DWORD
7373encode_code_page_flags(UINT code_page, const char *errors)
7374{
7375 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007376 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007377 }
7378 else if (code_page == CP_UTF7) {
7379 /* CP_UTF7 only supports flags=0 */
7380 return 0;
7381 }
7382 else {
7383 if (errors != NULL && strcmp(errors, "replace") == 0)
7384 return 0;
7385 else
7386 return WC_NO_BEST_FIT_CHARS;
7387 }
7388}
7389
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007390/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007391 * Encode a Unicode string to a Windows code page into a byte string in strict
7392 * mode.
7393 *
7394 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007395 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007396 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007397static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007398encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007399 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007400 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007401{
Victor Stinner554f3f02010-06-16 23:33:54 +00007402 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007403 BOOL *pusedDefaultChar = &usedDefaultChar;
7404 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007405 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007406 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 const DWORD flags = encode_code_page_flags(code_page, NULL);
7408 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007409 /* Create a substring so that we can get the UTF-16 representation
7410 of just the slice under consideration. */
7411 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007412
Martin v. Löwis3d325192011-11-04 18:23:06 +01007413 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007414
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007416 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007417 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007418 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007419
Victor Stinner2fc507f2011-11-04 20:06:39 +01007420 substring = PyUnicode_Substring(unicode, offset, offset+len);
7421 if (substring == NULL)
7422 return -1;
7423 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7424 if (p == NULL) {
7425 Py_DECREF(substring);
7426 return -1;
7427 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007428 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007429
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007430 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007431 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007432 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007433 NULL, 0,
7434 NULL, pusedDefaultChar);
7435 if (outsize <= 0)
7436 goto error;
7437 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007438 if (pusedDefaultChar && *pusedDefaultChar) {
7439 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007441 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007442
Victor Stinner3a50e702011-10-18 21:21:00 +02007443 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007444 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007446 if (*outbytes == NULL) {
7447 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007448 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007449 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007450 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007451 }
7452 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007453 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 const Py_ssize_t n = PyBytes_Size(*outbytes);
7455 if (outsize > PY_SSIZE_T_MAX - n) {
7456 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007457 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007458 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007460 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7461 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007462 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007463 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007464 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007465 }
7466
7467 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007468 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007469 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007470 out, outsize,
7471 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007472 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007473 if (outsize <= 0)
7474 goto error;
7475 if (pusedDefaultChar && *pusedDefaultChar)
7476 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007477 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007478
Victor Stinner3a50e702011-10-18 21:21:00 +02007479error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007480 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007481 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7482 return -2;
7483 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007484 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007485}
7486
Victor Stinner3a50e702011-10-18 21:21:00 +02007487/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007488 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007489 * error handler.
7490 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007491 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 * -1 on other error.
7493 */
7494static int
7495encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007496 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007497 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007498{
Victor Stinner3a50e702011-10-18 21:21:00 +02007499 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007500 Py_ssize_t pos = unicode_offset;
7501 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007502 /* Ideally, we should get reason from FormatMessage. This is the Windows
7503 2000 English version of the message. */
7504 const char *reason = "invalid character";
7505 /* 4=maximum length of a UTF-8 sequence */
7506 char buffer[4];
7507 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7508 Py_ssize_t outsize;
7509 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007510 PyObject *errorHandler = NULL;
7511 PyObject *exc = NULL;
7512 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007513 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007514 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007515 PyObject *rep;
7516 int ret = -1;
7517
7518 assert(insize > 0);
7519
7520 encoding = code_page_name(code_page, &encoding_obj);
7521 if (encoding == NULL)
7522 return -1;
7523
7524 if (errors == NULL || strcmp(errors, "strict") == 0) {
7525 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7526 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007527 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007528 if (exc != NULL) {
7529 PyCodec_StrictErrors(exc);
7530 Py_DECREF(exc);
7531 }
7532 Py_XDECREF(encoding_obj);
7533 return -1;
7534 }
7535
7536 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7537 pusedDefaultChar = &usedDefaultChar;
7538 else
7539 pusedDefaultChar = NULL;
7540
7541 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7542 PyErr_NoMemory();
7543 goto error;
7544 }
7545 outsize = insize * Py_ARRAY_LENGTH(buffer);
7546
7547 if (*outbytes == NULL) {
7548 /* Create string object */
7549 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7550 if (*outbytes == NULL)
7551 goto error;
7552 out = PyBytes_AS_STRING(*outbytes);
7553 }
7554 else {
7555 /* Extend string object */
7556 Py_ssize_t n = PyBytes_Size(*outbytes);
7557 if (n > PY_SSIZE_T_MAX - outsize) {
7558 PyErr_NoMemory();
7559 goto error;
7560 }
7561 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7562 goto error;
7563 out = PyBytes_AS_STRING(*outbytes) + n;
7564 }
7565
7566 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007567 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007568 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007569 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7570 wchar_t chars[2];
7571 int charsize;
7572 if (ch < 0x10000) {
7573 chars[0] = (wchar_t)ch;
7574 charsize = 1;
7575 }
7576 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007577 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7578 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007579 charsize = 2;
7580 }
7581
Victor Stinner3a50e702011-10-18 21:21:00 +02007582 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007583 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007584 buffer, Py_ARRAY_LENGTH(buffer),
7585 NULL, pusedDefaultChar);
7586 if (outsize > 0) {
7587 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7588 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007589 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007590 memcpy(out, buffer, outsize);
7591 out += outsize;
7592 continue;
7593 }
7594 }
7595 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7596 PyErr_SetFromWindowsErr(0);
7597 goto error;
7598 }
7599
Victor Stinner3a50e702011-10-18 21:21:00 +02007600 rep = unicode_encode_call_errorhandler(
7601 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007602 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007603 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007604 if (rep == NULL)
7605 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007606 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007607
7608 if (PyBytes_Check(rep)) {
7609 outsize = PyBytes_GET_SIZE(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 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7620 out += outsize;
7621 }
7622 else {
7623 Py_ssize_t i;
7624 enum PyUnicode_Kind kind;
7625 void *data;
7626
Benjamin Petersonbac79492012-01-14 13:34:47 -05007627 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007628 Py_DECREF(rep);
7629 goto error;
7630 }
7631
7632 outsize = PyUnicode_GET_LENGTH(rep);
7633 if (outsize != 1) {
7634 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7635 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7636 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7637 Py_DECREF(rep);
7638 goto error;
7639 }
7640 out = PyBytes_AS_STRING(*outbytes) + offset;
7641 }
7642 kind = PyUnicode_KIND(rep);
7643 data = PyUnicode_DATA(rep);
7644 for (i=0; i < outsize; i++) {
7645 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7646 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007647 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007648 encoding, unicode,
7649 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007650 "unable to encode error handler result to ASCII");
7651 Py_DECREF(rep);
7652 goto error;
7653 }
7654 *out = (unsigned char)ch;
7655 out++;
7656 }
7657 }
7658 Py_DECREF(rep);
7659 }
7660 /* write a NUL byte */
7661 *out = 0;
7662 outsize = out - PyBytes_AS_STRING(*outbytes);
7663 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7664 if (_PyBytes_Resize(outbytes, outsize) < 0)
7665 goto error;
7666 ret = 0;
7667
7668error:
7669 Py_XDECREF(encoding_obj);
7670 Py_XDECREF(errorHandler);
7671 Py_XDECREF(exc);
7672 return ret;
7673}
7674
Victor Stinner3a50e702011-10-18 21:21:00 +02007675static PyObject *
7676encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007677 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007678 const char *errors)
7679{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007680 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007681 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007682 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007683 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007684
Victor Stinner29dacf22015-01-26 16:41:32 +01007685 if (!PyUnicode_Check(unicode)) {
7686 PyErr_BadArgument();
7687 return NULL;
7688 }
7689
Benjamin Petersonbac79492012-01-14 13:34:47 -05007690 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007691 return NULL;
7692 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007693
Victor Stinner3a50e702011-10-18 21:21:00 +02007694 if (code_page < 0) {
7695 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7696 return NULL;
7697 }
7698
Martin v. Löwis3d325192011-11-04 18:23:06 +01007699 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007700 return PyBytes_FromStringAndSize(NULL, 0);
7701
Victor Stinner7581cef2011-11-03 22:32:33 +01007702 offset = 0;
7703 do
7704 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007705#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007706 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007707 chunks. */
7708 if (len > INT_MAX/2) {
7709 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007710 done = 0;
7711 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007712 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007713#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007714 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007715 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007716 done = 1;
7717 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007718
Victor Stinner76a31a62011-11-04 00:05:13 +01007719 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007720 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007721 errors);
7722 if (ret == -2)
7723 ret = encode_code_page_errors(code_page, &outbytes,
7724 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007725 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007726 if (ret < 0) {
7727 Py_XDECREF(outbytes);
7728 return NULL;
7729 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007730
Victor Stinner7581cef2011-11-03 22:32:33 +01007731 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007732 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007733 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007734
Victor Stinner3a50e702011-10-18 21:21:00 +02007735 return outbytes;
7736}
7737
7738PyObject *
7739PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7740 Py_ssize_t size,
7741 const char *errors)
7742{
Victor Stinner7581cef2011-11-03 22:32:33 +01007743 PyObject *unicode, *res;
7744 unicode = PyUnicode_FromUnicode(p, size);
7745 if (unicode == NULL)
7746 return NULL;
7747 res = encode_code_page(CP_ACP, unicode, errors);
7748 Py_DECREF(unicode);
7749 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007750}
7751
7752PyObject *
7753PyUnicode_EncodeCodePage(int code_page,
7754 PyObject *unicode,
7755 const char *errors)
7756{
Victor Stinner7581cef2011-11-03 22:32:33 +01007757 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007758}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007759
Alexander Belopolsky40018472011-02-26 01:02:56 +00007760PyObject *
7761PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007762{
Victor Stinner7581cef2011-11-03 22:32:33 +01007763 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007764}
7765
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007766#undef NEED_RETRY
7767
Steve Dowercc16be82016-09-08 10:35:16 -07007768#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007769
Guido van Rossumd57fd912000-03-10 22:53:23 +00007770/* --- Character Mapping Codec -------------------------------------------- */
7771
Victor Stinnerfb161b12013-04-18 01:44:27 +02007772static int
7773charmap_decode_string(const char *s,
7774 Py_ssize_t size,
7775 PyObject *mapping,
7776 const char *errors,
7777 _PyUnicodeWriter *writer)
7778{
7779 const char *starts = s;
7780 const char *e;
7781 Py_ssize_t startinpos, endinpos;
7782 PyObject *errorHandler = NULL, *exc = NULL;
7783 Py_ssize_t maplen;
7784 enum PyUnicode_Kind mapkind;
7785 void *mapdata;
7786 Py_UCS4 x;
7787 unsigned char ch;
7788
7789 if (PyUnicode_READY(mapping) == -1)
7790 return -1;
7791
7792 maplen = PyUnicode_GET_LENGTH(mapping);
7793 mapdata = PyUnicode_DATA(mapping);
7794 mapkind = PyUnicode_KIND(mapping);
7795
7796 e = s + size;
7797
7798 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7799 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7800 * is disabled in encoding aliases, latin1 is preferred because
7801 * its implementation is faster. */
7802 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7803 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7804 Py_UCS4 maxchar = writer->maxchar;
7805
7806 assert (writer->kind == PyUnicode_1BYTE_KIND);
7807 while (s < e) {
7808 ch = *s;
7809 x = mapdata_ucs1[ch];
7810 if (x > maxchar) {
7811 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7812 goto onError;
7813 maxchar = writer->maxchar;
7814 outdata = (Py_UCS1 *)writer->data;
7815 }
7816 outdata[writer->pos] = x;
7817 writer->pos++;
7818 ++s;
7819 }
7820 return 0;
7821 }
7822
7823 while (s < e) {
7824 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7825 enum PyUnicode_Kind outkind = writer->kind;
7826 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7827 if (outkind == PyUnicode_1BYTE_KIND) {
7828 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7829 Py_UCS4 maxchar = writer->maxchar;
7830 while (s < e) {
7831 ch = *s;
7832 x = mapdata_ucs2[ch];
7833 if (x > maxchar)
7834 goto Error;
7835 outdata[writer->pos] = x;
7836 writer->pos++;
7837 ++s;
7838 }
7839 break;
7840 }
7841 else if (outkind == PyUnicode_2BYTE_KIND) {
7842 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7843 while (s < e) {
7844 ch = *s;
7845 x = mapdata_ucs2[ch];
7846 if (x == 0xFFFE)
7847 goto Error;
7848 outdata[writer->pos] = x;
7849 writer->pos++;
7850 ++s;
7851 }
7852 break;
7853 }
7854 }
7855 ch = *s;
7856
7857 if (ch < maplen)
7858 x = PyUnicode_READ(mapkind, mapdata, ch);
7859 else
7860 x = 0xfffe; /* invalid value */
7861Error:
7862 if (x == 0xfffe)
7863 {
7864 /* undefined mapping */
7865 startinpos = s-starts;
7866 endinpos = startinpos+1;
7867 if (unicode_decode_call_errorhandler_writer(
7868 errors, &errorHandler,
7869 "charmap", "character maps to <undefined>",
7870 &starts, &e, &startinpos, &endinpos, &exc, &s,
7871 writer)) {
7872 goto onError;
7873 }
7874 continue;
7875 }
7876
7877 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7878 goto onError;
7879 ++s;
7880 }
7881 Py_XDECREF(errorHandler);
7882 Py_XDECREF(exc);
7883 return 0;
7884
7885onError:
7886 Py_XDECREF(errorHandler);
7887 Py_XDECREF(exc);
7888 return -1;
7889}
7890
7891static int
7892charmap_decode_mapping(const char *s,
7893 Py_ssize_t size,
7894 PyObject *mapping,
7895 const char *errors,
7896 _PyUnicodeWriter *writer)
7897{
7898 const char *starts = s;
7899 const char *e;
7900 Py_ssize_t startinpos, endinpos;
7901 PyObject *errorHandler = NULL, *exc = NULL;
7902 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007903 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007904
7905 e = s + size;
7906
7907 while (s < e) {
7908 ch = *s;
7909
7910 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7911 key = PyLong_FromLong((long)ch);
7912 if (key == NULL)
7913 goto onError;
7914
7915 item = PyObject_GetItem(mapping, key);
7916 Py_DECREF(key);
7917 if (item == NULL) {
7918 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7919 /* No mapping found means: mapping is undefined. */
7920 PyErr_Clear();
7921 goto Undefined;
7922 } else
7923 goto onError;
7924 }
7925
7926 /* Apply mapping */
7927 if (item == Py_None)
7928 goto Undefined;
7929 if (PyLong_Check(item)) {
7930 long value = PyLong_AS_LONG(item);
7931 if (value == 0xFFFE)
7932 goto Undefined;
7933 if (value < 0 || value > MAX_UNICODE) {
7934 PyErr_Format(PyExc_TypeError,
7935 "character mapping must be in range(0x%lx)",
7936 (unsigned long)MAX_UNICODE + 1);
7937 goto onError;
7938 }
7939
7940 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7941 goto onError;
7942 }
7943 else if (PyUnicode_Check(item)) {
7944 if (PyUnicode_READY(item) == -1)
7945 goto onError;
7946 if (PyUnicode_GET_LENGTH(item) == 1) {
7947 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7948 if (value == 0xFFFE)
7949 goto Undefined;
7950 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7951 goto onError;
7952 }
7953 else {
7954 writer->overallocate = 1;
7955 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7956 goto onError;
7957 }
7958 }
7959 else {
7960 /* wrong return value */
7961 PyErr_SetString(PyExc_TypeError,
7962 "character mapping must return integer, None or str");
7963 goto onError;
7964 }
7965 Py_CLEAR(item);
7966 ++s;
7967 continue;
7968
7969Undefined:
7970 /* undefined mapping */
7971 Py_CLEAR(item);
7972 startinpos = s-starts;
7973 endinpos = startinpos+1;
7974 if (unicode_decode_call_errorhandler_writer(
7975 errors, &errorHandler,
7976 "charmap", "character maps to <undefined>",
7977 &starts, &e, &startinpos, &endinpos, &exc, &s,
7978 writer)) {
7979 goto onError;
7980 }
7981 }
7982 Py_XDECREF(errorHandler);
7983 Py_XDECREF(exc);
7984 return 0;
7985
7986onError:
7987 Py_XDECREF(item);
7988 Py_XDECREF(errorHandler);
7989 Py_XDECREF(exc);
7990 return -1;
7991}
7992
Alexander Belopolsky40018472011-02-26 01:02:56 +00007993PyObject *
7994PyUnicode_DecodeCharmap(const char *s,
7995 Py_ssize_t size,
7996 PyObject *mapping,
7997 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007998{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007999 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008000
Guido van Rossumd57fd912000-03-10 22:53:23 +00008001 /* Default to Latin-1 */
8002 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008003 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008004
Guido van Rossumd57fd912000-03-10 22:53:23 +00008005 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008006 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008007 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008008 writer.min_length = size;
8009 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008010 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008011
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008012 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008013 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8014 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008015 }
8016 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008017 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8018 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008019 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008020 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008021
Benjamin Peterson29060642009-01-31 22:14:21 +00008022 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008023 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008024 return NULL;
8025}
8026
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008027/* Charmap encoding: the lookup table */
8028
Alexander Belopolsky40018472011-02-26 01:02:56 +00008029struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008030 PyObject_HEAD
8031 unsigned char level1[32];
8032 int count2, count3;
8033 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008034};
8035
8036static PyObject*
8037encoding_map_size(PyObject *obj, PyObject* args)
8038{
8039 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008040 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008042}
8043
8044static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008045 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008046 PyDoc_STR("Return the size (in bytes) of this object") },
8047 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008048};
8049
8050static void
8051encoding_map_dealloc(PyObject* o)
8052{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008053 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008054}
8055
8056static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008057 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 "EncodingMap", /*tp_name*/
8059 sizeof(struct encoding_map), /*tp_basicsize*/
8060 0, /*tp_itemsize*/
8061 /* methods */
8062 encoding_map_dealloc, /*tp_dealloc*/
8063 0, /*tp_print*/
8064 0, /*tp_getattr*/
8065 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008066 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008067 0, /*tp_repr*/
8068 0, /*tp_as_number*/
8069 0, /*tp_as_sequence*/
8070 0, /*tp_as_mapping*/
8071 0, /*tp_hash*/
8072 0, /*tp_call*/
8073 0, /*tp_str*/
8074 0, /*tp_getattro*/
8075 0, /*tp_setattro*/
8076 0, /*tp_as_buffer*/
8077 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8078 0, /*tp_doc*/
8079 0, /*tp_traverse*/
8080 0, /*tp_clear*/
8081 0, /*tp_richcompare*/
8082 0, /*tp_weaklistoffset*/
8083 0, /*tp_iter*/
8084 0, /*tp_iternext*/
8085 encoding_map_methods, /*tp_methods*/
8086 0, /*tp_members*/
8087 0, /*tp_getset*/
8088 0, /*tp_base*/
8089 0, /*tp_dict*/
8090 0, /*tp_descr_get*/
8091 0, /*tp_descr_set*/
8092 0, /*tp_dictoffset*/
8093 0, /*tp_init*/
8094 0, /*tp_alloc*/
8095 0, /*tp_new*/
8096 0, /*tp_free*/
8097 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098};
8099
8100PyObject*
8101PyUnicode_BuildEncodingMap(PyObject* string)
8102{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008103 PyObject *result;
8104 struct encoding_map *mresult;
8105 int i;
8106 int need_dict = 0;
8107 unsigned char level1[32];
8108 unsigned char level2[512];
8109 unsigned char *mlevel1, *mlevel2, *mlevel3;
8110 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008111 int kind;
8112 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008113 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008114 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008115
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008116 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008117 PyErr_BadArgument();
8118 return NULL;
8119 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008120 kind = PyUnicode_KIND(string);
8121 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008122 length = PyUnicode_GET_LENGTH(string);
8123 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008124 memset(level1, 0xFF, sizeof level1);
8125 memset(level2, 0xFF, sizeof level2);
8126
8127 /* If there isn't a one-to-one mapping of NULL to \0,
8128 or if there are non-BMP characters, we need to use
8129 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008130 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008131 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008132 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008133 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008134 ch = PyUnicode_READ(kind, data, i);
8135 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 need_dict = 1;
8137 break;
8138 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008139 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008140 /* unmapped character */
8141 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008142 l1 = ch >> 11;
8143 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008144 if (level1[l1] == 0xFF)
8145 level1[l1] = count2++;
8146 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008147 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008148 }
8149
8150 if (count2 >= 0xFF || count3 >= 0xFF)
8151 need_dict = 1;
8152
8153 if (need_dict) {
8154 PyObject *result = PyDict_New();
8155 PyObject *key, *value;
8156 if (!result)
8157 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008158 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008159 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008160 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008161 if (!key || !value)
8162 goto failed1;
8163 if (PyDict_SetItem(result, key, value) == -1)
8164 goto failed1;
8165 Py_DECREF(key);
8166 Py_DECREF(value);
8167 }
8168 return result;
8169 failed1:
8170 Py_XDECREF(key);
8171 Py_XDECREF(value);
8172 Py_DECREF(result);
8173 return NULL;
8174 }
8175
8176 /* Create a three-level trie */
8177 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8178 16*count2 + 128*count3 - 1);
8179 if (!result)
8180 return PyErr_NoMemory();
8181 PyObject_Init(result, &EncodingMapType);
8182 mresult = (struct encoding_map*)result;
8183 mresult->count2 = count2;
8184 mresult->count3 = count3;
8185 mlevel1 = mresult->level1;
8186 mlevel2 = mresult->level23;
8187 mlevel3 = mresult->level23 + 16*count2;
8188 memcpy(mlevel1, level1, 32);
8189 memset(mlevel2, 0xFF, 16*count2);
8190 memset(mlevel3, 0, 128*count3);
8191 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008192 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008193 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008194 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8195 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008196 /* unmapped character */
8197 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008198 o1 = ch>>11;
8199 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008200 i2 = 16*mlevel1[o1] + o2;
8201 if (mlevel2[i2] == 0xFF)
8202 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008203 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008204 i3 = 128*mlevel2[i2] + o3;
8205 mlevel3[i3] = i;
8206 }
8207 return result;
8208}
8209
8210static int
Victor Stinner22168992011-11-20 17:09:18 +01008211encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008212{
8213 struct encoding_map *map = (struct encoding_map*)mapping;
8214 int l1 = c>>11;
8215 int l2 = (c>>7) & 0xF;
8216 int l3 = c & 0x7F;
8217 int i;
8218
Victor Stinner22168992011-11-20 17:09:18 +01008219 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008220 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008221 if (c == 0)
8222 return 0;
8223 /* level 1*/
8224 i = map->level1[l1];
8225 if (i == 0xFF) {
8226 return -1;
8227 }
8228 /* level 2*/
8229 i = map->level23[16*i+l2];
8230 if (i == 0xFF) {
8231 return -1;
8232 }
8233 /* level 3 */
8234 i = map->level23[16*map->count2 + 128*i + l3];
8235 if (i == 0) {
8236 return -1;
8237 }
8238 return i;
8239}
8240
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008241/* Lookup the character ch in the mapping. If the character
8242 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008243 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008244static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008245charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008246{
Christian Heimes217cfd12007-12-02 14:31:20 +00008247 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008248 PyObject *x;
8249
8250 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008252 x = PyObject_GetItem(mapping, w);
8253 Py_DECREF(w);
8254 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008255 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8256 /* No mapping found means: mapping is undefined. */
8257 PyErr_Clear();
8258 x = Py_None;
8259 Py_INCREF(x);
8260 return x;
8261 } else
8262 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008263 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008264 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008266 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 long value = PyLong_AS_LONG(x);
8268 if (value < 0 || value > 255) {
8269 PyErr_SetString(PyExc_TypeError,
8270 "character mapping must be in range(256)");
8271 Py_DECREF(x);
8272 return NULL;
8273 }
8274 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008275 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008276 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008278 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008279 /* wrong return value */
8280 PyErr_Format(PyExc_TypeError,
8281 "character mapping must return integer, bytes or None, not %.400s",
8282 x->ob_type->tp_name);
8283 Py_DECREF(x);
8284 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008285 }
8286}
8287
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008288static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008289charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008290{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008291 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8292 /* exponentially overallocate to minimize reallocations */
8293 if (requiredsize < 2*outsize)
8294 requiredsize = 2*outsize;
8295 if (_PyBytes_Resize(outobj, requiredsize))
8296 return -1;
8297 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008298}
8299
Benjamin Peterson14339b62009-01-31 16:36:08 +00008300typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008301 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008302} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008303/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008304 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008305 space is available. Return a new reference to the object that
8306 was put in the output buffer, or Py_None, if the mapping was undefined
8307 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008308 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008309static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008310charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008311 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008312{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008313 PyObject *rep;
8314 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008315 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316
Christian Heimes90aa7642007-12-19 02:45:37 +00008317 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008318 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008320 if (res == -1)
8321 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 if (outsize<requiredsize)
8323 if (charmapencode_resize(outobj, outpos, requiredsize))
8324 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008325 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 outstart[(*outpos)++] = (char)res;
8327 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008328 }
8329
8330 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008332 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008333 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 Py_DECREF(rep);
8335 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008336 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008337 if (PyLong_Check(rep)) {
8338 Py_ssize_t requiredsize = *outpos+1;
8339 if (outsize<requiredsize)
8340 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8341 Py_DECREF(rep);
8342 return enc_EXCEPTION;
8343 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008344 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008346 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 else {
8348 const char *repchars = PyBytes_AS_STRING(rep);
8349 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8350 Py_ssize_t requiredsize = *outpos+repsize;
8351 if (outsize<requiredsize)
8352 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8353 Py_DECREF(rep);
8354 return enc_EXCEPTION;
8355 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008356 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 memcpy(outstart + *outpos, repchars, repsize);
8358 *outpos += repsize;
8359 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008361 Py_DECREF(rep);
8362 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008363}
8364
8365/* handle an error in PyUnicode_EncodeCharmap
8366 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008367static int
8368charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008369 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008370 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008371 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008372 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373{
8374 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008375 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008376 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008377 enum PyUnicode_Kind kind;
8378 void *data;
8379 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008381 Py_ssize_t collstartpos = *inpos;
8382 Py_ssize_t collendpos = *inpos+1;
8383 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384 char *encoding = "charmap";
8385 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008386 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008387 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008388 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389
Benjamin Petersonbac79492012-01-14 13:34:47 -05008390 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008391 return -1;
8392 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008393 /* find all unencodable characters */
8394 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008395 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008396 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008397 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008398 val = encoding_map_lookup(ch, mapping);
8399 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 break;
8401 ++collendpos;
8402 continue;
8403 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008404
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008405 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8406 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 if (rep==NULL)
8408 return -1;
8409 else if (rep!=Py_None) {
8410 Py_DECREF(rep);
8411 break;
8412 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008413 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008414 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008415 }
8416 /* cache callback name lookup
8417 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008418 if (*error_handler == _Py_ERROR_UNKNOWN)
8419 *error_handler = get_error_handler(errors);
8420
8421 switch (*error_handler) {
8422 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008423 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008424 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008425
8426 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008427 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008428 x = charmapencode_output('?', mapping, res, respos);
8429 if (x==enc_EXCEPTION) {
8430 return -1;
8431 }
8432 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008433 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 return -1;
8435 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008436 }
8437 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008438 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008439 *inpos = collendpos;
8440 break;
Victor Stinner50149202015-09-22 00:26:54 +02008441
8442 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008443 /* generate replacement (temporarily (mis)uses p) */
8444 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 char buffer[2+29+1+1];
8446 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008447 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 for (cp = buffer; *cp; ++cp) {
8449 x = charmapencode_output(*cp, mapping, res, respos);
8450 if (x==enc_EXCEPTION)
8451 return -1;
8452 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008453 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 return -1;
8455 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008456 }
8457 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008458 *inpos = collendpos;
8459 break;
Victor Stinner50149202015-09-22 00:26:54 +02008460
Benjamin Peterson14339b62009-01-31 16:36:08 +00008461 default:
Victor Stinner50149202015-09-22 00:26:54 +02008462 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008463 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008465 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008467 if (PyBytes_Check(repunicode)) {
8468 /* Directly copy bytes result to output. */
8469 Py_ssize_t outsize = PyBytes_Size(*res);
8470 Py_ssize_t requiredsize;
8471 repsize = PyBytes_Size(repunicode);
8472 requiredsize = *respos + repsize;
8473 if (requiredsize > outsize)
8474 /* Make room for all additional bytes. */
8475 if (charmapencode_resize(res, respos, requiredsize)) {
8476 Py_DECREF(repunicode);
8477 return -1;
8478 }
8479 memcpy(PyBytes_AsString(*res) + *respos,
8480 PyBytes_AsString(repunicode), repsize);
8481 *respos += repsize;
8482 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008483 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008484 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008485 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008486 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008487 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008488 Py_DECREF(repunicode);
8489 return -1;
8490 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008491 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008492 data = PyUnicode_DATA(repunicode);
8493 kind = PyUnicode_KIND(repunicode);
8494 for (index = 0; index < repsize; index++) {
8495 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8496 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008498 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 return -1;
8500 }
8501 else if (x==enc_FAILED) {
8502 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008503 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 return -1;
8505 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008506 }
8507 *inpos = newpos;
8508 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008509 }
8510 return 0;
8511}
8512
Alexander Belopolsky40018472011-02-26 01:02:56 +00008513PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008514_PyUnicode_EncodeCharmap(PyObject *unicode,
8515 PyObject *mapping,
8516 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008517{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518 /* output object */
8519 PyObject *res = NULL;
8520 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008521 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008522 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008523 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008524 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008525 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008526 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008527 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008528 void *data;
8529 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008530
Benjamin Petersonbac79492012-01-14 13:34:47 -05008531 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008532 return NULL;
8533 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008534 data = PyUnicode_DATA(unicode);
8535 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008536
Guido van Rossumd57fd912000-03-10 22:53:23 +00008537 /* Default to Latin-1 */
8538 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008539 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008540
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541 /* allocate enough for a simple encoding without
8542 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008543 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008544 if (res == NULL)
8545 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008546 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008547 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008548
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008549 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008550 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008551 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008552 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 if (x==enc_EXCEPTION) /* error */
8554 goto onError;
8555 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008556 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008558 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008559 &res, &respos)) {
8560 goto onError;
8561 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008562 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008563 else
8564 /* done with this character => adjust input position */
8565 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008567
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008569 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008570 if (_PyBytes_Resize(&res, respos) < 0)
8571 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008572
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008573 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008574 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008575 return res;
8576
Benjamin Peterson29060642009-01-31 22:14:21 +00008577 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008578 Py_XDECREF(res);
8579 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008580 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008581 return NULL;
8582}
8583
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008584/* Deprecated */
8585PyObject *
8586PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8587 Py_ssize_t size,
8588 PyObject *mapping,
8589 const char *errors)
8590{
8591 PyObject *result;
8592 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8593 if (unicode == NULL)
8594 return NULL;
8595 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8596 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008597 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008598}
8599
Alexander Belopolsky40018472011-02-26 01:02:56 +00008600PyObject *
8601PyUnicode_AsCharmapString(PyObject *unicode,
8602 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008603{
8604 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008605 PyErr_BadArgument();
8606 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008607 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008608 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008609}
8610
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008611/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008612static void
8613make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008614 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008615 Py_ssize_t startpos, Py_ssize_t endpos,
8616 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008617{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 *exceptionObject = _PyUnicodeTranslateError_Create(
8620 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008621 }
8622 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008623 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8624 goto onError;
8625 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8626 goto onError;
8627 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8628 goto onError;
8629 return;
8630 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008631 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008632 }
8633}
8634
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008635/* error handling callback helper:
8636 build arguments, call the callback and check the arguments,
8637 put the result into newpos and return the replacement string, which
8638 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008639static PyObject *
8640unicode_translate_call_errorhandler(const char *errors,
8641 PyObject **errorHandler,
8642 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008644 Py_ssize_t startpos, Py_ssize_t endpos,
8645 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008646{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008647 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008648
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008649 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650 PyObject *restuple;
8651 PyObject *resunicode;
8652
8653 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008655 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008656 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008657 }
8658
8659 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008661 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008663
8664 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008665 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008666 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008668 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008669 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008670 Py_DECREF(restuple);
8671 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008672 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008673 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008674 &resunicode, &i_newpos)) {
8675 Py_DECREF(restuple);
8676 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008677 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008678 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008680 else
8681 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008682 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008683 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 Py_DECREF(restuple);
8685 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008686 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687 Py_INCREF(resunicode);
8688 Py_DECREF(restuple);
8689 return resunicode;
8690}
8691
8692/* Lookup the character ch in the mapping and put the result in result,
8693 which must be decrefed by the caller.
8694 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008695static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008696charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008697{
Christian Heimes217cfd12007-12-02 14:31:20 +00008698 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008699 PyObject *x;
8700
8701 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008703 x = PyObject_GetItem(mapping, w);
8704 Py_DECREF(w);
8705 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8707 /* No mapping found means: use 1:1 mapping. */
8708 PyErr_Clear();
8709 *result = NULL;
8710 return 0;
8711 } else
8712 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008713 }
8714 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 *result = x;
8716 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008717 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008718 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008720 if (value < 0 || value > MAX_UNICODE) {
8721 PyErr_Format(PyExc_ValueError,
8722 "character mapping must be in range(0x%x)",
8723 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008724 Py_DECREF(x);
8725 return -1;
8726 }
8727 *result = x;
8728 return 0;
8729 }
8730 else if (PyUnicode_Check(x)) {
8731 *result = x;
8732 return 0;
8733 }
8734 else {
8735 /* wrong return value */
8736 PyErr_SetString(PyExc_TypeError,
8737 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008738 Py_DECREF(x);
8739 return -1;
8740 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008741}
Victor Stinner1194ea02014-04-04 19:37:40 +02008742
8743/* lookup the character, write the result into the writer.
8744 Return 1 if the result was written into the writer, return 0 if the mapping
8745 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008746static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008747charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8748 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008749{
Victor Stinner1194ea02014-04-04 19:37:40 +02008750 PyObject *item;
8751
8752 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008753 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008754
8755 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008756 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008757 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008758 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008759 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008760 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008761 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008762
8763 if (item == Py_None) {
8764 Py_DECREF(item);
8765 return 0;
8766 }
8767
8768 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008769 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8770 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8771 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008772 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8773 Py_DECREF(item);
8774 return -1;
8775 }
8776 Py_DECREF(item);
8777 return 1;
8778 }
8779
8780 if (!PyUnicode_Check(item)) {
8781 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008783 }
8784
8785 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8786 Py_DECREF(item);
8787 return -1;
8788 }
8789
8790 Py_DECREF(item);
8791 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008792}
8793
Victor Stinner89a76ab2014-04-05 11:44:04 +02008794static int
8795unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8796 Py_UCS1 *translate)
8797{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008798 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008799 int ret = 0;
8800
Victor Stinner89a76ab2014-04-05 11:44:04 +02008801 if (charmaptranslate_lookup(ch, mapping, &item)) {
8802 return -1;
8803 }
8804
8805 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008806 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008807 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008808 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008809 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008810 /* not found => default to 1:1 mapping */
8811 translate[ch] = ch;
8812 return 1;
8813 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008814 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008815 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008816 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8817 used it */
8818 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008819 /* invalid character or character outside ASCII:
8820 skip the fast translate */
8821 goto exit;
8822 }
8823 translate[ch] = (Py_UCS1)replace;
8824 }
8825 else if (PyUnicode_Check(item)) {
8826 Py_UCS4 replace;
8827
8828 if (PyUnicode_READY(item) == -1) {
8829 Py_DECREF(item);
8830 return -1;
8831 }
8832 if (PyUnicode_GET_LENGTH(item) != 1)
8833 goto exit;
8834
8835 replace = PyUnicode_READ_CHAR(item, 0);
8836 if (replace > 127)
8837 goto exit;
8838 translate[ch] = (Py_UCS1)replace;
8839 }
8840 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008841 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008842 goto exit;
8843 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008844 ret = 1;
8845
Benjamin Peterson1365de72014-04-07 20:15:41 -04008846 exit:
8847 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008848 return ret;
8849}
8850
8851/* Fast path for ascii => ascii translation. Return 1 if the whole string
8852 was translated into writer, return 0 if the input string was partially
8853 translated into writer, raise an exception and return -1 on error. */
8854static int
8855unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008856 _PyUnicodeWriter *writer, int ignore,
8857 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008858{
Victor Stinner872b2912014-04-05 14:27:07 +02008859 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008860 Py_ssize_t len;
8861 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008862 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008863
Victor Stinner89a76ab2014-04-05 11:44:04 +02008864 len = PyUnicode_GET_LENGTH(input);
8865
Victor Stinner872b2912014-04-05 14:27:07 +02008866 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008867
8868 in = PyUnicode_1BYTE_DATA(input);
8869 end = in + len;
8870
8871 assert(PyUnicode_IS_ASCII(writer->buffer));
8872 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8873 out = PyUnicode_1BYTE_DATA(writer->buffer);
8874
Victor Stinner872b2912014-04-05 14:27:07 +02008875 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008876 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008877 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008878 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008879 int translate = unicode_fast_translate_lookup(mapping, ch,
8880 ascii_table);
8881 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008882 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008883 if (translate == 0)
8884 goto exit;
8885 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008886 }
Victor Stinner872b2912014-04-05 14:27:07 +02008887 if (ch2 == 0xfe) {
8888 if (ignore)
8889 continue;
8890 goto exit;
8891 }
8892 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008893 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008894 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008895 }
Victor Stinner872b2912014-04-05 14:27:07 +02008896 res = 1;
8897
8898exit:
8899 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008900 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008901 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008902}
8903
Victor Stinner3222da22015-10-01 22:07:32 +02008904static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008905_PyUnicode_TranslateCharmap(PyObject *input,
8906 PyObject *mapping,
8907 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008909 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008910 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008911 Py_ssize_t size, i;
8912 int kind;
8913 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008914 _PyUnicodeWriter writer;
8915 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008916 char *reason = "character maps to <undefined>";
8917 PyObject *errorHandler = NULL;
8918 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008919 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008920 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008921
Guido van Rossumd57fd912000-03-10 22:53:23 +00008922 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 PyErr_BadArgument();
8924 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008925 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008926
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008927 if (PyUnicode_READY(input) == -1)
8928 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008929 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008930 kind = PyUnicode_KIND(input);
8931 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008932
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008933 if (size == 0)
8934 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008935
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008936 /* allocate enough for a simple 1:1 translation without
8937 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008938 _PyUnicodeWriter_Init(&writer);
8939 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008940 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008941
Victor Stinner872b2912014-04-05 14:27:07 +02008942 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8943
Victor Stinner33798672016-03-01 21:59:58 +01008944 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008945 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008946 if (PyUnicode_IS_ASCII(input)) {
8947 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8948 if (res < 0) {
8949 _PyUnicodeWriter_Dealloc(&writer);
8950 return NULL;
8951 }
8952 if (res == 1)
8953 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008954 }
Victor Stinner33798672016-03-01 21:59:58 +01008955 else {
8956 i = 0;
8957 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008959 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008960 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008961 int translate;
8962 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8963 Py_ssize_t newpos;
8964 /* startpos for collecting untranslatable chars */
8965 Py_ssize_t collstart;
8966 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008967 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008968
Victor Stinner1194ea02014-04-04 19:37:40 +02008969 ch = PyUnicode_READ(kind, data, i);
8970 translate = charmaptranslate_output(ch, mapping, &writer);
8971 if (translate < 0)
8972 goto onError;
8973
8974 if (translate != 0) {
8975 /* it worked => adjust input pointer */
8976 ++i;
8977 continue;
8978 }
8979
8980 /* untranslatable character */
8981 collstart = i;
8982 collend = i+1;
8983
8984 /* find all untranslatable characters */
8985 while (collend < size) {
8986 PyObject *x;
8987 ch = PyUnicode_READ(kind, data, collend);
8988 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008989 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008990 Py_XDECREF(x);
8991 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008992 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008993 ++collend;
8994 }
8995
8996 if (ignore) {
8997 i = collend;
8998 }
8999 else {
9000 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9001 reason, input, &exc,
9002 collstart, collend, &newpos);
9003 if (repunicode == NULL)
9004 goto onError;
9005 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009006 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009007 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009008 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009009 Py_DECREF(repunicode);
9010 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009011 }
9012 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009013 Py_XDECREF(exc);
9014 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009015 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009016
Benjamin Peterson29060642009-01-31 22:14:21 +00009017 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009018 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009019 Py_XDECREF(exc);
9020 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009021 return NULL;
9022}
9023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009024/* Deprecated. Use PyUnicode_Translate instead. */
9025PyObject *
9026PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9027 Py_ssize_t size,
9028 PyObject *mapping,
9029 const char *errors)
9030{
Christian Heimes5f520f42012-09-11 14:03:25 +02009031 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009032 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9033 if (!unicode)
9034 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009035 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9036 Py_DECREF(unicode);
9037 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009038}
9039
Alexander Belopolsky40018472011-02-26 01:02:56 +00009040PyObject *
9041PyUnicode_Translate(PyObject *str,
9042 PyObject *mapping,
9043 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009044{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009045 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009046 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009047 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009048}
Tim Petersced69f82003-09-16 20:30:58 +00009049
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009050static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009051fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009052{
9053 /* No need to call PyUnicode_READY(self) because this function is only
9054 called as a callback from fixup() which does it already. */
9055 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9056 const int kind = PyUnicode_KIND(self);
9057 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009058 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009059 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009060 Py_ssize_t i;
9061
9062 for (i = 0; i < len; ++i) {
9063 ch = PyUnicode_READ(kind, data, i);
9064 fixed = 0;
9065 if (ch > 127) {
9066 if (Py_UNICODE_ISSPACE(ch))
9067 fixed = ' ';
9068 else {
9069 const int decimal = Py_UNICODE_TODECIMAL(ch);
9070 if (decimal >= 0)
9071 fixed = '0' + decimal;
9072 }
9073 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009074 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009075 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076 PyUnicode_WRITE(kind, data, i, fixed);
9077 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009078 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009079 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009080 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009081 }
9082
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009083 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009084}
9085
9086PyObject *
9087_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9088{
9089 if (!PyUnicode_Check(unicode)) {
9090 PyErr_BadInternalCall();
9091 return NULL;
9092 }
9093 if (PyUnicode_READY(unicode) == -1)
9094 return NULL;
9095 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9096 /* If the string is already ASCII, just return the same string */
9097 Py_INCREF(unicode);
9098 return unicode;
9099 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009100 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009101}
9102
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009103PyObject *
9104PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9105 Py_ssize_t length)
9106{
Victor Stinnerf0124502011-11-21 23:12:56 +01009107 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009108 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009109 Py_UCS4 maxchar;
9110 enum PyUnicode_Kind kind;
9111 void *data;
9112
Victor Stinner99d7ad02012-02-22 13:37:39 +01009113 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009114 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009115 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009116 if (ch > 127) {
9117 int decimal = Py_UNICODE_TODECIMAL(ch);
9118 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009119 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009120 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009121 }
9122 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009123
9124 /* Copy to a new string */
9125 decimal = PyUnicode_New(length, maxchar);
9126 if (decimal == NULL)
9127 return decimal;
9128 kind = PyUnicode_KIND(decimal);
9129 data = PyUnicode_DATA(decimal);
9130 /* Iterate over code points */
9131 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009132 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009133 if (ch > 127) {
9134 int decimal = Py_UNICODE_TODECIMAL(ch);
9135 if (decimal >= 0)
9136 ch = '0' + decimal;
9137 }
9138 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009139 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009140 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009141}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009142/* --- Decimal Encoder ---------------------------------------------------- */
9143
Alexander Belopolsky40018472011-02-26 01:02:56 +00009144int
9145PyUnicode_EncodeDecimal(Py_UNICODE *s,
9146 Py_ssize_t length,
9147 char *output,
9148 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009149{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009150 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009151 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009152 enum PyUnicode_Kind kind;
9153 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009154
9155 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009156 PyErr_BadArgument();
9157 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009158 }
9159
Victor Stinner42bf7752011-11-21 22:52:58 +01009160 unicode = PyUnicode_FromUnicode(s, length);
9161 if (unicode == NULL)
9162 return -1;
9163
Benjamin Petersonbac79492012-01-14 13:34:47 -05009164 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009165 Py_DECREF(unicode);
9166 return -1;
9167 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009168 kind = PyUnicode_KIND(unicode);
9169 data = PyUnicode_DATA(unicode);
9170
Victor Stinnerb84d7232011-11-22 01:50:07 +01009171 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009172 PyObject *exc;
9173 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009174 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009175 Py_ssize_t startpos;
9176
9177 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009178
Benjamin Peterson29060642009-01-31 22:14:21 +00009179 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009180 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009181 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009182 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009183 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009184 decimal = Py_UNICODE_TODECIMAL(ch);
9185 if (decimal >= 0) {
9186 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009187 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009188 continue;
9189 }
9190 if (0 < ch && ch < 256) {
9191 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009192 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009193 continue;
9194 }
Victor Stinner6345be92011-11-25 20:09:01 +01009195
Victor Stinner42bf7752011-11-21 22:52:58 +01009196 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009197 exc = NULL;
9198 raise_encode_exception(&exc, "decimal", unicode,
9199 startpos, startpos+1,
9200 "invalid decimal Unicode string");
9201 Py_XDECREF(exc);
9202 Py_DECREF(unicode);
9203 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009204 }
9205 /* 0-terminate the output string */
9206 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009207 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009208 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009209}
9210
Guido van Rossumd57fd912000-03-10 22:53:23 +00009211/* --- Helpers ------------------------------------------------------------ */
9212
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009213/* helper macro to fixup start/end slice values */
9214#define ADJUST_INDICES(start, end, len) \
9215 if (end > len) \
9216 end = len; \
9217 else if (end < 0) { \
9218 end += len; \
9219 if (end < 0) \
9220 end = 0; \
9221 } \
9222 if (start < 0) { \
9223 start += len; \
9224 if (start < 0) \
9225 start = 0; \
9226 }
9227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009228static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009229any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009230 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009231 Py_ssize_t end,
9232 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009233{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009234 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009235 void *buf1, *buf2;
9236 Py_ssize_t len1, len2, result;
9237
9238 kind1 = PyUnicode_KIND(s1);
9239 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009240 if (kind1 < kind2)
9241 return -1;
9242
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009243 len1 = PyUnicode_GET_LENGTH(s1);
9244 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009245 ADJUST_INDICES(start, end, len1);
9246 if (end - start < len2)
9247 return -1;
9248
9249 buf1 = PyUnicode_DATA(s1);
9250 buf2 = PyUnicode_DATA(s2);
9251 if (len2 == 1) {
9252 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9253 result = findchar((const char *)buf1 + kind1*start,
9254 kind1, end - start, ch, direction);
9255 if (result == -1)
9256 return -1;
9257 else
9258 return start + result;
9259 }
9260
9261 if (kind2 != kind1) {
9262 buf2 = _PyUnicode_AsKind(s2, kind1);
9263 if (!buf2)
9264 return -2;
9265 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009266
Victor Stinner794d5672011-10-10 03:21:36 +02009267 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009268 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009269 case PyUnicode_1BYTE_KIND:
9270 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9271 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9272 else
9273 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9274 break;
9275 case PyUnicode_2BYTE_KIND:
9276 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9277 break;
9278 case PyUnicode_4BYTE_KIND:
9279 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9280 break;
9281 default:
9282 assert(0); result = -2;
9283 }
9284 }
9285 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009286 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009287 case PyUnicode_1BYTE_KIND:
9288 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9289 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9290 else
9291 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9292 break;
9293 case PyUnicode_2BYTE_KIND:
9294 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9295 break;
9296 case PyUnicode_4BYTE_KIND:
9297 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9298 break;
9299 default:
9300 assert(0); result = -2;
9301 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009302 }
9303
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009304 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305 PyMem_Free(buf2);
9306
9307 return result;
9308}
9309
9310Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009311_PyUnicode_InsertThousandsGrouping(
9312 PyObject *unicode, Py_ssize_t index,
9313 Py_ssize_t n_buffer,
9314 void *digits, Py_ssize_t n_digits,
9315 Py_ssize_t min_width,
9316 const char *grouping, PyObject *thousands_sep,
9317 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009318{
Victor Stinner41a863c2012-02-24 00:37:51 +01009319 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009320 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009321 Py_ssize_t thousands_sep_len;
9322 Py_ssize_t len;
9323
9324 if (unicode != NULL) {
9325 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009326 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009327 }
9328 else {
9329 kind = PyUnicode_1BYTE_KIND;
9330 data = NULL;
9331 }
9332 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9333 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9334 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9335 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009336 if (thousands_sep_kind < kind) {
9337 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9338 if (!thousands_sep_data)
9339 return -1;
9340 }
9341 else {
9342 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9343 if (!data)
9344 return -1;
9345 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009346 }
9347
Benjamin Petersonead6b532011-12-20 17:23:42 -06009348 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009349 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009350 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009351 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009352 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009353 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009354 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009355 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009356 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009357 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009358 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009359 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009360 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009361 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009362 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009363 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009364 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009365 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009366 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009367 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009368 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009369 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009370 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009371 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009372 break;
9373 default:
9374 assert(0);
9375 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009377 if (unicode != NULL && thousands_sep_kind != kind) {
9378 if (thousands_sep_kind < kind)
9379 PyMem_Free(thousands_sep_data);
9380 else
9381 PyMem_Free(data);
9382 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009383 if (unicode == NULL) {
9384 *maxchar = 127;
9385 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009386 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009387 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009388 }
9389 }
9390 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009391}
9392
9393
Alexander Belopolsky40018472011-02-26 01:02:56 +00009394Py_ssize_t
9395PyUnicode_Count(PyObject *str,
9396 PyObject *substr,
9397 Py_ssize_t start,
9398 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009399{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009400 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009401 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009402 void *buf1 = NULL, *buf2 = NULL;
9403 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009404
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009405 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009406 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009407
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009408 kind1 = PyUnicode_KIND(str);
9409 kind2 = PyUnicode_KIND(substr);
9410 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009411 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009412
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009413 len1 = PyUnicode_GET_LENGTH(str);
9414 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009416 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009417 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009418
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009419 buf1 = PyUnicode_DATA(str);
9420 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009421 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009422 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009423 if (!buf2)
9424 goto onError;
9425 }
9426
9427 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009428 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009429 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009430 result = asciilib_count(
9431 ((Py_UCS1*)buf1) + start, end - start,
9432 buf2, len2, PY_SSIZE_T_MAX
9433 );
9434 else
9435 result = ucs1lib_count(
9436 ((Py_UCS1*)buf1) + start, end - start,
9437 buf2, len2, PY_SSIZE_T_MAX
9438 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 break;
9440 case PyUnicode_2BYTE_KIND:
9441 result = ucs2lib_count(
9442 ((Py_UCS2*)buf1) + start, end - start,
9443 buf2, len2, PY_SSIZE_T_MAX
9444 );
9445 break;
9446 case PyUnicode_4BYTE_KIND:
9447 result = ucs4lib_count(
9448 ((Py_UCS4*)buf1) + start, end - start,
9449 buf2, len2, PY_SSIZE_T_MAX
9450 );
9451 break;
9452 default:
9453 assert(0); result = 0;
9454 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009455
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009456 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457 PyMem_Free(buf2);
9458
Guido van Rossumd57fd912000-03-10 22:53:23 +00009459 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009461 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462 PyMem_Free(buf2);
9463 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464}
9465
Alexander Belopolsky40018472011-02-26 01:02:56 +00009466Py_ssize_t
9467PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009468 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009469 Py_ssize_t start,
9470 Py_ssize_t end,
9471 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009473 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009474 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009475
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009476 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009477}
9478
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479Py_ssize_t
9480PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9481 Py_ssize_t start, Py_ssize_t end,
9482 int direction)
9483{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009485 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486 if (PyUnicode_READY(str) == -1)
9487 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009488 if (start < 0 || end < 0) {
9489 PyErr_SetString(PyExc_IndexError, "string index out of range");
9490 return -2;
9491 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 if (end > PyUnicode_GET_LENGTH(str))
9493 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009494 if (start >= end)
9495 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009496 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009497 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9498 kind, end-start, ch, direction);
9499 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009500 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009501 else
9502 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503}
9504
Alexander Belopolsky40018472011-02-26 01:02:56 +00009505static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009506tailmatch(PyObject *self,
9507 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009508 Py_ssize_t start,
9509 Py_ssize_t end,
9510 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009511{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512 int kind_self;
9513 int kind_sub;
9514 void *data_self;
9515 void *data_sub;
9516 Py_ssize_t offset;
9517 Py_ssize_t i;
9518 Py_ssize_t end_sub;
9519
9520 if (PyUnicode_READY(self) == -1 ||
9521 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009522 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009523
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009524 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9525 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009526 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009527 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009528
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009529 if (PyUnicode_GET_LENGTH(substring) == 0)
9530 return 1;
9531
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009532 kind_self = PyUnicode_KIND(self);
9533 data_self = PyUnicode_DATA(self);
9534 kind_sub = PyUnicode_KIND(substring);
9535 data_sub = PyUnicode_DATA(substring);
9536 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9537
9538 if (direction > 0)
9539 offset = end;
9540 else
9541 offset = start;
9542
9543 if (PyUnicode_READ(kind_self, data_self, offset) ==
9544 PyUnicode_READ(kind_sub, data_sub, 0) &&
9545 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9546 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9547 /* If both are of the same kind, memcmp is sufficient */
9548 if (kind_self == kind_sub) {
9549 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009550 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009551 data_sub,
9552 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009553 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009554 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009555 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009556 else {
9557 /* We do not need to compare 0 and len(substring)-1 because
9558 the if statement above ensured already that they are equal
9559 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 for (i = 1; i < end_sub; ++i) {
9561 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9562 PyUnicode_READ(kind_sub, data_sub, i))
9563 return 0;
9564 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009565 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009567 }
9568
9569 return 0;
9570}
9571
Alexander Belopolsky40018472011-02-26 01:02:56 +00009572Py_ssize_t
9573PyUnicode_Tailmatch(PyObject *str,
9574 PyObject *substr,
9575 Py_ssize_t start,
9576 Py_ssize_t end,
9577 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009579 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009580 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009581
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009582 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583}
9584
Guido van Rossumd57fd912000-03-10 22:53:23 +00009585/* Apply fixfct filter to the Unicode object self and return a
9586 reference to the modified object */
9587
Alexander Belopolsky40018472011-02-26 01:02:56 +00009588static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009589fixup(PyObject *self,
9590 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009591{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009592 PyObject *u;
9593 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009594 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009595
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009596 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009597 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009598 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009599 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009600
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009601 /* fix functions return the new maximum character in a string,
9602 if the kind of the resulting unicode object does not change,
9603 everything is fine. Otherwise we need to change the string kind
9604 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009605 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009606
9607 if (maxchar_new == 0) {
9608 /* no changes */;
9609 if (PyUnicode_CheckExact(self)) {
9610 Py_DECREF(u);
9611 Py_INCREF(self);
9612 return self;
9613 }
9614 else
9615 return u;
9616 }
9617
Victor Stinnere6abb482012-05-02 01:15:40 +02009618 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009619
Victor Stinnereaab6042011-12-11 22:22:39 +01009620 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009621 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009622
9623 /* In case the maximum character changed, we need to
9624 convert the string to the new category. */
9625 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9626 if (v == NULL) {
9627 Py_DECREF(u);
9628 return NULL;
9629 }
9630 if (maxchar_new > maxchar_old) {
9631 /* If the maxchar increased so that the kind changed, not all
9632 characters are representable anymore and we need to fix the
9633 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009634 _PyUnicode_FastCopyCharacters(v, 0,
9635 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009636 maxchar_old = fixfct(v);
9637 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638 }
9639 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009640 _PyUnicode_FastCopyCharacters(v, 0,
9641 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009642 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009643 Py_DECREF(u);
9644 assert(_PyUnicode_CheckConsistency(v, 1));
9645 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009646}
9647
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009648static PyObject *
9649ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009651 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9652 char *resdata, *data = PyUnicode_DATA(self);
9653 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009654
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009655 res = PyUnicode_New(len, 127);
9656 if (res == NULL)
9657 return NULL;
9658 resdata = PyUnicode_DATA(res);
9659 if (lower)
9660 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009661 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009662 _Py_bytes_upper(resdata, data, len);
9663 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009664}
9665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009666static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009667handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009669 Py_ssize_t j;
9670 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009671 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009672 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009673
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009674 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9675
9676 where ! is a negation and \p{xxx} is a character with property xxx.
9677 */
9678 for (j = i - 1; j >= 0; j--) {
9679 c = PyUnicode_READ(kind, data, j);
9680 if (!_PyUnicode_IsCaseIgnorable(c))
9681 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009682 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009683 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9684 if (final_sigma) {
9685 for (j = i + 1; j < length; j++) {
9686 c = PyUnicode_READ(kind, data, j);
9687 if (!_PyUnicode_IsCaseIgnorable(c))
9688 break;
9689 }
9690 final_sigma = j == length || !_PyUnicode_IsCased(c);
9691 }
9692 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009693}
9694
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009695static int
9696lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9697 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009698{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009699 /* Obscure special case. */
9700 if (c == 0x3A3) {
9701 mapped[0] = handle_capital_sigma(kind, data, length, i);
9702 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009703 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009704 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009705}
9706
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009707static Py_ssize_t
9708do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009709{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009710 Py_ssize_t i, k = 0;
9711 int n_res, j;
9712 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009713
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009714 c = PyUnicode_READ(kind, data, 0);
9715 n_res = _PyUnicode_ToUpperFull(c, mapped);
9716 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009717 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009718 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009719 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009720 for (i = 1; i < length; i++) {
9721 c = PyUnicode_READ(kind, data, i);
9722 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9723 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009724 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009725 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009726 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009727 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009728 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009729}
9730
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009731static Py_ssize_t
9732do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9733 Py_ssize_t i, k = 0;
9734
9735 for (i = 0; i < length; i++) {
9736 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9737 int n_res, j;
9738 if (Py_UNICODE_ISUPPER(c)) {
9739 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9740 }
9741 else if (Py_UNICODE_ISLOWER(c)) {
9742 n_res = _PyUnicode_ToUpperFull(c, mapped);
9743 }
9744 else {
9745 n_res = 1;
9746 mapped[0] = c;
9747 }
9748 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009749 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009750 res[k++] = mapped[j];
9751 }
9752 }
9753 return k;
9754}
9755
9756static Py_ssize_t
9757do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9758 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009759{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009760 Py_ssize_t i, k = 0;
9761
9762 for (i = 0; i < length; i++) {
9763 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9764 int n_res, j;
9765 if (lower)
9766 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9767 else
9768 n_res = _PyUnicode_ToUpperFull(c, mapped);
9769 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009770 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009771 res[k++] = mapped[j];
9772 }
9773 }
9774 return k;
9775}
9776
9777static Py_ssize_t
9778do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9779{
9780 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9781}
9782
9783static Py_ssize_t
9784do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9785{
9786 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9787}
9788
Benjamin Petersone51757f2012-01-12 21:10:29 -05009789static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009790do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9791{
9792 Py_ssize_t i, k = 0;
9793
9794 for (i = 0; i < length; i++) {
9795 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9796 Py_UCS4 mapped[3];
9797 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9798 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009799 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009800 res[k++] = mapped[j];
9801 }
9802 }
9803 return k;
9804}
9805
9806static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009807do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9808{
9809 Py_ssize_t i, k = 0;
9810 int previous_is_cased;
9811
9812 previous_is_cased = 0;
9813 for (i = 0; i < length; i++) {
9814 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9815 Py_UCS4 mapped[3];
9816 int n_res, j;
9817
9818 if (previous_is_cased)
9819 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9820 else
9821 n_res = _PyUnicode_ToTitleFull(c, mapped);
9822
9823 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009824 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009825 res[k++] = mapped[j];
9826 }
9827
9828 previous_is_cased = _PyUnicode_IsCased(c);
9829 }
9830 return k;
9831}
9832
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009833static PyObject *
9834case_operation(PyObject *self,
9835 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9836{
9837 PyObject *res = NULL;
9838 Py_ssize_t length, newlength = 0;
9839 int kind, outkind;
9840 void *data, *outdata;
9841 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9842
Benjamin Petersoneea48462012-01-16 14:28:50 -05009843 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009844
9845 kind = PyUnicode_KIND(self);
9846 data = PyUnicode_DATA(self);
9847 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009848 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009849 PyErr_SetString(PyExc_OverflowError, "string is too long");
9850 return NULL;
9851 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009852 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009853 if (tmp == NULL)
9854 return PyErr_NoMemory();
9855 newlength = perform(kind, data, length, tmp, &maxchar);
9856 res = PyUnicode_New(newlength, maxchar);
9857 if (res == NULL)
9858 goto leave;
9859 tmpend = tmp + newlength;
9860 outdata = PyUnicode_DATA(res);
9861 outkind = PyUnicode_KIND(res);
9862 switch (outkind) {
9863 case PyUnicode_1BYTE_KIND:
9864 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9865 break;
9866 case PyUnicode_2BYTE_KIND:
9867 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9868 break;
9869 case PyUnicode_4BYTE_KIND:
9870 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9871 break;
9872 default:
9873 assert(0);
9874 break;
9875 }
9876 leave:
9877 PyMem_FREE(tmp);
9878 return res;
9879}
9880
Tim Peters8ce9f162004-08-27 01:49:32 +00009881PyObject *
9882PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009883{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009884 PyObject *res;
9885 PyObject *fseq;
9886 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009887 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009888
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009889 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009890 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009891 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009892 }
9893
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009894 /* NOTE: the following code can't call back into Python code,
9895 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009896 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009897
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009898 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009899 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009900 res = _PyUnicode_JoinArray(separator, items, seqlen);
9901 Py_DECREF(fseq);
9902 return res;
9903}
9904
9905PyObject *
9906_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9907{
9908 PyObject *res = NULL; /* the result */
9909 PyObject *sep = NULL;
9910 Py_ssize_t seplen;
9911 PyObject *item;
9912 Py_ssize_t sz, i, res_offset;
9913 Py_UCS4 maxchar;
9914 Py_UCS4 item_maxchar;
9915 int use_memcpy;
9916 unsigned char *res_data = NULL, *sep_data = NULL;
9917 PyObject *last_obj;
9918 unsigned int kind = 0;
9919
Tim Peters05eba1f2004-08-27 21:32:02 +00009920 /* If empty sequence, return u"". */
9921 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009922 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009923 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009924
Tim Peters05eba1f2004-08-27 21:32:02 +00009925 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009926 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009927 if (seqlen == 1) {
9928 if (PyUnicode_CheckExact(items[0])) {
9929 res = items[0];
9930 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009931 return res;
9932 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009933 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009934 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009935 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009936 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009937 /* Set up sep and seplen */
9938 if (separator == NULL) {
9939 /* fall back to a blank space separator */
9940 sep = PyUnicode_FromOrdinal(' ');
9941 if (!sep)
9942 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009943 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009944 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009945 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009946 else {
9947 if (!PyUnicode_Check(separator)) {
9948 PyErr_Format(PyExc_TypeError,
9949 "separator: expected str instance,"
9950 " %.80s found",
9951 Py_TYPE(separator)->tp_name);
9952 goto onError;
9953 }
9954 if (PyUnicode_READY(separator))
9955 goto onError;
9956 sep = separator;
9957 seplen = PyUnicode_GET_LENGTH(separator);
9958 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9959 /* inc refcount to keep this code path symmetric with the
9960 above case of a blank separator */
9961 Py_INCREF(sep);
9962 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009963 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009964 }
9965
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009966 /* There are at least two things to join, or else we have a subclass
9967 * of str in the sequence.
9968 * Do a pre-pass to figure out the total amount of space we'll
9969 * need (sz), and see whether all argument are strings.
9970 */
9971 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009972#ifdef Py_DEBUG
9973 use_memcpy = 0;
9974#else
9975 use_memcpy = 1;
9976#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009977 for (i = 0; i < seqlen; i++) {
9978 const Py_ssize_t old_sz = sz;
9979 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009980 if (!PyUnicode_Check(item)) {
9981 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009982 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009983 " %.80s found",
9984 i, Py_TYPE(item)->tp_name);
9985 goto onError;
9986 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 if (PyUnicode_READY(item) == -1)
9988 goto onError;
9989 sz += PyUnicode_GET_LENGTH(item);
9990 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009991 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009992 if (i != 0)
9993 sz += seplen;
9994 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9995 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009996 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009997 goto onError;
9998 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009999 if (use_memcpy && last_obj != NULL) {
10000 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10001 use_memcpy = 0;
10002 }
10003 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010004 }
Tim Petersced69f82003-09-16 20:30:58 +000010005
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010007 if (res == NULL)
10008 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010009
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010010 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010011#ifdef Py_DEBUG
10012 use_memcpy = 0;
10013#else
10014 if (use_memcpy) {
10015 res_data = PyUnicode_1BYTE_DATA(res);
10016 kind = PyUnicode_KIND(res);
10017 if (seplen != 0)
10018 sep_data = PyUnicode_1BYTE_DATA(sep);
10019 }
10020#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010021 if (use_memcpy) {
10022 for (i = 0; i < seqlen; ++i) {
10023 Py_ssize_t itemlen;
10024 item = items[i];
10025
10026 /* Copy item, and maybe the separator. */
10027 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010028 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010029 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010030 kind * seplen);
10031 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010032 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010033
10034 itemlen = PyUnicode_GET_LENGTH(item);
10035 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010036 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010037 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010038 kind * itemlen);
10039 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010040 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010041 }
10042 assert(res_data == PyUnicode_1BYTE_DATA(res)
10043 + kind * PyUnicode_GET_LENGTH(res));
10044 }
10045 else {
10046 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10047 Py_ssize_t itemlen;
10048 item = items[i];
10049
10050 /* Copy item, and maybe the separator. */
10051 if (i && seplen != 0) {
10052 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10053 res_offset += seplen;
10054 }
10055
10056 itemlen = PyUnicode_GET_LENGTH(item);
10057 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010058 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010059 res_offset += itemlen;
10060 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010061 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010062 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010063 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010064
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010066 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010068
Benjamin Peterson29060642009-01-31 22:14:21 +000010069 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010071 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010072 return NULL;
10073}
10074
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010075#define FILL(kind, data, value, start, length) \
10076 do { \
10077 Py_ssize_t i_ = 0; \
10078 assert(kind != PyUnicode_WCHAR_KIND); \
10079 switch ((kind)) { \
10080 case PyUnicode_1BYTE_KIND: { \
10081 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010082 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 break; \
10084 } \
10085 case PyUnicode_2BYTE_KIND: { \
10086 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10087 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10088 break; \
10089 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010090 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010091 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10092 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10093 break; \
10094 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010095 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 } \
10097 } while (0)
10098
Victor Stinnerd3f08822012-05-29 12:57:52 +020010099void
10100_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10101 Py_UCS4 fill_char)
10102{
10103 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10104 const void *data = PyUnicode_DATA(unicode);
10105 assert(PyUnicode_IS_READY(unicode));
10106 assert(unicode_modifiable(unicode));
10107 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10108 assert(start >= 0);
10109 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10110 FILL(kind, data, fill_char, start, length);
10111}
10112
Victor Stinner3fe55312012-01-04 00:33:50 +010010113Py_ssize_t
10114PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10115 Py_UCS4 fill_char)
10116{
10117 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010118
10119 if (!PyUnicode_Check(unicode)) {
10120 PyErr_BadInternalCall();
10121 return -1;
10122 }
10123 if (PyUnicode_READY(unicode) == -1)
10124 return -1;
10125 if (unicode_check_modifiable(unicode))
10126 return -1;
10127
Victor Stinnerd3f08822012-05-29 12:57:52 +020010128 if (start < 0) {
10129 PyErr_SetString(PyExc_IndexError, "string index out of range");
10130 return -1;
10131 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010132 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10133 PyErr_SetString(PyExc_ValueError,
10134 "fill character is bigger than "
10135 "the string maximum character");
10136 return -1;
10137 }
10138
10139 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10140 length = Py_MIN(maxlen, length);
10141 if (length <= 0)
10142 return 0;
10143
Victor Stinnerd3f08822012-05-29 12:57:52 +020010144 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010145 return length;
10146}
10147
Victor Stinner9310abb2011-10-05 00:59:23 +020010148static PyObject *
10149pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010150 Py_ssize_t left,
10151 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010153{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 PyObject *u;
10155 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010156 int kind;
10157 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010158
10159 if (left < 0)
10160 left = 0;
10161 if (right < 0)
10162 right = 0;
10163
Victor Stinnerc4b49542011-12-11 22:44:26 +010010164 if (left == 0 && right == 0)
10165 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010166
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10168 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010169 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10170 return NULL;
10171 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010173 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010175 if (!u)
10176 return NULL;
10177
10178 kind = PyUnicode_KIND(u);
10179 data = PyUnicode_DATA(u);
10180 if (left)
10181 FILL(kind, data, fill, 0, left);
10182 if (right)
10183 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010184 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010185 assert(_PyUnicode_CheckConsistency(u, 1));
10186 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010187}
10188
Alexander Belopolsky40018472011-02-26 01:02:56 +000010189PyObject *
10190PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010191{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010192 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010193
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010194 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010195 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010196
Benjamin Petersonead6b532011-12-20 17:23:42 -060010197 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010199 if (PyUnicode_IS_ASCII(string))
10200 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010201 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010202 PyUnicode_GET_LENGTH(string), keepends);
10203 else
10204 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010205 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010206 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 break;
10208 case PyUnicode_2BYTE_KIND:
10209 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010210 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211 PyUnicode_GET_LENGTH(string), keepends);
10212 break;
10213 case PyUnicode_4BYTE_KIND:
10214 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010215 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 PyUnicode_GET_LENGTH(string), keepends);
10217 break;
10218 default:
10219 assert(0);
10220 list = 0;
10221 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010222 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010223}
10224
Alexander Belopolsky40018472011-02-26 01:02:56 +000010225static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010226split(PyObject *self,
10227 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010228 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010229{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010230 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 void *buf1, *buf2;
10232 Py_ssize_t len1, len2;
10233 PyObject* out;
10234
Guido van Rossumd57fd912000-03-10 22:53:23 +000010235 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010236 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010237
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 if (PyUnicode_READY(self) == -1)
10239 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010240
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010242 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010244 if (PyUnicode_IS_ASCII(self))
10245 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010246 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010247 PyUnicode_GET_LENGTH(self), maxcount
10248 );
10249 else
10250 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010251 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010252 PyUnicode_GET_LENGTH(self), maxcount
10253 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 case PyUnicode_2BYTE_KIND:
10255 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010256 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 PyUnicode_GET_LENGTH(self), maxcount
10258 );
10259 case PyUnicode_4BYTE_KIND:
10260 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010261 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 PyUnicode_GET_LENGTH(self), maxcount
10263 );
10264 default:
10265 assert(0);
10266 return NULL;
10267 }
10268
10269 if (PyUnicode_READY(substring) == -1)
10270 return NULL;
10271
10272 kind1 = PyUnicode_KIND(self);
10273 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010274 len1 = PyUnicode_GET_LENGTH(self);
10275 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010276 if (kind1 < kind2 || len1 < len2) {
10277 out = PyList_New(1);
10278 if (out == NULL)
10279 return NULL;
10280 Py_INCREF(self);
10281 PyList_SET_ITEM(out, 0, self);
10282 return out;
10283 }
10284 buf1 = PyUnicode_DATA(self);
10285 buf2 = PyUnicode_DATA(substring);
10286 if (kind2 != kind1) {
10287 buf2 = _PyUnicode_AsKind(substring, kind1);
10288 if (!buf2)
10289 return NULL;
10290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010292 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010294 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10295 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010296 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010297 else
10298 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010299 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 break;
10301 case PyUnicode_2BYTE_KIND:
10302 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010303 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 break;
10305 case PyUnicode_4BYTE_KIND:
10306 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010307 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 break;
10309 default:
10310 out = NULL;
10311 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010312 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 PyMem_Free(buf2);
10314 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010315}
10316
Alexander Belopolsky40018472011-02-26 01:02:56 +000010317static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010318rsplit(PyObject *self,
10319 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010320 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010321{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010322 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 void *buf1, *buf2;
10324 Py_ssize_t len1, len2;
10325 PyObject* out;
10326
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010327 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010328 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 if (PyUnicode_READY(self) == -1)
10331 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010332
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010334 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010335 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010336 if (PyUnicode_IS_ASCII(self))
10337 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010338 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010339 PyUnicode_GET_LENGTH(self), maxcount
10340 );
10341 else
10342 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010343 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010344 PyUnicode_GET_LENGTH(self), maxcount
10345 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 case PyUnicode_2BYTE_KIND:
10347 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010348 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 PyUnicode_GET_LENGTH(self), maxcount
10350 );
10351 case PyUnicode_4BYTE_KIND:
10352 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010353 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 PyUnicode_GET_LENGTH(self), maxcount
10355 );
10356 default:
10357 assert(0);
10358 return NULL;
10359 }
10360
10361 if (PyUnicode_READY(substring) == -1)
10362 return NULL;
10363
10364 kind1 = PyUnicode_KIND(self);
10365 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 len1 = PyUnicode_GET_LENGTH(self);
10367 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010368 if (kind1 < kind2 || len1 < len2) {
10369 out = PyList_New(1);
10370 if (out == NULL)
10371 return NULL;
10372 Py_INCREF(self);
10373 PyList_SET_ITEM(out, 0, self);
10374 return out;
10375 }
10376 buf1 = PyUnicode_DATA(self);
10377 buf2 = PyUnicode_DATA(substring);
10378 if (kind2 != kind1) {
10379 buf2 = _PyUnicode_AsKind(substring, kind1);
10380 if (!buf2)
10381 return NULL;
10382 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010384 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010386 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10387 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010388 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010389 else
10390 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010391 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 break;
10393 case PyUnicode_2BYTE_KIND:
10394 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010395 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 break;
10397 case PyUnicode_4BYTE_KIND:
10398 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010399 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 break;
10401 default:
10402 out = NULL;
10403 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010404 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 PyMem_Free(buf2);
10406 return out;
10407}
10408
10409static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010410anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10411 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010413 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010415 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10416 return asciilib_find(buf1, len1, buf2, len2, offset);
10417 else
10418 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 case PyUnicode_2BYTE_KIND:
10420 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10421 case PyUnicode_4BYTE_KIND:
10422 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10423 }
10424 assert(0);
10425 return -1;
10426}
10427
10428static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010429anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10430 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010432 switch (kind) {
10433 case PyUnicode_1BYTE_KIND:
10434 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10435 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10436 else
10437 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10438 case PyUnicode_2BYTE_KIND:
10439 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10440 case PyUnicode_4BYTE_KIND:
10441 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10442 }
10443 assert(0);
10444 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010445}
10446
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010447static void
10448replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10449 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10450{
10451 int kind = PyUnicode_KIND(u);
10452 void *data = PyUnicode_DATA(u);
10453 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10454 if (kind == PyUnicode_1BYTE_KIND) {
10455 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10456 (Py_UCS1 *)data + len,
10457 u1, u2, maxcount);
10458 }
10459 else if (kind == PyUnicode_2BYTE_KIND) {
10460 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10461 (Py_UCS2 *)data + len,
10462 u1, u2, maxcount);
10463 }
10464 else {
10465 assert(kind == PyUnicode_4BYTE_KIND);
10466 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10467 (Py_UCS4 *)data + len,
10468 u1, u2, maxcount);
10469 }
10470}
10471
Alexander Belopolsky40018472011-02-26 01:02:56 +000010472static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473replace(PyObject *self, PyObject *str1,
10474 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010475{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 PyObject *u;
10477 char *sbuf = PyUnicode_DATA(self);
10478 char *buf1 = PyUnicode_DATA(str1);
10479 char *buf2 = PyUnicode_DATA(str2);
10480 int srelease = 0, release1 = 0, release2 = 0;
10481 int skind = PyUnicode_KIND(self);
10482 int kind1 = PyUnicode_KIND(str1);
10483 int kind2 = PyUnicode_KIND(str2);
10484 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10485 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10486 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010487 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010488 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010489
10490 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010491 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010493 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010494
Victor Stinner59de0ee2011-10-07 10:01:28 +020010495 if (str1 == str2)
10496 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497
Victor Stinner49a0a212011-10-12 23:46:10 +020010498 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010499 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10500 if (maxchar < maxchar_str1)
10501 /* substring too wide to be present */
10502 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010503 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10504 /* Replacing str1 with str2 may cause a maxchar reduction in the
10505 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010506 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010507 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010510 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010512 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010514 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010515 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010516 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010517
Victor Stinner69ed0f42013-04-09 21:48:24 +020010518 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010519 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010520 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010521 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010522 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010524 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010525 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010526
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010527 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10528 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010529 }
10530 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010531 int rkind = skind;
10532 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010533 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010534
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010535 if (kind1 < rkind) {
10536 /* widen substring */
10537 buf1 = _PyUnicode_AsKind(str1, rkind);
10538 if (!buf1) goto error;
10539 release1 = 1;
10540 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010541 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010542 if (i < 0)
10543 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 if (rkind > kind2) {
10545 /* widen replacement */
10546 buf2 = _PyUnicode_AsKind(str2, rkind);
10547 if (!buf2) goto error;
10548 release2 = 1;
10549 }
10550 else if (rkind < kind2) {
10551 /* widen self and buf1 */
10552 rkind = kind2;
10553 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010554 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 sbuf = _PyUnicode_AsKind(self, rkind);
10556 if (!sbuf) goto error;
10557 srelease = 1;
10558 buf1 = _PyUnicode_AsKind(str1, rkind);
10559 if (!buf1) goto error;
10560 release1 = 1;
10561 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010562 u = PyUnicode_New(slen, maxchar);
10563 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010565 assert(PyUnicode_KIND(u) == rkind);
10566 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010567
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010568 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010569 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010570 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010572 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010574
10575 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010576 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010577 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010578 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010579 if (i == -1)
10580 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010581 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010583 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010585 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010586 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010587 }
10588 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010590 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 int rkind = skind;
10592 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010593
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010594 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010595 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 buf1 = _PyUnicode_AsKind(str1, rkind);
10597 if (!buf1) goto error;
10598 release1 = 1;
10599 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010600 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010601 if (n == 0)
10602 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010604 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 buf2 = _PyUnicode_AsKind(str2, rkind);
10606 if (!buf2) goto error;
10607 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010608 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010610 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611 rkind = kind2;
10612 sbuf = _PyUnicode_AsKind(self, rkind);
10613 if (!sbuf) goto error;
10614 srelease = 1;
10615 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010616 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 buf1 = _PyUnicode_AsKind(str1, rkind);
10618 if (!buf1) goto error;
10619 release1 = 1;
10620 }
10621 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10622 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010623 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 PyErr_SetString(PyExc_OverflowError,
10625 "replace string is too long");
10626 goto error;
10627 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010628 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010629 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010630 _Py_INCREF_UNICODE_EMPTY();
10631 if (!unicode_empty)
10632 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010633 u = unicode_empty;
10634 goto done;
10635 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010636 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010637 PyErr_SetString(PyExc_OverflowError,
10638 "replace string is too long");
10639 goto error;
10640 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010641 u = PyUnicode_New(new_size, maxchar);
10642 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010643 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010644 assert(PyUnicode_KIND(u) == rkind);
10645 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 ires = i = 0;
10647 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010648 while (n-- > 0) {
10649 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010650 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010651 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010652 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010653 if (j == -1)
10654 break;
10655 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010656 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010657 memcpy(res + rkind * ires,
10658 sbuf + rkind * i,
10659 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010660 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010661 }
10662 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010664 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010665 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010666 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010667 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010670 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010671 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010672 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010673 memcpy(res + rkind * ires,
10674 sbuf + rkind * i,
10675 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010676 }
10677 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010678 /* interleave */
10679 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010680 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010682 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010684 if (--n <= 0)
10685 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010686 memcpy(res + rkind * ires,
10687 sbuf + rkind * i,
10688 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 ires++;
10690 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010691 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010692 memcpy(res + rkind * ires,
10693 sbuf + rkind * i,
10694 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010695 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010696 }
10697
10698 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010699 unicode_adjust_maxchar(&u);
10700 if (u == NULL)
10701 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010702 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010703
10704 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010705 if (srelease)
10706 PyMem_FREE(sbuf);
10707 if (release1)
10708 PyMem_FREE(buf1);
10709 if (release2)
10710 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010711 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010712 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010713
Benjamin Peterson29060642009-01-31 22:14:21 +000010714 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010715 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010716 if (srelease)
10717 PyMem_FREE(sbuf);
10718 if (release1)
10719 PyMem_FREE(buf1);
10720 if (release2)
10721 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010722 return unicode_result_unchanged(self);
10723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010724 error:
10725 if (srelease && sbuf)
10726 PyMem_FREE(sbuf);
10727 if (release1 && buf1)
10728 PyMem_FREE(buf1);
10729 if (release2 && buf2)
10730 PyMem_FREE(buf2);
10731 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010732}
10733
10734/* --- Unicode Object Methods --------------------------------------------- */
10735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010736PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010737 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010738\n\
10739Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010740characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010741
10742static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010743unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010745 if (PyUnicode_READY(self) == -1)
10746 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010747 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010748}
10749
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010750PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010751 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010752\n\
10753Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010754have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010755
10756static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010757unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010758{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010759 if (PyUnicode_READY(self) == -1)
10760 return NULL;
10761 if (PyUnicode_GET_LENGTH(self) == 0)
10762 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010763 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764}
10765
Benjamin Petersond5890c82012-01-14 13:23:30 -050010766PyDoc_STRVAR(casefold__doc__,
10767 "S.casefold() -> str\n\
10768\n\
10769Return a version of S suitable for caseless comparisons.");
10770
10771static PyObject *
10772unicode_casefold(PyObject *self)
10773{
10774 if (PyUnicode_READY(self) == -1)
10775 return NULL;
10776 if (PyUnicode_IS_ASCII(self))
10777 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010778 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010779}
10780
10781
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010782/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010783
10784static int
10785convert_uc(PyObject *obj, void *addr)
10786{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010788
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010789 if (!PyUnicode_Check(obj)) {
10790 PyErr_Format(PyExc_TypeError,
10791 "The fill character must be a unicode character, "
10792 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010793 return 0;
10794 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010795 if (PyUnicode_READY(obj) < 0)
10796 return 0;
10797 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010798 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010799 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010800 return 0;
10801 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010802 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010803 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010804}
10805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010806PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010807 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010809Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010810done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010811
10812static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010813unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010814{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010815 Py_ssize_t marg, left;
10816 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010817 Py_UCS4 fillchar = ' ';
10818
Victor Stinnere9a29352011-10-01 02:14:59 +020010819 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010820 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821
Benjamin Petersonbac79492012-01-14 13:34:47 -050010822 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010823 return NULL;
10824
Victor Stinnerc4b49542011-12-11 22:44:26 +010010825 if (PyUnicode_GET_LENGTH(self) >= width)
10826 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010827
Victor Stinnerc4b49542011-12-11 22:44:26 +010010828 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010829 left = marg / 2 + (marg & width & 1);
10830
Victor Stinner9310abb2011-10-05 00:59:23 +020010831 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010832}
10833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010834/* This function assumes that str1 and str2 are readied by the caller. */
10835
Marc-André Lemburge5034372000-08-08 08:04:29 +000010836static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010837unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010838{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010839#define COMPARE(TYPE1, TYPE2) \
10840 do { \
10841 TYPE1* p1 = (TYPE1 *)data1; \
10842 TYPE2* p2 = (TYPE2 *)data2; \
10843 TYPE1* end = p1 + len; \
10844 Py_UCS4 c1, c2; \
10845 for (; p1 != end; p1++, p2++) { \
10846 c1 = *p1; \
10847 c2 = *p2; \
10848 if (c1 != c2) \
10849 return (c1 < c2) ? -1 : 1; \
10850 } \
10851 } \
10852 while (0)
10853
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010854 int kind1, kind2;
10855 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010856 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010857
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010858 kind1 = PyUnicode_KIND(str1);
10859 kind2 = PyUnicode_KIND(str2);
10860 data1 = PyUnicode_DATA(str1);
10861 data2 = PyUnicode_DATA(str2);
10862 len1 = PyUnicode_GET_LENGTH(str1);
10863 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010864 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010865
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010866 switch(kind1) {
10867 case PyUnicode_1BYTE_KIND:
10868 {
10869 switch(kind2) {
10870 case PyUnicode_1BYTE_KIND:
10871 {
10872 int cmp = memcmp(data1, data2, len);
10873 /* normalize result of memcmp() into the range [-1; 1] */
10874 if (cmp < 0)
10875 return -1;
10876 if (cmp > 0)
10877 return 1;
10878 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010879 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010880 case PyUnicode_2BYTE_KIND:
10881 COMPARE(Py_UCS1, Py_UCS2);
10882 break;
10883 case PyUnicode_4BYTE_KIND:
10884 COMPARE(Py_UCS1, Py_UCS4);
10885 break;
10886 default:
10887 assert(0);
10888 }
10889 break;
10890 }
10891 case PyUnicode_2BYTE_KIND:
10892 {
10893 switch(kind2) {
10894 case PyUnicode_1BYTE_KIND:
10895 COMPARE(Py_UCS2, Py_UCS1);
10896 break;
10897 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010898 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010899 COMPARE(Py_UCS2, Py_UCS2);
10900 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010901 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010902 case PyUnicode_4BYTE_KIND:
10903 COMPARE(Py_UCS2, Py_UCS4);
10904 break;
10905 default:
10906 assert(0);
10907 }
10908 break;
10909 }
10910 case PyUnicode_4BYTE_KIND:
10911 {
10912 switch(kind2) {
10913 case PyUnicode_1BYTE_KIND:
10914 COMPARE(Py_UCS4, Py_UCS1);
10915 break;
10916 case PyUnicode_2BYTE_KIND:
10917 COMPARE(Py_UCS4, Py_UCS2);
10918 break;
10919 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010920 {
10921#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10922 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10923 /* normalize result of wmemcmp() into the range [-1; 1] */
10924 if (cmp < 0)
10925 return -1;
10926 if (cmp > 0)
10927 return 1;
10928#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010929 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010930#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010931 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010932 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010933 default:
10934 assert(0);
10935 }
10936 break;
10937 }
10938 default:
10939 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010940 }
10941
Victor Stinner770e19e2012-10-04 22:59:45 +020010942 if (len1 == len2)
10943 return 0;
10944 if (len1 < len2)
10945 return -1;
10946 else
10947 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010948
10949#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010950}
10951
Benjamin Peterson621b4302016-09-09 13:54:34 -070010952static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010953unicode_compare_eq(PyObject *str1, PyObject *str2)
10954{
10955 int kind;
10956 void *data1, *data2;
10957 Py_ssize_t len;
10958 int cmp;
10959
Victor Stinnere5567ad2012-10-23 02:48:49 +020010960 len = PyUnicode_GET_LENGTH(str1);
10961 if (PyUnicode_GET_LENGTH(str2) != len)
10962 return 0;
10963 kind = PyUnicode_KIND(str1);
10964 if (PyUnicode_KIND(str2) != kind)
10965 return 0;
10966 data1 = PyUnicode_DATA(str1);
10967 data2 = PyUnicode_DATA(str2);
10968
10969 cmp = memcmp(data1, data2, len * kind);
10970 return (cmp == 0);
10971}
10972
10973
Alexander Belopolsky40018472011-02-26 01:02:56 +000010974int
10975PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010976{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010977 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10978 if (PyUnicode_READY(left) == -1 ||
10979 PyUnicode_READY(right) == -1)
10980 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010981
10982 /* a string is equal to itself */
10983 if (left == right)
10984 return 0;
10985
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010986 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010988 PyErr_Format(PyExc_TypeError,
10989 "Can't compare %.100s and %.100s",
10990 left->ob_type->tp_name,
10991 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992 return -1;
10993}
10994
Martin v. Löwis5b222132007-06-10 09:51:05 +000010995int
10996PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10997{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010998 Py_ssize_t i;
10999 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011000 Py_UCS4 chr;
11001
Victor Stinner910337b2011-10-03 03:20:16 +020011002 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011003 if (PyUnicode_READY(uni) == -1)
11004 return -1;
11005 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011006 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011007 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011008 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011009 size_t len, len2 = strlen(str);
11010 int cmp;
11011
11012 len = Py_MIN(len1, len2);
11013 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011014 if (cmp != 0) {
11015 if (cmp < 0)
11016 return -1;
11017 else
11018 return 1;
11019 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011020 if (len1 > len2)
11021 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011022 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011023 return -1; /* str is longer */
11024 return 0;
11025 }
11026 else {
11027 void *data = PyUnicode_DATA(uni);
11028 /* Compare Unicode string and source character set string */
11029 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011030 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011031 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11032 /* This check keeps Python strings that end in '\0' from comparing equal
11033 to C strings identical up to that point. */
11034 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11035 return 1; /* uni is longer */
11036 if (str[i])
11037 return -1; /* str is longer */
11038 return 0;
11039 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011040}
11041
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011042static int
11043non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11044{
11045 size_t i, len;
11046 const wchar_t *p;
11047 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11048 if (strlen(str) != len)
11049 return 0;
11050 p = _PyUnicode_WSTR(unicode);
11051 assert(p);
11052 for (i = 0; i < len; i++) {
11053 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011054 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011055 return 0;
11056 }
11057 return 1;
11058}
11059
11060int
11061_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11062{
11063 size_t len;
11064 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011065 assert(str);
11066#ifndef NDEBUG
11067 for (const char *p = str; *p; p++) {
11068 assert((unsigned char)*p < 128);
11069 }
11070#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011071 if (PyUnicode_READY(unicode) == -1) {
11072 /* Memory error or bad data */
11073 PyErr_Clear();
11074 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11075 }
11076 if (!PyUnicode_IS_ASCII(unicode))
11077 return 0;
11078 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11079 return strlen(str) == len &&
11080 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11081}
11082
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011083int
11084_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11085{
11086 PyObject *right_uni;
11087 Py_hash_t hash;
11088
11089 assert(_PyUnicode_CHECK(left));
11090 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011091#ifndef NDEBUG
11092 for (const char *p = right->string; *p; p++) {
11093 assert((unsigned char)*p < 128);
11094 }
11095#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011096
11097 if (PyUnicode_READY(left) == -1) {
11098 /* memory error or bad data */
11099 PyErr_Clear();
11100 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11101 }
11102
11103 if (!PyUnicode_IS_ASCII(left))
11104 return 0;
11105
11106 right_uni = _PyUnicode_FromId(right); /* borrowed */
11107 if (right_uni == NULL) {
11108 /* memory error or bad data */
11109 PyErr_Clear();
11110 return _PyUnicode_EqualToASCIIString(left, right->string);
11111 }
11112
11113 if (left == right_uni)
11114 return 1;
11115
11116 if (PyUnicode_CHECK_INTERNED(left))
11117 return 0;
11118
11119 assert(_PyUnicode_HASH(right_uni) != 1);
11120 hash = _PyUnicode_HASH(left);
11121 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11122 return 0;
11123
11124 return unicode_compare_eq(left, right_uni);
11125}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011126
Benjamin Peterson29060642009-01-31 22:14:21 +000011127#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011128 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011129
Alexander Belopolsky40018472011-02-26 01:02:56 +000011130PyObject *
11131PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011132{
11133 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011134 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011135
Victor Stinnere5567ad2012-10-23 02:48:49 +020011136 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11137 Py_RETURN_NOTIMPLEMENTED;
11138
11139 if (PyUnicode_READY(left) == -1 ||
11140 PyUnicode_READY(right) == -1)
11141 return NULL;
11142
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011143 if (left == right) {
11144 switch (op) {
11145 case Py_EQ:
11146 case Py_LE:
11147 case Py_GE:
11148 /* a string is equal to itself */
11149 v = Py_True;
11150 break;
11151 case Py_NE:
11152 case Py_LT:
11153 case Py_GT:
11154 v = Py_False;
11155 break;
11156 default:
11157 PyErr_BadArgument();
11158 return NULL;
11159 }
11160 }
11161 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011162 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011163 result ^= (op == Py_NE);
11164 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011165 }
11166 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011167 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011168
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011169 /* Convert the return value to a Boolean */
11170 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011171 case Py_LE:
11172 v = TEST_COND(result <= 0);
11173 break;
11174 case Py_GE:
11175 v = TEST_COND(result >= 0);
11176 break;
11177 case Py_LT:
11178 v = TEST_COND(result == -1);
11179 break;
11180 case Py_GT:
11181 v = TEST_COND(result == 1);
11182 break;
11183 default:
11184 PyErr_BadArgument();
11185 return NULL;
11186 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011187 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011188 Py_INCREF(v);
11189 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011190}
11191
Alexander Belopolsky40018472011-02-26 01:02:56 +000011192int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011193_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11194{
11195 return unicode_eq(aa, bb);
11196}
11197
11198int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011199PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011200{
Victor Stinner77282cb2013-04-14 19:22:47 +020011201 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011202 void *buf1, *buf2;
11203 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011204 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011205
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011206 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011207 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011208 "'in <string>' requires string as left operand, not %.100s",
11209 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011210 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011211 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011212 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011213 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011214 if (ensure_unicode(str) < 0)
11215 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011217 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011218 kind2 = PyUnicode_KIND(substr);
11219 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011220 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011221 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011222 len2 = PyUnicode_GET_LENGTH(substr);
11223 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011224 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011225 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011226 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011227 if (len2 == 1) {
11228 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11229 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011230 return result;
11231 }
11232 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011233 buf2 = _PyUnicode_AsKind(substr, kind1);
11234 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011235 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011236 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011237
Victor Stinner77282cb2013-04-14 19:22:47 +020011238 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011239 case PyUnicode_1BYTE_KIND:
11240 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11241 break;
11242 case PyUnicode_2BYTE_KIND:
11243 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11244 break;
11245 case PyUnicode_4BYTE_KIND:
11246 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11247 break;
11248 default:
11249 result = -1;
11250 assert(0);
11251 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011252
Victor Stinner77282cb2013-04-14 19:22:47 +020011253 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011254 PyMem_Free(buf2);
11255
Guido van Rossum403d68b2000-03-13 15:55:09 +000011256 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011257}
11258
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259/* Concat to string or Unicode object giving a new Unicode object. */
11260
Alexander Belopolsky40018472011-02-26 01:02:56 +000011261PyObject *
11262PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011264 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011265 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011266 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011268 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11269 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270
11271 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011272 if (left == unicode_empty)
11273 return PyUnicode_FromObject(right);
11274 if (right == unicode_empty)
11275 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011277 left_len = PyUnicode_GET_LENGTH(left);
11278 right_len = PyUnicode_GET_LENGTH(right);
11279 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011280 PyErr_SetString(PyExc_OverflowError,
11281 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011282 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011283 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011284 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011285
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011286 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11287 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011288 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011289
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011291 result = PyUnicode_New(new_len, maxchar);
11292 if (result == NULL)
11293 return NULL;
11294 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11295 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11296 assert(_PyUnicode_CheckConsistency(result, 1));
11297 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298}
11299
Walter Dörwald1ab83302007-05-18 17:15:44 +000011300void
Victor Stinner23e56682011-10-03 03:54:37 +020011301PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011302{
Victor Stinner23e56682011-10-03 03:54:37 +020011303 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011304 Py_UCS4 maxchar, maxchar2;
11305 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011306
11307 if (p_left == NULL) {
11308 if (!PyErr_Occurred())
11309 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011310 return;
11311 }
Victor Stinner23e56682011-10-03 03:54:37 +020011312 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011313 if (right == NULL || left == NULL
11314 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011315 if (!PyErr_Occurred())
11316 PyErr_BadInternalCall();
11317 goto error;
11318 }
11319
Benjamin Petersonbac79492012-01-14 13:34:47 -050011320 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011321 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011322 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011323 goto error;
11324
Victor Stinner488fa492011-12-12 00:01:39 +010011325 /* Shortcuts */
11326 if (left == unicode_empty) {
11327 Py_DECREF(left);
11328 Py_INCREF(right);
11329 *p_left = right;
11330 return;
11331 }
11332 if (right == unicode_empty)
11333 return;
11334
11335 left_len = PyUnicode_GET_LENGTH(left);
11336 right_len = PyUnicode_GET_LENGTH(right);
11337 if (left_len > PY_SSIZE_T_MAX - right_len) {
11338 PyErr_SetString(PyExc_OverflowError,
11339 "strings are too large to concat");
11340 goto error;
11341 }
11342 new_len = left_len + right_len;
11343
11344 if (unicode_modifiable(left)
11345 && PyUnicode_CheckExact(right)
11346 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011347 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11348 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011349 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011350 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011351 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11352 {
11353 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011354 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011355 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011356
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011357 /* copy 'right' into the newly allocated area of 'left' */
11358 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011359 }
Victor Stinner488fa492011-12-12 00:01:39 +010011360 else {
11361 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11362 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011363 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011364
Victor Stinner488fa492011-12-12 00:01:39 +010011365 /* Concat the two Unicode strings */
11366 res = PyUnicode_New(new_len, maxchar);
11367 if (res == NULL)
11368 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011369 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11370 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011371 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011372 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011373 }
11374 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011375 return;
11376
11377error:
Victor Stinner488fa492011-12-12 00:01:39 +010011378 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011379}
11380
11381void
11382PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11383{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011384 PyUnicode_Append(pleft, right);
11385 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011386}
11387
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011388/*
11389Wraps stringlib_parse_args_finds() and additionally ensures that the
11390first argument is a unicode object.
11391*/
11392
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011393static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011394parse_args_finds_unicode(const char * function_name, PyObject *args,
11395 PyObject **substring,
11396 Py_ssize_t *start, Py_ssize_t *end)
11397{
11398 if(stringlib_parse_args_finds(function_name, args, substring,
11399 start, end)) {
11400 if (ensure_unicode(*substring) < 0)
11401 return 0;
11402 return 1;
11403 }
11404 return 0;
11405}
11406
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011407PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011408 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011410Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011411string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011412interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413
11414static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011415unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011417 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011418 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011419 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011421 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 void *buf1, *buf2;
11423 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011425 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011426 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428 kind1 = PyUnicode_KIND(self);
11429 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011430 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011431 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011432
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011433 len1 = PyUnicode_GET_LENGTH(self);
11434 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011435 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011436 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011437 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011438
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011439 buf1 = PyUnicode_DATA(self);
11440 buf2 = PyUnicode_DATA(substring);
11441 if (kind2 != kind1) {
11442 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011443 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011444 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011445 }
11446 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 case PyUnicode_1BYTE_KIND:
11448 iresult = ucs1lib_count(
11449 ((Py_UCS1*)buf1) + start, end - start,
11450 buf2, len2, PY_SSIZE_T_MAX
11451 );
11452 break;
11453 case PyUnicode_2BYTE_KIND:
11454 iresult = ucs2lib_count(
11455 ((Py_UCS2*)buf1) + start, end - start,
11456 buf2, len2, PY_SSIZE_T_MAX
11457 );
11458 break;
11459 case PyUnicode_4BYTE_KIND:
11460 iresult = ucs4lib_count(
11461 ((Py_UCS4*)buf1) + start, end - start,
11462 buf2, len2, PY_SSIZE_T_MAX
11463 );
11464 break;
11465 default:
11466 assert(0); iresult = 0;
11467 }
11468
11469 result = PyLong_FromSsize_t(iresult);
11470
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011471 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011472 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 return result;
11475}
11476
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011477PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011478 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011480Encode S using the codec registered for encoding. Default encoding\n\
11481is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011482handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011483a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11484'xmlcharrefreplace' as well as any other name registered with\n\
11485codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486
11487static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011488unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011490 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 char *encoding = NULL;
11492 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011493
Benjamin Peterson308d6372009-09-18 21:42:35 +000011494 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11495 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011497 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011498}
11499
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011500PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011501 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502\n\
11503Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011504If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505
11506static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011507unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011509 Py_ssize_t i, j, line_pos, src_len, incr;
11510 Py_UCS4 ch;
11511 PyObject *u;
11512 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011513 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011515 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011516 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517
Ezio Melotti745d54d2013-11-16 19:10:57 +020011518 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11519 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011520 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521
Antoine Pitrou22425222011-10-04 19:10:51 +020011522 if (PyUnicode_READY(self) == -1)
11523 return NULL;
11524
Thomas Wouters7e474022000-07-16 12:04:32 +000011525 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011526 src_len = PyUnicode_GET_LENGTH(self);
11527 i = j = line_pos = 0;
11528 kind = PyUnicode_KIND(self);
11529 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011530 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011531 for (; i < src_len; i++) {
11532 ch = PyUnicode_READ(kind, src_data, i);
11533 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011534 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011535 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011536 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011537 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011538 goto overflow;
11539 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011540 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011541 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011542 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011544 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011545 goto overflow;
11546 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011548 if (ch == '\n' || ch == '\r')
11549 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011551 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011552 if (!found)
11553 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011554
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011556 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557 if (!u)
11558 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011559 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560
Antoine Pitroue71d5742011-10-04 15:55:09 +020011561 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562
Antoine Pitroue71d5742011-10-04 15:55:09 +020011563 for (; i < src_len; i++) {
11564 ch = PyUnicode_READ(kind, src_data, i);
11565 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011566 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011567 incr = tabsize - (line_pos % tabsize);
11568 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011569 FILL(kind, dest_data, ' ', j, incr);
11570 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011571 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011572 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011573 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011574 line_pos++;
11575 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011576 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011577 if (ch == '\n' || ch == '\r')
11578 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011580 }
11581 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011582 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011583
Antoine Pitroue71d5742011-10-04 15:55:09 +020011584 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011585 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11586 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587}
11588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011589PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011590 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591\n\
11592Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011593such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594arguments start and end are interpreted as in slice notation.\n\
11595\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011596Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597
11598static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011599unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011601 /* initialize variables to prevent gcc warning */
11602 PyObject *substring = NULL;
11603 Py_ssize_t start = 0;
11604 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011605 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011607 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011610 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011611 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011613 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011614
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 if (result == -2)
11616 return NULL;
11617
Christian Heimes217cfd12007-12-02 14:31:20 +000011618 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619}
11620
11621static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011622unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011624 void *data;
11625 enum PyUnicode_Kind kind;
11626 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011627
11628 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11629 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011631 }
11632 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11633 PyErr_SetString(PyExc_IndexError, "string index out of range");
11634 return NULL;
11635 }
11636 kind = PyUnicode_KIND(self);
11637 data = PyUnicode_DATA(self);
11638 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011639 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640}
11641
Guido van Rossumc2504932007-09-18 19:42:40 +000011642/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011643 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011644static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011645unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646{
Guido van Rossumc2504932007-09-18 19:42:40 +000011647 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011648 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011649
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011650#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011651 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011652#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 if (_PyUnicode_HASH(self) != -1)
11654 return _PyUnicode_HASH(self);
11655 if (PyUnicode_READY(self) == -1)
11656 return -1;
11657 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011658 /*
11659 We make the hash of the empty string be 0, rather than using
11660 (prefix ^ suffix), since this slightly obfuscates the hash secret
11661 */
11662 if (len == 0) {
11663 _PyUnicode_HASH(self) = 0;
11664 return 0;
11665 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011666 x = _Py_HashBytes(PyUnicode_DATA(self),
11667 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011668 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011669 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670}
11671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011672PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011673 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011674\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011675Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676
11677static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011678unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011679{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011680 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011681 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011682 PyObject *substring = NULL;
11683 Py_ssize_t start = 0;
11684 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011685
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011686 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011689 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011691
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011692 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011693
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694 if (result == -2)
11695 return NULL;
11696
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697 if (result < 0) {
11698 PyErr_SetString(PyExc_ValueError, "substring not found");
11699 return NULL;
11700 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011701
Christian Heimes217cfd12007-12-02 14:31:20 +000011702 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703}
11704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011705PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011706 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011708Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011709at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710
11711static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011712unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714 Py_ssize_t i, length;
11715 int kind;
11716 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717 int cased;
11718
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719 if (PyUnicode_READY(self) == -1)
11720 return NULL;
11721 length = PyUnicode_GET_LENGTH(self);
11722 kind = PyUnicode_KIND(self);
11723 data = PyUnicode_DATA(self);
11724
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 if (length == 1)
11727 return PyBool_FromLong(
11728 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011730 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011731 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011732 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011733
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 for (i = 0; i < length; i++) {
11736 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011737
Benjamin Peterson29060642009-01-31 22:14:21 +000011738 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11739 return PyBool_FromLong(0);
11740 else if (!cased && Py_UNICODE_ISLOWER(ch))
11741 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011743 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744}
11745
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011746PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011747 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011748\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011749Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011750at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751
11752static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011753unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011755 Py_ssize_t i, length;
11756 int kind;
11757 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758 int cased;
11759
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011760 if (PyUnicode_READY(self) == -1)
11761 return NULL;
11762 length = PyUnicode_GET_LENGTH(self);
11763 kind = PyUnicode_KIND(self);
11764 data = PyUnicode_DATA(self);
11765
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767 if (length == 1)
11768 return PyBool_FromLong(
11769 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011771 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011772 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011773 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011774
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 for (i = 0; i < length; i++) {
11777 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011778
Benjamin Peterson29060642009-01-31 22:14:21 +000011779 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11780 return PyBool_FromLong(0);
11781 else if (!cased && Py_UNICODE_ISUPPER(ch))
11782 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011784 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785}
11786
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011787PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011788 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011790Return True if S is a titlecased string and there is at least one\n\
11791character in S, i.e. upper- and titlecase characters may only\n\
11792follow uncased characters and lowercase characters only cased ones.\n\
11793Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794
11795static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011796unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011797{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 Py_ssize_t i, length;
11799 int kind;
11800 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801 int cased, previous_is_cased;
11802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803 if (PyUnicode_READY(self) == -1)
11804 return NULL;
11805 length = PyUnicode_GET_LENGTH(self);
11806 kind = PyUnicode_KIND(self);
11807 data = PyUnicode_DATA(self);
11808
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 if (length == 1) {
11811 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11812 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11813 (Py_UNICODE_ISUPPER(ch) != 0));
11814 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011815
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011816 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011817 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011818 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011819
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820 cased = 0;
11821 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011822 for (i = 0; i < length; i++) {
11823 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011824
Benjamin Peterson29060642009-01-31 22:14:21 +000011825 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11826 if (previous_is_cased)
11827 return PyBool_FromLong(0);
11828 previous_is_cased = 1;
11829 cased = 1;
11830 }
11831 else if (Py_UNICODE_ISLOWER(ch)) {
11832 if (!previous_is_cased)
11833 return PyBool_FromLong(0);
11834 previous_is_cased = 1;
11835 cased = 1;
11836 }
11837 else
11838 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011839 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011840 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011841}
11842
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011843PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011844 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011845\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011846Return True if all characters in S are whitespace\n\
11847and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011848
11849static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011850unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 Py_ssize_t i, length;
11853 int kind;
11854 void *data;
11855
11856 if (PyUnicode_READY(self) == -1)
11857 return NULL;
11858 length = PyUnicode_GET_LENGTH(self);
11859 kind = PyUnicode_KIND(self);
11860 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 if (length == 1)
11864 return PyBool_FromLong(
11865 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011867 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011868 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011869 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011870
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011871 for (i = 0; i < length; i++) {
11872 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011873 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011874 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011876 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877}
11878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011879PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011880 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011881\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011882Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011883and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011884
11885static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011886unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011887{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 Py_ssize_t i, length;
11889 int kind;
11890 void *data;
11891
11892 if (PyUnicode_READY(self) == -1)
11893 return NULL;
11894 length = PyUnicode_GET_LENGTH(self);
11895 kind = PyUnicode_KIND(self);
11896 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011897
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011898 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011899 if (length == 1)
11900 return PyBool_FromLong(
11901 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011902
11903 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011904 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011905 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011906
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 for (i = 0; i < length; i++) {
11908 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011909 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011910 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011911 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011912}
11913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011914PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011915 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011916\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011917Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011918and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011919
11920static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011921unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011922{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011923 int kind;
11924 void *data;
11925 Py_ssize_t len, i;
11926
11927 if (PyUnicode_READY(self) == -1)
11928 return NULL;
11929
11930 kind = PyUnicode_KIND(self);
11931 data = PyUnicode_DATA(self);
11932 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011933
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011934 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011935 if (len == 1) {
11936 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11937 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11938 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011939
11940 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011941 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011942 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011944 for (i = 0; i < len; i++) {
11945 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011946 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011947 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011948 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011949 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011950}
11951
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011952PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011953 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011955Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011956False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011957
11958static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011959unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961 Py_ssize_t i, length;
11962 int kind;
11963 void *data;
11964
11965 if (PyUnicode_READY(self) == -1)
11966 return NULL;
11967 length = PyUnicode_GET_LENGTH(self);
11968 kind = PyUnicode_KIND(self);
11969 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011970
Guido van Rossumd57fd912000-03-10 22:53:23 +000011971 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 if (length == 1)
11973 return PyBool_FromLong(
11974 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011975
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011976 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011977 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011978 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 for (i = 0; i < length; i++) {
11981 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011982 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011984 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011985}
11986
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011987PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011988 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011989\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011990Return True if all characters in S are digits\n\
11991and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011992
11993static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011994unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 Py_ssize_t i, length;
11997 int kind;
11998 void *data;
11999
12000 if (PyUnicode_READY(self) == -1)
12001 return NULL;
12002 length = PyUnicode_GET_LENGTH(self);
12003 kind = PyUnicode_KIND(self);
12004 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012005
Guido van Rossumd57fd912000-03-10 22:53:23 +000012006 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007 if (length == 1) {
12008 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12009 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12010 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012011
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012012 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012013 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012014 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016 for (i = 0; i < length; i++) {
12017 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012018 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012019 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012020 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012021}
12022
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012023PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012024 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012025\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000012026Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012027False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012028
12029static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012030unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012031{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012032 Py_ssize_t i, length;
12033 int kind;
12034 void *data;
12035
12036 if (PyUnicode_READY(self) == -1)
12037 return NULL;
12038 length = PyUnicode_GET_LENGTH(self);
12039 kind = PyUnicode_KIND(self);
12040 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012041
Guido van Rossumd57fd912000-03-10 22:53:23 +000012042 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012043 if (length == 1)
12044 return PyBool_FromLong(
12045 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012047 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012048 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012049 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012050
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012051 for (i = 0; i < length; i++) {
12052 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012053 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012054 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012055 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056}
12057
Martin v. Löwis47383402007-08-15 07:32:56 +000012058int
12059PyUnicode_IsIdentifier(PyObject *self)
12060{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061 int kind;
12062 void *data;
12063 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012064 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012066 if (PyUnicode_READY(self) == -1) {
12067 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012068 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 }
12070
12071 /* Special case for empty strings */
12072 if (PyUnicode_GET_LENGTH(self) == 0)
12073 return 0;
12074 kind = PyUnicode_KIND(self);
12075 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012076
12077 /* PEP 3131 says that the first character must be in
12078 XID_Start and subsequent characters in XID_Continue,
12079 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012080 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012081 letters, digits, underscore). However, given the current
12082 definition of XID_Start and XID_Continue, it is sufficient
12083 to check just for these, except that _ must be allowed
12084 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012086 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012087 return 0;
12088
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012089 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012090 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012091 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012092 return 1;
12093}
12094
12095PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012096 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012097\n\
12098Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012099to the language definition.\n\
12100\n\
12101Use keyword.iskeyword() to test for reserved identifiers\n\
12102such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012103
12104static PyObject*
12105unicode_isidentifier(PyObject *self)
12106{
12107 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12108}
12109
Georg Brandl559e5d72008-06-11 18:37:52 +000012110PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012111 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012112\n\
12113Return True if all characters in S are considered\n\
12114printable in repr() or S is empty, False otherwise.");
12115
12116static PyObject*
12117unicode_isprintable(PyObject *self)
12118{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012119 Py_ssize_t i, length;
12120 int kind;
12121 void *data;
12122
12123 if (PyUnicode_READY(self) == -1)
12124 return NULL;
12125 length = PyUnicode_GET_LENGTH(self);
12126 kind = PyUnicode_KIND(self);
12127 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012128
12129 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012130 if (length == 1)
12131 return PyBool_FromLong(
12132 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012134 for (i = 0; i < length; i++) {
12135 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012136 Py_RETURN_FALSE;
12137 }
12138 }
12139 Py_RETURN_TRUE;
12140}
12141
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012142PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012143 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144\n\
12145Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012146iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147
12148static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012149unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012151 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152}
12153
Martin v. Löwis18e16552006-02-15 17:27:45 +000012154static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012155unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012157 if (PyUnicode_READY(self) == -1)
12158 return -1;
12159 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160}
12161
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012162PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012163 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012164\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012165Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012166done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012167
12168static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012169unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012171 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012172 Py_UCS4 fillchar = ' ';
12173
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012174 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175 return NULL;
12176
Benjamin Petersonbac79492012-01-14 13:34:47 -050012177 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012178 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
Victor Stinnerc4b49542011-12-11 22:44:26 +010012180 if (PyUnicode_GET_LENGTH(self) >= width)
12181 return unicode_result_unchanged(self);
12182
12183 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184}
12185
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012186PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012187 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012189Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190
12191static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012192unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012194 if (PyUnicode_READY(self) == -1)
12195 return NULL;
12196 if (PyUnicode_IS_ASCII(self))
12197 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012198 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199}
12200
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012201#define LEFTSTRIP 0
12202#define RIGHTSTRIP 1
12203#define BOTHSTRIP 2
12204
12205/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012206static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012207
12208#define STRIPNAME(i) (stripformat[i]+3)
12209
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012210/* externally visible for str.strip(unicode) */
12211PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012212_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012213{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 void *data;
12215 int kind;
12216 Py_ssize_t i, j, len;
12217 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012218 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012219
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012220 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12221 return NULL;
12222
12223 kind = PyUnicode_KIND(self);
12224 data = PyUnicode_DATA(self);
12225 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012226 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012227 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12228 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012229 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012230
Benjamin Peterson14339b62009-01-31 16:36:08 +000012231 i = 0;
12232 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012233 while (i < len) {
12234 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12235 if (!BLOOM(sepmask, ch))
12236 break;
12237 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12238 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012239 i++;
12240 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012241 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012242
Benjamin Peterson14339b62009-01-31 16:36:08 +000012243 j = len;
12244 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012245 j--;
12246 while (j >= i) {
12247 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12248 if (!BLOOM(sepmask, ch))
12249 break;
12250 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12251 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012252 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012253 }
12254
Benjamin Peterson29060642009-01-31 22:14:21 +000012255 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012256 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012257
Victor Stinner7931d9a2011-11-04 00:22:48 +010012258 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012259}
12260
12261PyObject*
12262PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12263{
12264 unsigned char *data;
12265 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012266 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012267
Victor Stinnerde636f32011-10-01 03:55:54 +020012268 if (PyUnicode_READY(self) == -1)
12269 return NULL;
12270
Victor Stinner684d5fd2012-05-03 02:32:34 +020012271 length = PyUnicode_GET_LENGTH(self);
12272 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012273
Victor Stinner684d5fd2012-05-03 02:32:34 +020012274 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012275 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012276
Victor Stinnerde636f32011-10-01 03:55:54 +020012277 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012278 PyErr_SetString(PyExc_IndexError, "string index out of range");
12279 return NULL;
12280 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012281 if (start >= length || end < start)
12282 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012283
Victor Stinner684d5fd2012-05-03 02:32:34 +020012284 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012285 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012286 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012287 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012288 }
12289 else {
12290 kind = PyUnicode_KIND(self);
12291 data = PyUnicode_1BYTE_DATA(self);
12292 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012293 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012294 length);
12295 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012297
12298static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012299do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012300{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012301 Py_ssize_t len, i, j;
12302
12303 if (PyUnicode_READY(self) == -1)
12304 return NULL;
12305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012307
Victor Stinnercc7af722013-04-09 22:39:24 +020012308 if (PyUnicode_IS_ASCII(self)) {
12309 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12310
12311 i = 0;
12312 if (striptype != RIGHTSTRIP) {
12313 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012314 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012315 if (!_Py_ascii_whitespace[ch])
12316 break;
12317 i++;
12318 }
12319 }
12320
12321 j = len;
12322 if (striptype != LEFTSTRIP) {
12323 j--;
12324 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012325 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012326 if (!_Py_ascii_whitespace[ch])
12327 break;
12328 j--;
12329 }
12330 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012331 }
12332 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012333 else {
12334 int kind = PyUnicode_KIND(self);
12335 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012336
Victor Stinnercc7af722013-04-09 22:39:24 +020012337 i = 0;
12338 if (striptype != RIGHTSTRIP) {
12339 while (i < len) {
12340 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12341 if (!Py_UNICODE_ISSPACE(ch))
12342 break;
12343 i++;
12344 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012345 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012346
12347 j = len;
12348 if (striptype != LEFTSTRIP) {
12349 j--;
12350 while (j >= i) {
12351 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12352 if (!Py_UNICODE_ISSPACE(ch))
12353 break;
12354 j--;
12355 }
12356 j++;
12357 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012358 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012359
Victor Stinner7931d9a2011-11-04 00:22:48 +010012360 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012361}
12362
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012363
12364static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012365do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012366{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012367 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012368
Serhiy Storchakac6792272013-10-19 21:03:34 +030012369 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012370 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012371
Benjamin Peterson14339b62009-01-31 16:36:08 +000012372 if (sep != NULL && sep != Py_None) {
12373 if (PyUnicode_Check(sep))
12374 return _PyUnicode_XStrip(self, striptype, sep);
12375 else {
12376 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012377 "%s arg must be None or str",
12378 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012379 return NULL;
12380 }
12381 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012382
Benjamin Peterson14339b62009-01-31 16:36:08 +000012383 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012384}
12385
12386
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012387PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012388 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012389\n\
12390Return a copy of the string S with leading and trailing\n\
12391whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012392If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012393
12394static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012395unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012396{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012397 if (PyTuple_GET_SIZE(args) == 0)
12398 return do_strip(self, BOTHSTRIP); /* Common case */
12399 else
12400 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012401}
12402
12403
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012404PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012405 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012406\n\
12407Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012408If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012409
12410static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012411unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012412{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012413 if (PyTuple_GET_SIZE(args) == 0)
12414 return do_strip(self, LEFTSTRIP); /* Common case */
12415 else
12416 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012417}
12418
12419
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012420PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012421 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012422\n\
12423Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012424If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012425
12426static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012427unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012428{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012429 if (PyTuple_GET_SIZE(args) == 0)
12430 return do_strip(self, RIGHTSTRIP); /* Common case */
12431 else
12432 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012433}
12434
12435
Guido van Rossumd57fd912000-03-10 22:53:23 +000012436static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012437unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012438{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012439 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012440 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012441
Serhiy Storchaka05997252013-01-26 12:14:02 +020012442 if (len < 1)
12443 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012444
Victor Stinnerc4b49542011-12-11 22:44:26 +010012445 /* no repeat, return original string */
12446 if (len == 1)
12447 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012448
Benjamin Petersonbac79492012-01-14 13:34:47 -050012449 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012450 return NULL;
12451
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012452 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012453 PyErr_SetString(PyExc_OverflowError,
12454 "repeated string is too long");
12455 return NULL;
12456 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012457 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012458
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012459 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460 if (!u)
12461 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012462 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012464 if (PyUnicode_GET_LENGTH(str) == 1) {
12465 const int kind = PyUnicode_KIND(str);
12466 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012467 if (kind == PyUnicode_1BYTE_KIND) {
12468 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012469 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012470 }
12471 else if (kind == PyUnicode_2BYTE_KIND) {
12472 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012473 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012474 ucs2[n] = fill_char;
12475 } else {
12476 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12477 assert(kind == PyUnicode_4BYTE_KIND);
12478 for (n = 0; n < len; ++n)
12479 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012480 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012481 }
12482 else {
12483 /* number of characters copied this far */
12484 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012485 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012487 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012488 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012489 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012490 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012491 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012492 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012493 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012494 }
12495
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012496 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012497 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498}
12499
Alexander Belopolsky40018472011-02-26 01:02:56 +000012500PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012501PyUnicode_Replace(PyObject *str,
12502 PyObject *substr,
12503 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012504 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012505{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012506 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12507 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012508 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012509 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510}
12511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012512PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012513 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012514\n\
12515Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012516old replaced by new. If the optional argument count is\n\
12517given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518
12519static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012520unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012522 PyObject *str1;
12523 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012524 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012526 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012528 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012529 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012530 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531}
12532
Alexander Belopolsky40018472011-02-26 01:02:56 +000012533static PyObject *
12534unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012536 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 Py_ssize_t isize;
12538 Py_ssize_t osize, squote, dquote, i, o;
12539 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012540 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012544 return NULL;
12545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 isize = PyUnicode_GET_LENGTH(unicode);
12547 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 /* Compute length of output, quote characters, and
12550 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012551 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552 max = 127;
12553 squote = dquote = 0;
12554 ikind = PyUnicode_KIND(unicode);
12555 for (i = 0; i < isize; i++) {
12556 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012557 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012558 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012559 case '\'': squote++; break;
12560 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012562 incr = 2;
12563 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564 default:
12565 /* Fast-path ASCII */
12566 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012567 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012569 ;
12570 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012573 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012575 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012576 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012577 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012579 if (osize > PY_SSIZE_T_MAX - incr) {
12580 PyErr_SetString(PyExc_OverflowError,
12581 "string is too long to generate repr");
12582 return NULL;
12583 }
12584 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 }
12586
12587 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012588 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012590 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012591 if (dquote)
12592 /* Both squote and dquote present. Use squote,
12593 and escape them */
12594 osize += squote;
12595 else
12596 quote = '"';
12597 }
Victor Stinner55c08782013-04-14 18:45:39 +020012598 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012599
12600 repr = PyUnicode_New(osize, max);
12601 if (repr == NULL)
12602 return NULL;
12603 okind = PyUnicode_KIND(repr);
12604 odata = PyUnicode_DATA(repr);
12605
12606 PyUnicode_WRITE(okind, odata, 0, quote);
12607 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012608 if (unchanged) {
12609 _PyUnicode_FastCopyCharacters(repr, 1,
12610 unicode, 0,
12611 isize);
12612 }
12613 else {
12614 for (i = 0, o = 1; i < isize; i++) {
12615 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012616
Victor Stinner55c08782013-04-14 18:45:39 +020012617 /* Escape quotes and backslashes */
12618 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012619 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012620 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012621 continue;
12622 }
12623
12624 /* Map special whitespace to '\t', \n', '\r' */
12625 if (ch == '\t') {
12626 PyUnicode_WRITE(okind, odata, o++, '\\');
12627 PyUnicode_WRITE(okind, odata, o++, 't');
12628 }
12629 else if (ch == '\n') {
12630 PyUnicode_WRITE(okind, odata, o++, '\\');
12631 PyUnicode_WRITE(okind, odata, o++, 'n');
12632 }
12633 else if (ch == '\r') {
12634 PyUnicode_WRITE(okind, odata, o++, '\\');
12635 PyUnicode_WRITE(okind, odata, o++, 'r');
12636 }
12637
12638 /* Map non-printable US ASCII to '\xhh' */
12639 else if (ch < ' ' || ch == 0x7F) {
12640 PyUnicode_WRITE(okind, odata, o++, '\\');
12641 PyUnicode_WRITE(okind, odata, o++, 'x');
12642 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12643 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12644 }
12645
12646 /* Copy ASCII characters as-is */
12647 else if (ch < 0x7F) {
12648 PyUnicode_WRITE(okind, odata, o++, ch);
12649 }
12650
12651 /* Non-ASCII characters */
12652 else {
12653 /* Map Unicode whitespace and control characters
12654 (categories Z* and C* except ASCII space)
12655 */
12656 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12657 PyUnicode_WRITE(okind, odata, o++, '\\');
12658 /* Map 8-bit characters to '\xhh' */
12659 if (ch <= 0xff) {
12660 PyUnicode_WRITE(okind, odata, o++, 'x');
12661 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12662 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12663 }
12664 /* Map 16-bit characters to '\uxxxx' */
12665 else if (ch <= 0xffff) {
12666 PyUnicode_WRITE(okind, odata, o++, 'u');
12667 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12668 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12669 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12670 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12671 }
12672 /* Map 21-bit characters to '\U00xxxxxx' */
12673 else {
12674 PyUnicode_WRITE(okind, odata, o++, 'U');
12675 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12676 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12677 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12678 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12679 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12680 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12681 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12682 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12683 }
12684 }
12685 /* Copy characters as-is */
12686 else {
12687 PyUnicode_WRITE(okind, odata, o++, ch);
12688 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012689 }
12690 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012691 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012693 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012694 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695}
12696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012697PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012698 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699\n\
12700Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012701such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702arguments start and end are interpreted as in slice notation.\n\
12703\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012704Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705
12706static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012707unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012709 /* initialize variables to prevent gcc warning */
12710 PyObject *substring = NULL;
12711 Py_ssize_t start = 0;
12712 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012713 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012715 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012716 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012717
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012718 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012719 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012720
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012721 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012722
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723 if (result == -2)
12724 return NULL;
12725
Christian Heimes217cfd12007-12-02 14:31:20 +000012726 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012727}
12728
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012729PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012730 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012732Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012733
12734static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012735unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012737 /* initialize variables to prevent gcc warning */
12738 PyObject *substring = NULL;
12739 Py_ssize_t start = 0;
12740 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012741 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012742
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012743 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012744 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012746 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012747 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012748
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012749 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012750
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012751 if (result == -2)
12752 return NULL;
12753
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754 if (result < 0) {
12755 PyErr_SetString(PyExc_ValueError, "substring not found");
12756 return NULL;
12757 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012758
Christian Heimes217cfd12007-12-02 14:31:20 +000012759 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012760}
12761
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012762PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012763 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012765Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012766done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767
12768static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012769unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012771 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012772 Py_UCS4 fillchar = ' ';
12773
Victor Stinnere9a29352011-10-01 02:14:59 +020012774 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012775 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012776
Benjamin Petersonbac79492012-01-14 13:34:47 -050012777 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778 return NULL;
12779
Victor Stinnerc4b49542011-12-11 22:44:26 +010012780 if (PyUnicode_GET_LENGTH(self) >= width)
12781 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782
Victor Stinnerc4b49542011-12-11 22:44:26 +010012783 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784}
12785
Alexander Belopolsky40018472011-02-26 01:02:56 +000012786PyObject *
12787PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012788{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012789 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012790 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012791
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012792 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793}
12794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012795PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012796 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797\n\
12798Return a list of the words in S, using sep as the\n\
12799delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012800splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012801whitespace string is a separator and empty strings are\n\
12802removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803
12804static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012805unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012807 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012808 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012809 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012811 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12812 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012813 return NULL;
12814
12815 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012816 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012817
12818 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012819 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012820
12821 PyErr_Format(PyExc_TypeError,
12822 "must be str or None, not %.100s",
12823 Py_TYPE(substring)->tp_name);
12824 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825}
12826
Thomas Wouters477c8d52006-05-27 19:21:47 +000012827PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012828PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012829{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012830 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012831 int kind1, kind2;
12832 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012833 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012834
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012835 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012836 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012837
Victor Stinner14f8f022011-10-05 20:58:25 +020012838 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012839 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012840 len1 = PyUnicode_GET_LENGTH(str_obj);
12841 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012842 if (kind1 < kind2 || len1 < len2) {
12843 _Py_INCREF_UNICODE_EMPTY();
12844 if (!unicode_empty)
12845 out = NULL;
12846 else {
12847 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12848 Py_DECREF(unicode_empty);
12849 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012850 return out;
12851 }
12852 buf1 = PyUnicode_DATA(str_obj);
12853 buf2 = PyUnicode_DATA(sep_obj);
12854 if (kind2 != kind1) {
12855 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12856 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012857 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012858 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012859
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012860 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012861 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012862 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12863 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12864 else
12865 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012866 break;
12867 case PyUnicode_2BYTE_KIND:
12868 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12869 break;
12870 case PyUnicode_4BYTE_KIND:
12871 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12872 break;
12873 default:
12874 assert(0);
12875 out = 0;
12876 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012877
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012878 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012879 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012880
12881 return out;
12882}
12883
12884
12885PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012886PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012887{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012888 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012889 int kind1, kind2;
12890 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012891 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012892
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012893 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012894 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012895
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012896 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012897 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012898 len1 = PyUnicode_GET_LENGTH(str_obj);
12899 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012900 if (kind1 < kind2 || len1 < len2) {
12901 _Py_INCREF_UNICODE_EMPTY();
12902 if (!unicode_empty)
12903 out = NULL;
12904 else {
12905 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12906 Py_DECREF(unicode_empty);
12907 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012908 return out;
12909 }
12910 buf1 = PyUnicode_DATA(str_obj);
12911 buf2 = PyUnicode_DATA(sep_obj);
12912 if (kind2 != kind1) {
12913 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12914 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012915 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012916 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012917
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012918 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012919 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012920 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12921 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12922 else
12923 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012924 break;
12925 case PyUnicode_2BYTE_KIND:
12926 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12927 break;
12928 case PyUnicode_4BYTE_KIND:
12929 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12930 break;
12931 default:
12932 assert(0);
12933 out = 0;
12934 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012935
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012936 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012937 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012938
12939 return out;
12940}
12941
12942PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012943 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012944\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012945Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012946the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012947found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012948
12949static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012950unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012951{
Victor Stinner9310abb2011-10-05 00:59:23 +020012952 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012953}
12954
12955PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012956 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012957\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012958Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012959the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012960separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012961
12962static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012963unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012964{
Victor Stinner9310abb2011-10-05 00:59:23 +020012965 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012966}
12967
Alexander Belopolsky40018472011-02-26 01:02:56 +000012968PyObject *
12969PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012970{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012971 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012972 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012973
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012974 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012975}
12976
12977PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012978 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012979\n\
12980Return a list of the words in S, using sep as the\n\
12981delimiter string, starting at the end of the string and\n\
12982working to the front. If maxsplit is given, at most maxsplit\n\
12983splits are done. If sep is not specified, any whitespace string\n\
12984is a separator.");
12985
12986static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012987unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012988{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012989 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012990 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012991 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012992
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012993 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12994 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012995 return NULL;
12996
12997 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012998 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012999
13000 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020013001 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013002
13003 PyErr_Format(PyExc_TypeError,
13004 "must be str or None, not %.100s",
13005 Py_TYPE(substring)->tp_name);
13006 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013007}
13008
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013009PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013010 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013011\n\
13012Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000013013Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013014is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013015
13016static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013017unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013018{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013019 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000013020 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013021
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013022 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
13023 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013024 return NULL;
13025
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013026 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013027}
13028
13029static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013030PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013031{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013032 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013033}
13034
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013035PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013036 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013037\n\
13038Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013039and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013040
13041static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013042unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013043{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013044 if (PyUnicode_READY(self) == -1)
13045 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013046 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013047}
13048
Larry Hastings61272b72014-01-07 12:41:53 -080013049/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013050
Larry Hastings31826802013-10-19 00:09:25 -070013051@staticmethod
13052str.maketrans as unicode_maketrans
13053
13054 x: object
13055
13056 y: unicode=NULL
13057
13058 z: unicode=NULL
13059
13060 /
13061
13062Return a translation table usable for str.translate().
13063
13064If there is only one argument, it must be a dictionary mapping Unicode
13065ordinals (integers) or characters to Unicode ordinals, strings or None.
13066Character keys will be then converted to ordinals.
13067If there are two arguments, they must be strings of equal length, and
13068in the resulting dictionary, each character in x will be mapped to the
13069character at the same position in y. If there is a third argument, it
13070must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013071[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013072
Larry Hastings31826802013-10-19 00:09:25 -070013073static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013074unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013075/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013076{
Georg Brandlceee0772007-11-27 23:48:05 +000013077 PyObject *new = NULL, *key, *value;
13078 Py_ssize_t i = 0;
13079 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013080
Georg Brandlceee0772007-11-27 23:48:05 +000013081 new = PyDict_New();
13082 if (!new)
13083 return NULL;
13084 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013085 int x_kind, y_kind, z_kind;
13086 void *x_data, *y_data, *z_data;
13087
Georg Brandlceee0772007-11-27 23:48:05 +000013088 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013089 if (!PyUnicode_Check(x)) {
13090 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13091 "be a string if there is a second argument");
13092 goto err;
13093 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013094 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013095 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13096 "arguments must have equal length");
13097 goto err;
13098 }
13099 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013100 x_kind = PyUnicode_KIND(x);
13101 y_kind = PyUnicode_KIND(y);
13102 x_data = PyUnicode_DATA(x);
13103 y_data = PyUnicode_DATA(y);
13104 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13105 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013106 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013107 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013108 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013109 if (!value) {
13110 Py_DECREF(key);
13111 goto err;
13112 }
Georg Brandlceee0772007-11-27 23:48:05 +000013113 res = PyDict_SetItem(new, key, value);
13114 Py_DECREF(key);
13115 Py_DECREF(value);
13116 if (res < 0)
13117 goto err;
13118 }
13119 /* create entries for deleting chars in z */
13120 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013121 z_kind = PyUnicode_KIND(z);
13122 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013123 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013124 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013125 if (!key)
13126 goto err;
13127 res = PyDict_SetItem(new, key, Py_None);
13128 Py_DECREF(key);
13129 if (res < 0)
13130 goto err;
13131 }
13132 }
13133 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013134 int kind;
13135 void *data;
13136
Georg Brandlceee0772007-11-27 23:48:05 +000013137 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013138 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013139 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13140 "to maketrans it must be a dict");
13141 goto err;
13142 }
13143 /* copy entries into the new dict, converting string keys to int keys */
13144 while (PyDict_Next(x, &i, &key, &value)) {
13145 if (PyUnicode_Check(key)) {
13146 /* convert string keys to integer keys */
13147 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013148 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013149 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13150 "table must be of length 1");
13151 goto err;
13152 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013153 kind = PyUnicode_KIND(key);
13154 data = PyUnicode_DATA(key);
13155 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013156 if (!newkey)
13157 goto err;
13158 res = PyDict_SetItem(new, newkey, value);
13159 Py_DECREF(newkey);
13160 if (res < 0)
13161 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013162 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013163 /* just keep integer keys */
13164 if (PyDict_SetItem(new, key, value) < 0)
13165 goto err;
13166 } else {
13167 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13168 "be strings or integers");
13169 goto err;
13170 }
13171 }
13172 }
13173 return new;
13174 err:
13175 Py_DECREF(new);
13176 return NULL;
13177}
13178
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013179PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013180 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013181\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013182Return a copy of the string S in which each character has been mapped\n\
13183through the given translation table. The table must implement\n\
13184lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13185mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13186this operation raises LookupError, the character is left untouched.\n\
13187Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188
13189static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013190unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013192 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193}
13194
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013195PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013196 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013198Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199
13200static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013201unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013202{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013203 if (PyUnicode_READY(self) == -1)
13204 return NULL;
13205 if (PyUnicode_IS_ASCII(self))
13206 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013207 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208}
13209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013210PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013211 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013213Pad a numeric string S with zeros on the left, to fill a field\n\
13214of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215
13216static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013217unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013219 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013220 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013221 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013222 int kind;
13223 void *data;
13224 Py_UCS4 chr;
13225
Martin v. Löwis18e16552006-02-15 17:27:45 +000013226 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227 return NULL;
13228
Benjamin Petersonbac79492012-01-14 13:34:47 -050013229 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013230 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231
Victor Stinnerc4b49542011-12-11 22:44:26 +010013232 if (PyUnicode_GET_LENGTH(self) >= width)
13233 return unicode_result_unchanged(self);
13234
13235 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013236
13237 u = pad(self, fill, 0, '0');
13238
Walter Dörwald068325e2002-04-15 13:36:47 +000013239 if (u == NULL)
13240 return NULL;
13241
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013242 kind = PyUnicode_KIND(u);
13243 data = PyUnicode_DATA(u);
13244 chr = PyUnicode_READ(kind, data, fill);
13245
13246 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013247 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013248 PyUnicode_WRITE(kind, data, 0, chr);
13249 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013250 }
13251
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013252 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013253 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013254}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013255
13256#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013257static PyObject *
13258unicode__decimal2ascii(PyObject *self)
13259{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013260 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013261}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013262#endif
13263
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013264PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013265 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013266\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013267Return True if S starts with the specified prefix, False otherwise.\n\
13268With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013269With optional end, stop comparing S at that position.\n\
13270prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013271
13272static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013273unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013274 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013275{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013276 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013277 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013278 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013279 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013280 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013281
Jesus Ceaac451502011-04-20 17:09:23 +020013282 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013283 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013284 if (PyTuple_Check(subobj)) {
13285 Py_ssize_t i;
13286 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013287 substring = PyTuple_GET_ITEM(subobj, i);
13288 if (!PyUnicode_Check(substring)) {
13289 PyErr_Format(PyExc_TypeError,
13290 "tuple for startswith must only contain str, "
13291 "not %.100s",
13292 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013293 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013294 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013295 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013296 if (result == -1)
13297 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013298 if (result) {
13299 Py_RETURN_TRUE;
13300 }
13301 }
13302 /* nothing matched */
13303 Py_RETURN_FALSE;
13304 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013305 if (!PyUnicode_Check(subobj)) {
13306 PyErr_Format(PyExc_TypeError,
13307 "startswith first arg must be str or "
13308 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013309 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013310 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013311 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013312 if (result == -1)
13313 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013314 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013315}
13316
13317
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013318PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013319 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013320\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013321Return True if S ends with the specified suffix, False otherwise.\n\
13322With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013323With optional end, stop comparing S at that position.\n\
13324suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013325
13326static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013327unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013328 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013329{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013330 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013331 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013332 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013333 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013334 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013335
Jesus Ceaac451502011-04-20 17:09:23 +020013336 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013337 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013338 if (PyTuple_Check(subobj)) {
13339 Py_ssize_t i;
13340 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013341 substring = PyTuple_GET_ITEM(subobj, i);
13342 if (!PyUnicode_Check(substring)) {
13343 PyErr_Format(PyExc_TypeError,
13344 "tuple for endswith must only contain str, "
13345 "not %.100s",
13346 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013347 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013348 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013349 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013350 if (result == -1)
13351 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013352 if (result) {
13353 Py_RETURN_TRUE;
13354 }
13355 }
13356 Py_RETURN_FALSE;
13357 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013358 if (!PyUnicode_Check(subobj)) {
13359 PyErr_Format(PyExc_TypeError,
13360 "endswith first arg must be str or "
13361 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013362 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013363 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013364 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013365 if (result == -1)
13366 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013367 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013368}
13369
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013370static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013371_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013372{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013373 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13374 writer->data = PyUnicode_DATA(writer->buffer);
13375
13376 if (!writer->readonly) {
13377 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013378 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013379 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013380 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013381 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13382 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13383 writer->kind = PyUnicode_WCHAR_KIND;
13384 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13385
Victor Stinner8f674cc2013-04-17 23:02:17 +020013386 /* Copy-on-write mode: set buffer size to 0 so
13387 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13388 * next write. */
13389 writer->size = 0;
13390 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013391}
13392
Victor Stinnerd3f08822012-05-29 12:57:52 +020013393void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013394_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013395{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013396 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013397
13398 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013399 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013400
13401 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13402 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13403 writer->kind = PyUnicode_WCHAR_KIND;
13404 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013405}
13406
Victor Stinnerd3f08822012-05-29 12:57:52 +020013407int
13408_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13409 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013410{
13411 Py_ssize_t newlen;
13412 PyObject *newbuffer;
13413
Victor Stinner2740e462016-09-06 16:58:36 -070013414 assert(maxchar <= MAX_UNICODE);
13415
Victor Stinnerca9381e2015-09-22 00:58:32 +020013416 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013417 assert((maxchar > writer->maxchar && length >= 0)
13418 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013419
Victor Stinner202fdca2012-05-07 12:47:02 +020013420 if (length > PY_SSIZE_T_MAX - writer->pos) {
13421 PyErr_NoMemory();
13422 return -1;
13423 }
13424 newlen = writer->pos + length;
13425
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013426 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013427
Victor Stinnerd3f08822012-05-29 12:57:52 +020013428 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013429 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013430 if (writer->overallocate
13431 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13432 /* overallocate to limit the number of realloc() */
13433 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013434 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013435 if (newlen < writer->min_length)
13436 newlen = writer->min_length;
13437
Victor Stinnerd3f08822012-05-29 12:57:52 +020013438 writer->buffer = PyUnicode_New(newlen, maxchar);
13439 if (writer->buffer == NULL)
13440 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013441 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013442 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013443 if (writer->overallocate
13444 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13445 /* overallocate to limit the number of realloc() */
13446 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013447 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013448 if (newlen < writer->min_length)
13449 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013450
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013451 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013452 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013453 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013454 newbuffer = PyUnicode_New(newlen, maxchar);
13455 if (newbuffer == NULL)
13456 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013457 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13458 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013459 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013460 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013461 }
13462 else {
13463 newbuffer = resize_compact(writer->buffer, newlen);
13464 if (newbuffer == NULL)
13465 return -1;
13466 }
13467 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013468 }
13469 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013470 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013471 newbuffer = PyUnicode_New(writer->size, maxchar);
13472 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013473 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013474 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13475 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013476 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013477 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013478 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013479 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013480
13481#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013482}
13483
Victor Stinnerca9381e2015-09-22 00:58:32 +020013484int
13485_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13486 enum PyUnicode_Kind kind)
13487{
13488 Py_UCS4 maxchar;
13489
13490 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13491 assert(writer->kind < kind);
13492
13493 switch (kind)
13494 {
13495 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13496 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13497 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13498 default:
13499 assert(0 && "invalid kind");
13500 return -1;
13501 }
13502
13503 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13504}
13505
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013506static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013507_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013508{
Victor Stinner2740e462016-09-06 16:58:36 -070013509 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013510 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13511 return -1;
13512 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13513 writer->pos++;
13514 return 0;
13515}
13516
13517int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013518_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13519{
13520 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13521}
13522
13523int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013524_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13525{
13526 Py_UCS4 maxchar;
13527 Py_ssize_t len;
13528
13529 if (PyUnicode_READY(str) == -1)
13530 return -1;
13531 len = PyUnicode_GET_LENGTH(str);
13532 if (len == 0)
13533 return 0;
13534 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13535 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013536 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013537 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013538 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013539 Py_INCREF(str);
13540 writer->buffer = str;
13541 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013542 writer->pos += len;
13543 return 0;
13544 }
13545 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13546 return -1;
13547 }
13548 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13549 str, 0, len);
13550 writer->pos += len;
13551 return 0;
13552}
13553
Victor Stinnere215d962012-10-06 23:03:36 +020013554int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013555_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13556 Py_ssize_t start, Py_ssize_t end)
13557{
13558 Py_UCS4 maxchar;
13559 Py_ssize_t len;
13560
13561 if (PyUnicode_READY(str) == -1)
13562 return -1;
13563
13564 assert(0 <= start);
13565 assert(end <= PyUnicode_GET_LENGTH(str));
13566 assert(start <= end);
13567
13568 if (end == 0)
13569 return 0;
13570
13571 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13572 return _PyUnicodeWriter_WriteStr(writer, str);
13573
13574 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13575 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13576 else
13577 maxchar = writer->maxchar;
13578 len = end - start;
13579
13580 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13581 return -1;
13582
13583 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13584 str, start, len);
13585 writer->pos += len;
13586 return 0;
13587}
13588
13589int
Victor Stinner4a587072013-11-19 12:54:53 +010013590_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13591 const char *ascii, Py_ssize_t len)
13592{
13593 if (len == -1)
13594 len = strlen(ascii);
13595
13596 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13597
13598 if (writer->buffer == NULL && !writer->overallocate) {
13599 PyObject *str;
13600
13601 str = _PyUnicode_FromASCII(ascii, len);
13602 if (str == NULL)
13603 return -1;
13604
13605 writer->readonly = 1;
13606 writer->buffer = str;
13607 _PyUnicodeWriter_Update(writer);
13608 writer->pos += len;
13609 return 0;
13610 }
13611
13612 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13613 return -1;
13614
13615 switch (writer->kind)
13616 {
13617 case PyUnicode_1BYTE_KIND:
13618 {
13619 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13620 Py_UCS1 *data = writer->data;
13621
Christian Heimesf051e432016-09-13 20:22:02 +020013622 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013623 break;
13624 }
13625 case PyUnicode_2BYTE_KIND:
13626 {
13627 _PyUnicode_CONVERT_BYTES(
13628 Py_UCS1, Py_UCS2,
13629 ascii, ascii + len,
13630 (Py_UCS2 *)writer->data + writer->pos);
13631 break;
13632 }
13633 case PyUnicode_4BYTE_KIND:
13634 {
13635 _PyUnicode_CONVERT_BYTES(
13636 Py_UCS1, Py_UCS4,
13637 ascii, ascii + len,
13638 (Py_UCS4 *)writer->data + writer->pos);
13639 break;
13640 }
13641 default:
13642 assert(0);
13643 }
13644
13645 writer->pos += len;
13646 return 0;
13647}
13648
13649int
13650_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13651 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013652{
13653 Py_UCS4 maxchar;
13654
13655 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13656 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13657 return -1;
13658 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13659 writer->pos += len;
13660 return 0;
13661}
13662
Victor Stinnerd3f08822012-05-29 12:57:52 +020013663PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013664_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013665{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013666 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013667
Victor Stinnerd3f08822012-05-29 12:57:52 +020013668 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013669 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013670 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013671 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013672
13673 str = writer->buffer;
13674 writer->buffer = NULL;
13675
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013676 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013677 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13678 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013679 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013680
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013681 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13682 PyObject *str2;
13683 str2 = resize_compact(str, writer->pos);
13684 if (str2 == NULL) {
13685 Py_DECREF(str);
13686 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013687 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013688 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013689 }
13690
Victor Stinner15a0bd32013-07-08 22:29:55 +020013691 assert(_PyUnicode_CheckConsistency(str, 1));
13692 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013693}
13694
Victor Stinnerd3f08822012-05-29 12:57:52 +020013695void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013696_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013697{
13698 Py_CLEAR(writer->buffer);
13699}
13700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013701#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013702
13703PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013704 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013705\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013706Return a formatted version of S, using substitutions from args and kwargs.\n\
13707The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013708
Eric Smith27bbca62010-11-04 17:06:58 +000013709PyDoc_STRVAR(format_map__doc__,
13710 "S.format_map(mapping) -> str\n\
13711\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013712Return a formatted version of S, using substitutions from mapping.\n\
13713The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013714
Eric Smith4a7d76d2008-05-30 18:10:19 +000013715static PyObject *
13716unicode__format__(PyObject* self, PyObject* args)
13717{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013718 PyObject *format_spec;
13719 _PyUnicodeWriter writer;
13720 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013721
13722 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13723 return NULL;
13724
Victor Stinnerd3f08822012-05-29 12:57:52 +020013725 if (PyUnicode_READY(self) == -1)
13726 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013727 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013728 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13729 self, format_spec, 0,
13730 PyUnicode_GET_LENGTH(format_spec));
13731 if (ret == -1) {
13732 _PyUnicodeWriter_Dealloc(&writer);
13733 return NULL;
13734 }
13735 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013736}
13737
Eric Smith8c663262007-08-25 02:26:07 +000013738PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013739 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013740\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013741Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013742
13743static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013744unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013745{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013746 Py_ssize_t size;
13747
13748 /* If it's a compact object, account for base structure +
13749 character data. */
13750 if (PyUnicode_IS_COMPACT_ASCII(v))
13751 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13752 else if (PyUnicode_IS_COMPACT(v))
13753 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013754 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013755 else {
13756 /* If it is a two-block object, account for base object, and
13757 for character block if present. */
13758 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013759 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013760 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013761 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013762 }
13763 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013764 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013765 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013766 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013767 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013768 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013769
13770 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013771}
13772
13773PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013774 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013775
13776static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013777unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013778{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013779 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013780 if (!copy)
13781 return NULL;
13782 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013783}
13784
Guido van Rossumd57fd912000-03-10 22:53:23 +000013785static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013786 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013787 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013788 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13789 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013790 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13791 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013792 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013793 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13794 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13795 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013796 {"expandtabs", (PyCFunction) unicode_expandtabs,
13797 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013798 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013799 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013800 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13801 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13802 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013803 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013804 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13805 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13806 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013807 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013808 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013809 {"splitlines", (PyCFunction) unicode_splitlines,
13810 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013811 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013812 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13813 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13814 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13815 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13816 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13817 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13818 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13819 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13820 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13821 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13822 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13823 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13824 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13825 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013826 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013827 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013828 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013829 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013830 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013831 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013832 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013833 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013834#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013835 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013836 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013837#endif
13838
Benjamin Peterson14339b62009-01-31 16:36:08 +000013839 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013840 {NULL, NULL}
13841};
13842
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013843static PyObject *
13844unicode_mod(PyObject *v, PyObject *w)
13845{
Brian Curtindfc80e32011-08-10 20:28:54 -050013846 if (!PyUnicode_Check(v))
13847 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013848 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013849}
13850
13851static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013852 0, /*nb_add*/
13853 0, /*nb_subtract*/
13854 0, /*nb_multiply*/
13855 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013856};
13857
Guido van Rossumd57fd912000-03-10 22:53:23 +000013858static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013859 (lenfunc) unicode_length, /* sq_length */
13860 PyUnicode_Concat, /* sq_concat */
13861 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13862 (ssizeargfunc) unicode_getitem, /* sq_item */
13863 0, /* sq_slice */
13864 0, /* sq_ass_item */
13865 0, /* sq_ass_slice */
13866 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013867};
13868
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013869static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013870unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013871{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013872 if (PyUnicode_READY(self) == -1)
13873 return NULL;
13874
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013875 if (PyIndex_Check(item)) {
13876 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013877 if (i == -1 && PyErr_Occurred())
13878 return NULL;
13879 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013880 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013881 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013882 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013883 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013884 PyObject *result;
13885 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013886 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013887 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013888
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013889 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013890 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013891 return NULL;
13892 }
13893
13894 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013895 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013896 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013897 slicelength == PyUnicode_GET_LENGTH(self)) {
13898 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013899 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013900 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013901 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013902 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013903 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013904 src_kind = PyUnicode_KIND(self);
13905 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013906 if (!PyUnicode_IS_ASCII(self)) {
13907 kind_limit = kind_maxchar_limit(src_kind);
13908 max_char = 0;
13909 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13910 ch = PyUnicode_READ(src_kind, src_data, cur);
13911 if (ch > max_char) {
13912 max_char = ch;
13913 if (max_char >= kind_limit)
13914 break;
13915 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013916 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013917 }
Victor Stinner55c99112011-10-13 01:17:06 +020013918 else
13919 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013920 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013921 if (result == NULL)
13922 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013923 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013924 dest_data = PyUnicode_DATA(result);
13925
13926 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013927 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13928 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013929 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013930 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013931 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013932 } else {
13933 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13934 return NULL;
13935 }
13936}
13937
13938static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013939 (lenfunc)unicode_length, /* mp_length */
13940 (binaryfunc)unicode_subscript, /* mp_subscript */
13941 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013942};
13943
Guido van Rossumd57fd912000-03-10 22:53:23 +000013944
Guido van Rossumd57fd912000-03-10 22:53:23 +000013945/* Helpers for PyUnicode_Format() */
13946
Victor Stinnera47082312012-10-04 02:19:54 +020013947struct unicode_formatter_t {
13948 PyObject *args;
13949 int args_owned;
13950 Py_ssize_t arglen, argidx;
13951 PyObject *dict;
13952
13953 enum PyUnicode_Kind fmtkind;
13954 Py_ssize_t fmtcnt, fmtpos;
13955 void *fmtdata;
13956 PyObject *fmtstr;
13957
13958 _PyUnicodeWriter writer;
13959};
13960
13961struct unicode_format_arg_t {
13962 Py_UCS4 ch;
13963 int flags;
13964 Py_ssize_t width;
13965 int prec;
13966 int sign;
13967};
13968
Guido van Rossumd57fd912000-03-10 22:53:23 +000013969static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013970unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013971{
Victor Stinnera47082312012-10-04 02:19:54 +020013972 Py_ssize_t argidx = ctx->argidx;
13973
13974 if (argidx < ctx->arglen) {
13975 ctx->argidx++;
13976 if (ctx->arglen < 0)
13977 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013978 else
Victor Stinnera47082312012-10-04 02:19:54 +020013979 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013980 }
13981 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013982 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013983 return NULL;
13984}
13985
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013986/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013987
Victor Stinnera47082312012-10-04 02:19:54 +020013988/* Format a float into the writer if the writer is not NULL, or into *p_output
13989 otherwise.
13990
13991 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013992static int
Victor Stinnera47082312012-10-04 02:19:54 +020013993formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13994 PyObject **p_output,
13995 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013996{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013997 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013998 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013999 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014000 int prec;
14001 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014002
Guido van Rossumd57fd912000-03-10 22:53:23 +000014003 x = PyFloat_AsDouble(v);
14004 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014005 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014006
Victor Stinnera47082312012-10-04 02:19:54 +020014007 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014008 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014009 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014010
Victor Stinnera47082312012-10-04 02:19:54 +020014011 if (arg->flags & F_ALT)
14012 dtoa_flags = Py_DTSF_ALT;
14013 else
14014 dtoa_flags = 0;
14015 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014016 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014017 return -1;
14018 len = strlen(p);
14019 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014020 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014021 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014022 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014023 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014024 }
14025 else
14026 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014027 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014028 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014029}
14030
Victor Stinnerd0880d52012-04-27 23:40:13 +020014031/* formatlong() emulates the format codes d, u, o, x and X, and
14032 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14033 * Python's regular ints.
14034 * Return value: a new PyUnicodeObject*, or NULL if error.
14035 * The output string is of the form
14036 * "-"? ("0x" | "0X")? digit+
14037 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14038 * set in flags. The case of hex digits will be correct,
14039 * There will be at least prec digits, zero-filled on the left if
14040 * necessary to get that many.
14041 * val object to be converted
14042 * flags bitmask of format flags; only F_ALT is looked at
14043 * prec minimum number of digits; 0-fill on left if needed
14044 * type a character in [duoxX]; u acts the same as d
14045 *
14046 * CAUTION: o, x and X conversions on regular ints can never
14047 * produce a '-' sign, but can for Python's unbounded ints.
14048 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014049PyObject *
14050_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014051{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014052 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014053 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014054 Py_ssize_t i;
14055 int sign; /* 1 if '-', else 0 */
14056 int len; /* number of characters */
14057 Py_ssize_t llen;
14058 int numdigits; /* len == numnondigits + numdigits */
14059 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014060
Victor Stinnerd0880d52012-04-27 23:40:13 +020014061 /* Avoid exceeding SSIZE_T_MAX */
14062 if (prec > INT_MAX-3) {
14063 PyErr_SetString(PyExc_OverflowError,
14064 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014065 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014066 }
14067
14068 assert(PyLong_Check(val));
14069
14070 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014071 default:
14072 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014073 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014074 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014075 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014076 /* int and int subclasses should print numerically when a numeric */
14077 /* format code is used (see issue18780) */
14078 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014079 break;
14080 case 'o':
14081 numnondigits = 2;
14082 result = PyNumber_ToBase(val, 8);
14083 break;
14084 case 'x':
14085 case 'X':
14086 numnondigits = 2;
14087 result = PyNumber_ToBase(val, 16);
14088 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014089 }
14090 if (!result)
14091 return NULL;
14092
14093 assert(unicode_modifiable(result));
14094 assert(PyUnicode_IS_READY(result));
14095 assert(PyUnicode_IS_ASCII(result));
14096
14097 /* To modify the string in-place, there can only be one reference. */
14098 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014099 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014100 PyErr_BadInternalCall();
14101 return NULL;
14102 }
14103 buf = PyUnicode_DATA(result);
14104 llen = PyUnicode_GET_LENGTH(result);
14105 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014106 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014107 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014108 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014109 return NULL;
14110 }
14111 len = (int)llen;
14112 sign = buf[0] == '-';
14113 numnondigits += sign;
14114 numdigits = len - numnondigits;
14115 assert(numdigits > 0);
14116
14117 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014118 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014119 (type == 'o' || type == 'x' || type == 'X'))) {
14120 assert(buf[sign] == '0');
14121 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14122 buf[sign+1] == 'o');
14123 numnondigits -= 2;
14124 buf += 2;
14125 len -= 2;
14126 if (sign)
14127 buf[0] = '-';
14128 assert(len == numnondigits + numdigits);
14129 assert(numdigits > 0);
14130 }
14131
14132 /* Fill with leading zeroes to meet minimum width. */
14133 if (prec > numdigits) {
14134 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14135 numnondigits + prec);
14136 char *b1;
14137 if (!r1) {
14138 Py_DECREF(result);
14139 return NULL;
14140 }
14141 b1 = PyBytes_AS_STRING(r1);
14142 for (i = 0; i < numnondigits; ++i)
14143 *b1++ = *buf++;
14144 for (i = 0; i < prec - numdigits; i++)
14145 *b1++ = '0';
14146 for (i = 0; i < numdigits; i++)
14147 *b1++ = *buf++;
14148 *b1 = '\0';
14149 Py_DECREF(result);
14150 result = r1;
14151 buf = PyBytes_AS_STRING(result);
14152 len = numnondigits + prec;
14153 }
14154
14155 /* Fix up case for hex conversions. */
14156 if (type == 'X') {
14157 /* Need to convert all lower case letters to upper case.
14158 and need to convert 0x to 0X (and -0x to -0X). */
14159 for (i = 0; i < len; i++)
14160 if (buf[i] >= 'a' && buf[i] <= 'x')
14161 buf[i] -= 'a'-'A';
14162 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014163 if (!PyUnicode_Check(result)
14164 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014165 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014166 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014167 Py_DECREF(result);
14168 result = unicode;
14169 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014170 else if (len != PyUnicode_GET_LENGTH(result)) {
14171 if (PyUnicode_Resize(&result, len) < 0)
14172 Py_CLEAR(result);
14173 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014174 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014175}
14176
Ethan Furmandf3ed242014-01-05 06:50:30 -080014177/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014178 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014179 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014180 * -1 and raise an exception on error */
14181static int
Victor Stinnera47082312012-10-04 02:19:54 +020014182mainformatlong(PyObject *v,
14183 struct unicode_format_arg_t *arg,
14184 PyObject **p_output,
14185 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014186{
14187 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014188 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014189
14190 if (!PyNumber_Check(v))
14191 goto wrongtype;
14192
Ethan Furman9ab74802014-03-21 06:38:46 -070014193 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014194 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014195 if (type == 'o' || type == 'x' || type == 'X') {
14196 iobj = PyNumber_Index(v);
14197 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014198 if (PyErr_ExceptionMatches(PyExc_TypeError))
14199 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014200 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014201 }
14202 }
14203 else {
14204 iobj = PyNumber_Long(v);
14205 if (iobj == NULL ) {
14206 if (PyErr_ExceptionMatches(PyExc_TypeError))
14207 goto wrongtype;
14208 return -1;
14209 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014210 }
14211 assert(PyLong_Check(iobj));
14212 }
14213 else {
14214 iobj = v;
14215 Py_INCREF(iobj);
14216 }
14217
14218 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014219 && arg->width == -1 && arg->prec == -1
14220 && !(arg->flags & (F_SIGN | F_BLANK))
14221 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014222 {
14223 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014224 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014225 int base;
14226
Victor Stinnera47082312012-10-04 02:19:54 +020014227 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014228 {
14229 default:
14230 assert(0 && "'type' not in [diuoxX]");
14231 case 'd':
14232 case 'i':
14233 case 'u':
14234 base = 10;
14235 break;
14236 case 'o':
14237 base = 8;
14238 break;
14239 case 'x':
14240 case 'X':
14241 base = 16;
14242 break;
14243 }
14244
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014245 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14246 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014247 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014248 }
14249 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014250 return 1;
14251 }
14252
Ethan Furmanb95b5612015-01-23 20:05:18 -080014253 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014254 Py_DECREF(iobj);
14255 if (res == NULL)
14256 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014257 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014258 return 0;
14259
14260wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014261 switch(type)
14262 {
14263 case 'o':
14264 case 'x':
14265 case 'X':
14266 PyErr_Format(PyExc_TypeError,
14267 "%%%c format: an integer is required, "
14268 "not %.200s",
14269 type, Py_TYPE(v)->tp_name);
14270 break;
14271 default:
14272 PyErr_Format(PyExc_TypeError,
14273 "%%%c format: a number is required, "
14274 "not %.200s",
14275 type, Py_TYPE(v)->tp_name);
14276 break;
14277 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014278 return -1;
14279}
14280
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014281static Py_UCS4
14282formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014283{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014284 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014285 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014286 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014287 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014288 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014289 goto onError;
14290 }
14291 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014292 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014293 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014294 /* make sure number is a type of integer */
14295 if (!PyLong_Check(v)) {
14296 iobj = PyNumber_Index(v);
14297 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014298 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014299 }
14300 v = iobj;
14301 Py_DECREF(iobj);
14302 }
14303 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014304 x = PyLong_AsLong(v);
14305 if (x == -1 && PyErr_Occurred())
14306 goto onError;
14307
Victor Stinner8faf8212011-12-08 22:14:11 +010014308 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014309 PyErr_SetString(PyExc_OverflowError,
14310 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014311 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014312 }
14313
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014314 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014315 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014316
Benjamin Peterson29060642009-01-31 22:14:21 +000014317 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014318 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014319 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014320 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014321}
14322
Victor Stinnera47082312012-10-04 02:19:54 +020014323/* Parse options of an argument: flags, width, precision.
14324 Handle also "%(name)" syntax.
14325
14326 Return 0 if the argument has been formatted into arg->str.
14327 Return 1 if the argument has been written into ctx->writer,
14328 Raise an exception and return -1 on error. */
14329static int
14330unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14331 struct unicode_format_arg_t *arg)
14332{
14333#define FORMAT_READ(ctx) \
14334 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14335
14336 PyObject *v;
14337
Victor Stinnera47082312012-10-04 02:19:54 +020014338 if (arg->ch == '(') {
14339 /* Get argument value from a dictionary. Example: "%(name)s". */
14340 Py_ssize_t keystart;
14341 Py_ssize_t keylen;
14342 PyObject *key;
14343 int pcount = 1;
14344
14345 if (ctx->dict == NULL) {
14346 PyErr_SetString(PyExc_TypeError,
14347 "format requires a mapping");
14348 return -1;
14349 }
14350 ++ctx->fmtpos;
14351 --ctx->fmtcnt;
14352 keystart = ctx->fmtpos;
14353 /* Skip over balanced parentheses */
14354 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14355 arg->ch = FORMAT_READ(ctx);
14356 if (arg->ch == ')')
14357 --pcount;
14358 else if (arg->ch == '(')
14359 ++pcount;
14360 ctx->fmtpos++;
14361 }
14362 keylen = ctx->fmtpos - keystart - 1;
14363 if (ctx->fmtcnt < 0 || pcount > 0) {
14364 PyErr_SetString(PyExc_ValueError,
14365 "incomplete format key");
14366 return -1;
14367 }
14368 key = PyUnicode_Substring(ctx->fmtstr,
14369 keystart, keystart + keylen);
14370 if (key == NULL)
14371 return -1;
14372 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014373 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014374 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014375 }
14376 ctx->args = PyObject_GetItem(ctx->dict, key);
14377 Py_DECREF(key);
14378 if (ctx->args == NULL)
14379 return -1;
14380 ctx->args_owned = 1;
14381 ctx->arglen = -1;
14382 ctx->argidx = -2;
14383 }
14384
14385 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014386 while (--ctx->fmtcnt >= 0) {
14387 arg->ch = FORMAT_READ(ctx);
14388 ctx->fmtpos++;
14389 switch (arg->ch) {
14390 case '-': arg->flags |= F_LJUST; continue;
14391 case '+': arg->flags |= F_SIGN; continue;
14392 case ' ': arg->flags |= F_BLANK; continue;
14393 case '#': arg->flags |= F_ALT; continue;
14394 case '0': arg->flags |= F_ZERO; continue;
14395 }
14396 break;
14397 }
14398
14399 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014400 if (arg->ch == '*') {
14401 v = unicode_format_getnextarg(ctx);
14402 if (v == NULL)
14403 return -1;
14404 if (!PyLong_Check(v)) {
14405 PyErr_SetString(PyExc_TypeError,
14406 "* wants int");
14407 return -1;
14408 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014409 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014410 if (arg->width == -1 && PyErr_Occurred())
14411 return -1;
14412 if (arg->width < 0) {
14413 arg->flags |= F_LJUST;
14414 arg->width = -arg->width;
14415 }
14416 if (--ctx->fmtcnt >= 0) {
14417 arg->ch = FORMAT_READ(ctx);
14418 ctx->fmtpos++;
14419 }
14420 }
14421 else if (arg->ch >= '0' && arg->ch <= '9') {
14422 arg->width = arg->ch - '0';
14423 while (--ctx->fmtcnt >= 0) {
14424 arg->ch = FORMAT_READ(ctx);
14425 ctx->fmtpos++;
14426 if (arg->ch < '0' || arg->ch > '9')
14427 break;
14428 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14429 mixing signed and unsigned comparison. Since arg->ch is between
14430 '0' and '9', casting to int is safe. */
14431 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14432 PyErr_SetString(PyExc_ValueError,
14433 "width too big");
14434 return -1;
14435 }
14436 arg->width = arg->width*10 + (arg->ch - '0');
14437 }
14438 }
14439
14440 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014441 if (arg->ch == '.') {
14442 arg->prec = 0;
14443 if (--ctx->fmtcnt >= 0) {
14444 arg->ch = FORMAT_READ(ctx);
14445 ctx->fmtpos++;
14446 }
14447 if (arg->ch == '*') {
14448 v = unicode_format_getnextarg(ctx);
14449 if (v == NULL)
14450 return -1;
14451 if (!PyLong_Check(v)) {
14452 PyErr_SetString(PyExc_TypeError,
14453 "* wants int");
14454 return -1;
14455 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014456 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014457 if (arg->prec == -1 && PyErr_Occurred())
14458 return -1;
14459 if (arg->prec < 0)
14460 arg->prec = 0;
14461 if (--ctx->fmtcnt >= 0) {
14462 arg->ch = FORMAT_READ(ctx);
14463 ctx->fmtpos++;
14464 }
14465 }
14466 else if (arg->ch >= '0' && arg->ch <= '9') {
14467 arg->prec = arg->ch - '0';
14468 while (--ctx->fmtcnt >= 0) {
14469 arg->ch = FORMAT_READ(ctx);
14470 ctx->fmtpos++;
14471 if (arg->ch < '0' || arg->ch > '9')
14472 break;
14473 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14474 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014475 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014476 return -1;
14477 }
14478 arg->prec = arg->prec*10 + (arg->ch - '0');
14479 }
14480 }
14481 }
14482
14483 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14484 if (ctx->fmtcnt >= 0) {
14485 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14486 if (--ctx->fmtcnt >= 0) {
14487 arg->ch = FORMAT_READ(ctx);
14488 ctx->fmtpos++;
14489 }
14490 }
14491 }
14492 if (ctx->fmtcnt < 0) {
14493 PyErr_SetString(PyExc_ValueError,
14494 "incomplete format");
14495 return -1;
14496 }
14497 return 0;
14498
14499#undef FORMAT_READ
14500}
14501
14502/* Format one argument. Supported conversion specifiers:
14503
14504 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014505 - "i", "d", "u": int or float
14506 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014507 - "e", "E", "f", "F", "g", "G": float
14508 - "c": int or str (1 character)
14509
Victor Stinner8dbd4212012-12-04 09:30:24 +010014510 When possible, the output is written directly into the Unicode writer
14511 (ctx->writer). A string is created when padding is required.
14512
Victor Stinnera47082312012-10-04 02:19:54 +020014513 Return 0 if the argument has been formatted into *p_str,
14514 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014515 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014516static int
14517unicode_format_arg_format(struct unicode_formatter_t *ctx,
14518 struct unicode_format_arg_t *arg,
14519 PyObject **p_str)
14520{
14521 PyObject *v;
14522 _PyUnicodeWriter *writer = &ctx->writer;
14523
14524 if (ctx->fmtcnt == 0)
14525 ctx->writer.overallocate = 0;
14526
14527 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014528 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014529 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014530 return 1;
14531 }
14532
14533 v = unicode_format_getnextarg(ctx);
14534 if (v == NULL)
14535 return -1;
14536
Victor Stinnera47082312012-10-04 02:19:54 +020014537
14538 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014539 case 's':
14540 case 'r':
14541 case 'a':
14542 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14543 /* Fast path */
14544 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14545 return -1;
14546 return 1;
14547 }
14548
14549 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14550 *p_str = v;
14551 Py_INCREF(*p_str);
14552 }
14553 else {
14554 if (arg->ch == 's')
14555 *p_str = PyObject_Str(v);
14556 else if (arg->ch == 'r')
14557 *p_str = PyObject_Repr(v);
14558 else
14559 *p_str = PyObject_ASCII(v);
14560 }
14561 break;
14562
14563 case 'i':
14564 case 'd':
14565 case 'u':
14566 case 'o':
14567 case 'x':
14568 case 'X':
14569 {
14570 int ret = mainformatlong(v, arg, p_str, writer);
14571 if (ret != 0)
14572 return ret;
14573 arg->sign = 1;
14574 break;
14575 }
14576
14577 case 'e':
14578 case 'E':
14579 case 'f':
14580 case 'F':
14581 case 'g':
14582 case 'G':
14583 if (arg->width == -1 && arg->prec == -1
14584 && !(arg->flags & (F_SIGN | F_BLANK)))
14585 {
14586 /* Fast path */
14587 if (formatfloat(v, arg, NULL, writer) == -1)
14588 return -1;
14589 return 1;
14590 }
14591
14592 arg->sign = 1;
14593 if (formatfloat(v, arg, p_str, NULL) == -1)
14594 return -1;
14595 break;
14596
14597 case 'c':
14598 {
14599 Py_UCS4 ch = formatchar(v);
14600 if (ch == (Py_UCS4) -1)
14601 return -1;
14602 if (arg->width == -1 && arg->prec == -1) {
14603 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014604 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014605 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014606 return 1;
14607 }
14608 *p_str = PyUnicode_FromOrdinal(ch);
14609 break;
14610 }
14611
14612 default:
14613 PyErr_Format(PyExc_ValueError,
14614 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014615 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014616 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14617 (int)arg->ch,
14618 ctx->fmtpos - 1);
14619 return -1;
14620 }
14621 if (*p_str == NULL)
14622 return -1;
14623 assert (PyUnicode_Check(*p_str));
14624 return 0;
14625}
14626
14627static int
14628unicode_format_arg_output(struct unicode_formatter_t *ctx,
14629 struct unicode_format_arg_t *arg,
14630 PyObject *str)
14631{
14632 Py_ssize_t len;
14633 enum PyUnicode_Kind kind;
14634 void *pbuf;
14635 Py_ssize_t pindex;
14636 Py_UCS4 signchar;
14637 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014638 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014639 Py_ssize_t sublen;
14640 _PyUnicodeWriter *writer = &ctx->writer;
14641 Py_UCS4 fill;
14642
14643 fill = ' ';
14644 if (arg->sign && arg->flags & F_ZERO)
14645 fill = '0';
14646
14647 if (PyUnicode_READY(str) == -1)
14648 return -1;
14649
14650 len = PyUnicode_GET_LENGTH(str);
14651 if ((arg->width == -1 || arg->width <= len)
14652 && (arg->prec == -1 || arg->prec >= len)
14653 && !(arg->flags & (F_SIGN | F_BLANK)))
14654 {
14655 /* Fast path */
14656 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14657 return -1;
14658 return 0;
14659 }
14660
14661 /* Truncate the string for "s", "r" and "a" formats
14662 if the precision is set */
14663 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14664 if (arg->prec >= 0 && len > arg->prec)
14665 len = arg->prec;
14666 }
14667
14668 /* Adjust sign and width */
14669 kind = PyUnicode_KIND(str);
14670 pbuf = PyUnicode_DATA(str);
14671 pindex = 0;
14672 signchar = '\0';
14673 if (arg->sign) {
14674 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14675 if (ch == '-' || ch == '+') {
14676 signchar = ch;
14677 len--;
14678 pindex++;
14679 }
14680 else if (arg->flags & F_SIGN)
14681 signchar = '+';
14682 else if (arg->flags & F_BLANK)
14683 signchar = ' ';
14684 else
14685 arg->sign = 0;
14686 }
14687 if (arg->width < len)
14688 arg->width = len;
14689
14690 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014691 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014692 if (!(arg->flags & F_LJUST)) {
14693 if (arg->sign) {
14694 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014695 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014696 }
14697 else {
14698 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014699 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014700 }
14701 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014702 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14703 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014704 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014705 }
14706
Victor Stinnera47082312012-10-04 02:19:54 +020014707 buflen = arg->width;
14708 if (arg->sign && len == arg->width)
14709 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014710 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014711 return -1;
14712
14713 /* Write the sign if needed */
14714 if (arg->sign) {
14715 if (fill != ' ') {
14716 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14717 writer->pos += 1;
14718 }
14719 if (arg->width > len)
14720 arg->width--;
14721 }
14722
14723 /* Write the numeric prefix for "x", "X" and "o" formats
14724 if the alternate form is used.
14725 For example, write "0x" for the "%#x" format. */
14726 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14727 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14728 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14729 if (fill != ' ') {
14730 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14731 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14732 writer->pos += 2;
14733 pindex += 2;
14734 }
14735 arg->width -= 2;
14736 if (arg->width < 0)
14737 arg->width = 0;
14738 len -= 2;
14739 }
14740
14741 /* Pad left with the fill character if needed */
14742 if (arg->width > len && !(arg->flags & F_LJUST)) {
14743 sublen = arg->width - len;
14744 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14745 writer->pos += sublen;
14746 arg->width = len;
14747 }
14748
14749 /* If padding with spaces: write sign if needed and/or numeric prefix if
14750 the alternate form is used */
14751 if (fill == ' ') {
14752 if (arg->sign) {
14753 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14754 writer->pos += 1;
14755 }
14756 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14757 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14758 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14759 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14760 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14761 writer->pos += 2;
14762 pindex += 2;
14763 }
14764 }
14765
14766 /* Write characters */
14767 if (len) {
14768 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14769 str, pindex, len);
14770 writer->pos += len;
14771 }
14772
14773 /* Pad right with the fill character if needed */
14774 if (arg->width > len) {
14775 sublen = arg->width - len;
14776 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14777 writer->pos += sublen;
14778 }
14779 return 0;
14780}
14781
14782/* Helper of PyUnicode_Format(): format one arg.
14783 Return 0 on success, raise an exception and return -1 on error. */
14784static int
14785unicode_format_arg(struct unicode_formatter_t *ctx)
14786{
14787 struct unicode_format_arg_t arg;
14788 PyObject *str;
14789 int ret;
14790
Victor Stinner8dbd4212012-12-04 09:30:24 +010014791 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14792 arg.flags = 0;
14793 arg.width = -1;
14794 arg.prec = -1;
14795 arg.sign = 0;
14796 str = NULL;
14797
Victor Stinnera47082312012-10-04 02:19:54 +020014798 ret = unicode_format_arg_parse(ctx, &arg);
14799 if (ret == -1)
14800 return -1;
14801
14802 ret = unicode_format_arg_format(ctx, &arg, &str);
14803 if (ret == -1)
14804 return -1;
14805
14806 if (ret != 1) {
14807 ret = unicode_format_arg_output(ctx, &arg, str);
14808 Py_DECREF(str);
14809 if (ret == -1)
14810 return -1;
14811 }
14812
14813 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14814 PyErr_SetString(PyExc_TypeError,
14815 "not all arguments converted during string formatting");
14816 return -1;
14817 }
14818 return 0;
14819}
14820
Alexander Belopolsky40018472011-02-26 01:02:56 +000014821PyObject *
14822PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014823{
Victor Stinnera47082312012-10-04 02:19:54 +020014824 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014825
Guido van Rossumd57fd912000-03-10 22:53:23 +000014826 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014827 PyErr_BadInternalCall();
14828 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014829 }
Victor Stinnera47082312012-10-04 02:19:54 +020014830
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014831 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014832 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014833
14834 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014835 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14836 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14837 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14838 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014839
Victor Stinner8f674cc2013-04-17 23:02:17 +020014840 _PyUnicodeWriter_Init(&ctx.writer);
14841 ctx.writer.min_length = ctx.fmtcnt + 100;
14842 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014843
Guido van Rossumd57fd912000-03-10 22:53:23 +000014844 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014845 ctx.arglen = PyTuple_Size(args);
14846 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014847 }
14848 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014849 ctx.arglen = -1;
14850 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014851 }
Victor Stinnera47082312012-10-04 02:19:54 +020014852 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014853 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014854 ctx.dict = args;
14855 else
14856 ctx.dict = NULL;
14857 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014858
Victor Stinnera47082312012-10-04 02:19:54 +020014859 while (--ctx.fmtcnt >= 0) {
14860 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014861 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014862
14863 nonfmtpos = ctx.fmtpos++;
14864 while (ctx.fmtcnt >= 0 &&
14865 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14866 ctx.fmtpos++;
14867 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014868 }
Victor Stinnera47082312012-10-04 02:19:54 +020014869 if (ctx.fmtcnt < 0) {
14870 ctx.fmtpos--;
14871 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014872 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014873
Victor Stinnercfc4c132013-04-03 01:48:39 +020014874 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14875 nonfmtpos, ctx.fmtpos) < 0)
14876 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014877 }
14878 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014879 ctx.fmtpos++;
14880 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014881 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014882 }
14883 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014884
Victor Stinnera47082312012-10-04 02:19:54 +020014885 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014886 PyErr_SetString(PyExc_TypeError,
14887 "not all arguments converted during string formatting");
14888 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014889 }
14890
Victor Stinnera47082312012-10-04 02:19:54 +020014891 if (ctx.args_owned) {
14892 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014893 }
Victor Stinnera47082312012-10-04 02:19:54 +020014894 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014895
Benjamin Peterson29060642009-01-31 22:14:21 +000014896 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014897 _PyUnicodeWriter_Dealloc(&ctx.writer);
14898 if (ctx.args_owned) {
14899 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014900 }
14901 return NULL;
14902}
14903
Jeremy Hylton938ace62002-07-17 16:30:39 +000014904static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014905unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14906
Tim Peters6d6c1a32001-08-02 04:15:00 +000014907static PyObject *
14908unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14909{
Benjamin Peterson29060642009-01-31 22:14:21 +000014910 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014911 static char *kwlist[] = {"object", "encoding", "errors", 0};
14912 char *encoding = NULL;
14913 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014914
Benjamin Peterson14339b62009-01-31 16:36:08 +000014915 if (type != &PyUnicode_Type)
14916 return unicode_subtype_new(type, args, kwds);
14917 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014918 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014919 return NULL;
14920 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014921 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014922 if (encoding == NULL && errors == NULL)
14923 return PyObject_Str(x);
14924 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014925 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014926}
14927
Guido van Rossume023fe02001-08-30 03:12:59 +000014928static PyObject *
14929unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14930{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014931 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014932 Py_ssize_t length, char_size;
14933 int share_wstr, share_utf8;
14934 unsigned int kind;
14935 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014936
Benjamin Peterson14339b62009-01-31 16:36:08 +000014937 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014938
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014939 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014940 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014941 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014942 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014943 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014944 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014945 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014946 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014947
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014948 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014949 if (self == NULL) {
14950 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014951 return NULL;
14952 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014953 kind = PyUnicode_KIND(unicode);
14954 length = PyUnicode_GET_LENGTH(unicode);
14955
14956 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014957#ifdef Py_DEBUG
14958 _PyUnicode_HASH(self) = -1;
14959#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014960 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014961#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014962 _PyUnicode_STATE(self).interned = 0;
14963 _PyUnicode_STATE(self).kind = kind;
14964 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014965 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014966 _PyUnicode_STATE(self).ready = 1;
14967 _PyUnicode_WSTR(self) = NULL;
14968 _PyUnicode_UTF8_LENGTH(self) = 0;
14969 _PyUnicode_UTF8(self) = NULL;
14970 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014971 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014972
14973 share_utf8 = 0;
14974 share_wstr = 0;
14975 if (kind == PyUnicode_1BYTE_KIND) {
14976 char_size = 1;
14977 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14978 share_utf8 = 1;
14979 }
14980 else if (kind == PyUnicode_2BYTE_KIND) {
14981 char_size = 2;
14982 if (sizeof(wchar_t) == 2)
14983 share_wstr = 1;
14984 }
14985 else {
14986 assert(kind == PyUnicode_4BYTE_KIND);
14987 char_size = 4;
14988 if (sizeof(wchar_t) == 4)
14989 share_wstr = 1;
14990 }
14991
14992 /* Ensure we won't overflow the length. */
14993 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14994 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014995 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014996 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014997 data = PyObject_MALLOC((length + 1) * char_size);
14998 if (data == NULL) {
14999 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015000 goto onError;
15001 }
15002
Victor Stinnerc3c74152011-10-02 20:39:55 +020015003 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015004 if (share_utf8) {
15005 _PyUnicode_UTF8_LENGTH(self) = length;
15006 _PyUnicode_UTF8(self) = data;
15007 }
15008 if (share_wstr) {
15009 _PyUnicode_WSTR_LENGTH(self) = length;
15010 _PyUnicode_WSTR(self) = (wchar_t *)data;
15011 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015012
Christian Heimesf051e432016-09-13 20:22:02 +020015013 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015014 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015015 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015016#ifdef Py_DEBUG
15017 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15018#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015019 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015020 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015021
15022onError:
15023 Py_DECREF(unicode);
15024 Py_DECREF(self);
15025 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015026}
15027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015028PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015029"str(object='') -> str\n\
15030str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015031\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015032Create a new string object from the given object. If encoding or\n\
15033errors is specified, then the object must expose a data buffer\n\
15034that will be decoded using the given encoding and error handler.\n\
15035Otherwise, returns the result of object.__str__() (if defined)\n\
15036or repr(object).\n\
15037encoding defaults to sys.getdefaultencoding().\n\
15038errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015039
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015040static PyObject *unicode_iter(PyObject *seq);
15041
Guido van Rossumd57fd912000-03-10 22:53:23 +000015042PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015043 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015044 "str", /* tp_name */
15045 sizeof(PyUnicodeObject), /* tp_size */
15046 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015047 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015048 (destructor)unicode_dealloc, /* tp_dealloc */
15049 0, /* tp_print */
15050 0, /* tp_getattr */
15051 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015052 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015053 unicode_repr, /* tp_repr */
15054 &unicode_as_number, /* tp_as_number */
15055 &unicode_as_sequence, /* tp_as_sequence */
15056 &unicode_as_mapping, /* tp_as_mapping */
15057 (hashfunc) unicode_hash, /* tp_hash*/
15058 0, /* tp_call*/
15059 (reprfunc) unicode_str, /* tp_str */
15060 PyObject_GenericGetAttr, /* tp_getattro */
15061 0, /* tp_setattro */
15062 0, /* tp_as_buffer */
15063 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015064 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015065 unicode_doc, /* tp_doc */
15066 0, /* tp_traverse */
15067 0, /* tp_clear */
15068 PyUnicode_RichCompare, /* tp_richcompare */
15069 0, /* tp_weaklistoffset */
15070 unicode_iter, /* tp_iter */
15071 0, /* tp_iternext */
15072 unicode_methods, /* tp_methods */
15073 0, /* tp_members */
15074 0, /* tp_getset */
15075 &PyBaseObject_Type, /* tp_base */
15076 0, /* tp_dict */
15077 0, /* tp_descr_get */
15078 0, /* tp_descr_set */
15079 0, /* tp_dictoffset */
15080 0, /* tp_init */
15081 0, /* tp_alloc */
15082 unicode_new, /* tp_new */
15083 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015084};
15085
15086/* Initialize the Unicode implementation */
15087
Victor Stinner3a50e702011-10-18 21:21:00 +020015088int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015089{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015090 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015091 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015092 0x000A, /* LINE FEED */
15093 0x000D, /* CARRIAGE RETURN */
15094 0x001C, /* FILE SEPARATOR */
15095 0x001D, /* GROUP SEPARATOR */
15096 0x001E, /* RECORD SEPARATOR */
15097 0x0085, /* NEXT LINE */
15098 0x2028, /* LINE SEPARATOR */
15099 0x2029, /* PARAGRAPH SEPARATOR */
15100 };
15101
Fred Drakee4315f52000-05-09 19:53:39 +000015102 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015103 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015104 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015105 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015106 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015107
Guido van Rossumcacfc072002-05-24 19:01:59 +000015108 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015109 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015110
15111 /* initialize the linebreak bloom filter */
15112 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015113 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015114 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015115
Christian Heimes26532f72013-07-20 14:57:16 +020015116 if (PyType_Ready(&EncodingMapType) < 0)
15117 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015118
Benjamin Petersonc4311282012-10-30 23:21:10 -040015119 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15120 Py_FatalError("Can't initialize field name iterator type");
15121
15122 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15123 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015124
Victor Stinner3a50e702011-10-18 21:21:00 +020015125 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015126}
15127
15128/* Finalize the Unicode implementation */
15129
Christian Heimesa156e092008-02-16 07:38:31 +000015130int
15131PyUnicode_ClearFreeList(void)
15132{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015133 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015134}
15135
Guido van Rossumd57fd912000-03-10 22:53:23 +000015136void
Thomas Wouters78890102000-07-22 19:25:51 +000015137_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015138{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015139 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015140
Serhiy Storchaka05997252013-01-26 12:14:02 +020015141 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015142
Serhiy Storchaka05997252013-01-26 12:14:02 +020015143 for (i = 0; i < 256; i++)
15144 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015145 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015146 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015147}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015148
Walter Dörwald16807132007-05-25 13:52:07 +000015149void
15150PyUnicode_InternInPlace(PyObject **p)
15151{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015152 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015153 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015154#ifdef Py_DEBUG
15155 assert(s != NULL);
15156 assert(_PyUnicode_CHECK(s));
15157#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015158 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015159 return;
15160#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015161 /* If it's a subclass, we don't really know what putting
15162 it in the interned dict might do. */
15163 if (!PyUnicode_CheckExact(s))
15164 return;
15165 if (PyUnicode_CHECK_INTERNED(s))
15166 return;
15167 if (interned == NULL) {
15168 interned = PyDict_New();
15169 if (interned == NULL) {
15170 PyErr_Clear(); /* Don't leave an exception */
15171 return;
15172 }
15173 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015174 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015175 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015176 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015177 if (t == NULL) {
15178 PyErr_Clear();
15179 return;
15180 }
15181 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015182 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015183 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015184 return;
15185 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015186 /* The two references in interned are not counted by refcnt.
15187 The deallocator will take care of this */
15188 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015189 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015190}
15191
15192void
15193PyUnicode_InternImmortal(PyObject **p)
15194{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015195 PyUnicode_InternInPlace(p);
15196 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015197 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015198 Py_INCREF(*p);
15199 }
Walter Dörwald16807132007-05-25 13:52:07 +000015200}
15201
15202PyObject *
15203PyUnicode_InternFromString(const char *cp)
15204{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015205 PyObject *s = PyUnicode_FromString(cp);
15206 if (s == NULL)
15207 return NULL;
15208 PyUnicode_InternInPlace(&s);
15209 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015210}
15211
Alexander Belopolsky40018472011-02-26 01:02:56 +000015212void
15213_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015214{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015215 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015216 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015217 Py_ssize_t i, n;
15218 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015219
Benjamin Peterson14339b62009-01-31 16:36:08 +000015220 if (interned == NULL || !PyDict_Check(interned))
15221 return;
15222 keys = PyDict_Keys(interned);
15223 if (keys == NULL || !PyList_Check(keys)) {
15224 PyErr_Clear();
15225 return;
15226 }
Walter Dörwald16807132007-05-25 13:52:07 +000015227
Benjamin Peterson14339b62009-01-31 16:36:08 +000015228 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15229 detector, interned unicode strings are not forcibly deallocated;
15230 rather, we give them their stolen references back, and then clear
15231 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015232
Benjamin Peterson14339b62009-01-31 16:36:08 +000015233 n = PyList_GET_SIZE(keys);
15234 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015235 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015236 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015237 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015238 if (PyUnicode_READY(s) == -1) {
15239 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015240 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015241 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015242 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015243 case SSTATE_NOT_INTERNED:
15244 /* XXX Shouldn't happen */
15245 break;
15246 case SSTATE_INTERNED_IMMORTAL:
15247 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015248 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015249 break;
15250 case SSTATE_INTERNED_MORTAL:
15251 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015252 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015253 break;
15254 default:
15255 Py_FatalError("Inconsistent interned string state.");
15256 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015257 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015258 }
15259 fprintf(stderr, "total size of all interned strings: "
15260 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15261 "mortal/immortal\n", mortal_size, immortal_size);
15262 Py_DECREF(keys);
15263 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015264 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015265}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015266
15267
15268/********************* Unicode Iterator **************************/
15269
15270typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015271 PyObject_HEAD
15272 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015273 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015274} unicodeiterobject;
15275
15276static void
15277unicodeiter_dealloc(unicodeiterobject *it)
15278{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015279 _PyObject_GC_UNTRACK(it);
15280 Py_XDECREF(it->it_seq);
15281 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015282}
15283
15284static int
15285unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15286{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015287 Py_VISIT(it->it_seq);
15288 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015289}
15290
15291static PyObject *
15292unicodeiter_next(unicodeiterobject *it)
15293{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015294 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015295
Benjamin Peterson14339b62009-01-31 16:36:08 +000015296 assert(it != NULL);
15297 seq = it->it_seq;
15298 if (seq == NULL)
15299 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015300 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015302 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15303 int kind = PyUnicode_KIND(seq);
15304 void *data = PyUnicode_DATA(seq);
15305 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15306 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015307 if (item != NULL)
15308 ++it->it_index;
15309 return item;
15310 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015311
Benjamin Peterson14339b62009-01-31 16:36:08 +000015312 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015313 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015314 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015315}
15316
15317static PyObject *
15318unicodeiter_len(unicodeiterobject *it)
15319{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015320 Py_ssize_t len = 0;
15321 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015322 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015323 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015324}
15325
15326PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15327
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015328static PyObject *
15329unicodeiter_reduce(unicodeiterobject *it)
15330{
15331 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015332 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015333 it->it_seq, it->it_index);
15334 } else {
15335 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15336 if (u == NULL)
15337 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015338 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015339 }
15340}
15341
15342PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15343
15344static PyObject *
15345unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15346{
15347 Py_ssize_t index = PyLong_AsSsize_t(state);
15348 if (index == -1 && PyErr_Occurred())
15349 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015350 if (it->it_seq != NULL) {
15351 if (index < 0)
15352 index = 0;
15353 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15354 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15355 it->it_index = index;
15356 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015357 Py_RETURN_NONE;
15358}
15359
15360PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15361
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015362static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015363 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015364 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015365 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15366 reduce_doc},
15367 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15368 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015369 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015370};
15371
15372PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015373 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15374 "str_iterator", /* tp_name */
15375 sizeof(unicodeiterobject), /* tp_basicsize */
15376 0, /* tp_itemsize */
15377 /* methods */
15378 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15379 0, /* tp_print */
15380 0, /* tp_getattr */
15381 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015382 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015383 0, /* tp_repr */
15384 0, /* tp_as_number */
15385 0, /* tp_as_sequence */
15386 0, /* tp_as_mapping */
15387 0, /* tp_hash */
15388 0, /* tp_call */
15389 0, /* tp_str */
15390 PyObject_GenericGetAttr, /* tp_getattro */
15391 0, /* tp_setattro */
15392 0, /* tp_as_buffer */
15393 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15394 0, /* tp_doc */
15395 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15396 0, /* tp_clear */
15397 0, /* tp_richcompare */
15398 0, /* tp_weaklistoffset */
15399 PyObject_SelfIter, /* tp_iter */
15400 (iternextfunc)unicodeiter_next, /* tp_iternext */
15401 unicodeiter_methods, /* tp_methods */
15402 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015403};
15404
15405static PyObject *
15406unicode_iter(PyObject *seq)
15407{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015408 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015409
Benjamin Peterson14339b62009-01-31 16:36:08 +000015410 if (!PyUnicode_Check(seq)) {
15411 PyErr_BadInternalCall();
15412 return NULL;
15413 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015414 if (PyUnicode_READY(seq) == -1)
15415 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015416 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15417 if (it == NULL)
15418 return NULL;
15419 it->it_index = 0;
15420 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015421 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015422 _PyObject_GC_TRACK(it);
15423 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015424}
15425
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015426
15427size_t
15428Py_UNICODE_strlen(const Py_UNICODE *u)
15429{
15430 int res = 0;
15431 while(*u++)
15432 res++;
15433 return res;
15434}
15435
15436Py_UNICODE*
15437Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15438{
15439 Py_UNICODE *u = s1;
15440 while ((*u++ = *s2++));
15441 return s1;
15442}
15443
15444Py_UNICODE*
15445Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15446{
15447 Py_UNICODE *u = s1;
15448 while ((*u++ = *s2++))
15449 if (n-- == 0)
15450 break;
15451 return s1;
15452}
15453
15454Py_UNICODE*
15455Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15456{
15457 Py_UNICODE *u1 = s1;
15458 u1 += Py_UNICODE_strlen(u1);
15459 Py_UNICODE_strcpy(u1, s2);
15460 return s1;
15461}
15462
15463int
15464Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15465{
15466 while (*s1 && *s2 && *s1 == *s2)
15467 s1++, s2++;
15468 if (*s1 && *s2)
15469 return (*s1 < *s2) ? -1 : +1;
15470 if (*s1)
15471 return 1;
15472 if (*s2)
15473 return -1;
15474 return 0;
15475}
15476
15477int
15478Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15479{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015480 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015481 for (; n != 0; n--) {
15482 u1 = *s1;
15483 u2 = *s2;
15484 if (u1 != u2)
15485 return (u1 < u2) ? -1 : +1;
15486 if (u1 == '\0')
15487 return 0;
15488 s1++;
15489 s2++;
15490 }
15491 return 0;
15492}
15493
15494Py_UNICODE*
15495Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15496{
15497 const Py_UNICODE *p;
15498 for (p = s; *p; p++)
15499 if (*p == c)
15500 return (Py_UNICODE*)p;
15501 return NULL;
15502}
15503
15504Py_UNICODE*
15505Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15506{
15507 const Py_UNICODE *p;
15508 p = s + Py_UNICODE_strlen(s);
15509 while (p != s) {
15510 p--;
15511 if (*p == c)
15512 return (Py_UNICODE*)p;
15513 }
15514 return NULL;
15515}
Victor Stinner331ea922010-08-10 16:37:20 +000015516
Victor Stinner71133ff2010-09-01 23:43:53 +000015517Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015518PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015519{
Victor Stinner577db2c2011-10-11 22:12:48 +020015520 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015521 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015523 if (!PyUnicode_Check(unicode)) {
15524 PyErr_BadArgument();
15525 return NULL;
15526 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015527 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015528 if (u == NULL)
15529 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015530 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015531 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015532 PyErr_NoMemory();
15533 return NULL;
15534 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015535 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015536 size *= sizeof(Py_UNICODE);
15537 copy = PyMem_Malloc(size);
15538 if (copy == NULL) {
15539 PyErr_NoMemory();
15540 return NULL;
15541 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015542 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015543 return copy;
15544}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015545
Georg Brandl66c221e2010-10-14 07:04:07 +000015546/* A _string module, to export formatter_parser and formatter_field_name_split
15547 to the string.Formatter class implemented in Python. */
15548
15549static PyMethodDef _string_methods[] = {
15550 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15551 METH_O, PyDoc_STR("split the argument as a field name")},
15552 {"formatter_parser", (PyCFunction) formatter_parser,
15553 METH_O, PyDoc_STR("parse the argument as a format string")},
15554 {NULL, NULL}
15555};
15556
15557static struct PyModuleDef _string_module = {
15558 PyModuleDef_HEAD_INIT,
15559 "_string",
15560 PyDoc_STR("string helper module"),
15561 0,
15562 _string_methods,
15563 NULL,
15564 NULL,
15565 NULL,
15566 NULL
15567};
15568
15569PyMODINIT_FUNC
15570PyInit__string(void)
15571{
15572 return PyModule_Create(&_string_module);
15573}
15574
15575
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015576#ifdef __cplusplus
15577}
15578#endif