blob: 02aaf6eb53277047f837d3112c97867ba7afe44c [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070045#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000046
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000047#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000048#include <windows.h>
49#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000050
Larry Hastings61272b72014-01-07 12:41:53 -080051/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080052class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080053[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080054/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080055
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000056/* --- Globals ------------------------------------------------------------
57
Serhiy Storchaka05997252013-01-26 12:14:02 +020058NOTE: In the interpreter's initialization phase, some globals are currently
59 initialized dynamically as needed. In the process Unicode objects may
60 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061
62*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064
65#ifdef __cplusplus
66extern "C" {
67#endif
68
Victor Stinner8faf8212011-12-08 22:14:11 +010069/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
70#define MAX_UNICODE 0x10ffff
71
Victor Stinner910337b2011-10-03 03:20:16 +020072#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020073# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020074#else
75# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
76#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020077
Victor Stinnere90fe6a2011-10-01 16:48:13 +020078#define _PyUnicode_UTF8(op) \
79 (((PyCompactUnicodeObject*)(op))->utf8)
80#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020081 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020082 assert(PyUnicode_IS_READY(op)), \
83 PyUnicode_IS_COMPACT_ASCII(op) ? \
84 ((char*)((PyASCIIObject*)(op) + 1)) : \
85 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020086#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020087 (((PyCompactUnicodeObject*)(op))->utf8_length)
88#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020089 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020090 assert(PyUnicode_IS_READY(op)), \
91 PyUnicode_IS_COMPACT_ASCII(op) ? \
92 ((PyASCIIObject*)(op))->length : \
93 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020094#define _PyUnicode_WSTR(op) \
95 (((PyASCIIObject*)(op))->wstr)
96#define _PyUnicode_WSTR_LENGTH(op) \
97 (((PyCompactUnicodeObject*)(op))->wstr_length)
98#define _PyUnicode_LENGTH(op) \
99 (((PyASCIIObject *)(op))->length)
100#define _PyUnicode_STATE(op) \
101 (((PyASCIIObject *)(op))->state)
102#define _PyUnicode_HASH(op) \
103 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200104#define _PyUnicode_KIND(op) \
105 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200106 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200107#define _PyUnicode_GET_LENGTH(op) \
108 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200109 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200110#define _PyUnicode_DATA_ANY(op) \
111 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200112
Victor Stinner910337b2011-10-03 03:20:16 +0200113#undef PyUnicode_READY
114#define PyUnicode_READY(op) \
115 (assert(_PyUnicode_CHECK(op)), \
116 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200117 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100118 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200119
Victor Stinnerc379ead2011-10-03 12:52:27 +0200120#define _PyUnicode_SHARE_UTF8(op) \
121 (assert(_PyUnicode_CHECK(op)), \
122 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
123 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
124#define _PyUnicode_SHARE_WSTR(op) \
125 (assert(_PyUnicode_CHECK(op)), \
126 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
127
Victor Stinner829c0ad2011-10-03 01:08:02 +0200128/* true if the Unicode object has an allocated UTF-8 memory block
129 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200130#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200131 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200132 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200133 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
134
Victor Stinner03490912011-10-03 23:45:12 +0200135/* true if the Unicode object has an allocated wstr memory block
136 (not shared with other data) */
137#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200138 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200139 (!PyUnicode_IS_READY(op) || \
140 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
141
Victor Stinner910337b2011-10-03 03:20:16 +0200142/* Generic helper macro to convert characters of different types.
143 from_type and to_type have to be valid type names, begin and end
144 are pointers to the source characters which should be of type
145 "from_type *". to is a pointer of type "to_type *" and points to the
146 buffer where the result characters are written to. */
147#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
148 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100149 to_type *_to = (to_type *)(to); \
150 const from_type *_iter = (from_type *)(begin); \
151 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200152 Py_ssize_t n = (_end) - (_iter); \
153 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200154 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200155 while (_iter < (_unrolled_end)) { \
156 _to[0] = (to_type) _iter[0]; \
157 _to[1] = (to_type) _iter[1]; \
158 _to[2] = (to_type) _iter[2]; \
159 _to[3] = (to_type) _iter[3]; \
160 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200161 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200162 while (_iter < (_end)) \
163 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200164 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200165
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200166#ifdef MS_WINDOWS
167 /* On Windows, overallocate by 50% is the best factor */
168# define OVERALLOCATE_FACTOR 2
169#else
170 /* On Linux, overallocate by 25% is the best factor */
171# define OVERALLOCATE_FACTOR 4
172#endif
173
Walter Dörwald16807132007-05-25 13:52:07 +0000174/* This dictionary holds all interned unicode strings. Note that references
175 to strings in this dictionary are *not* counted in the string's ob_refcnt.
176 When the interned string reaches a refcnt of 0 the string deallocation
177 function will delete the reference from this dictionary.
178
179 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000180 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000181*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200182static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000183
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200185static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200186
Serhiy Storchaka678db842013-01-26 12:16:36 +0200187#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 do { \
189 if (unicode_empty != NULL) \
190 Py_INCREF(unicode_empty); \
191 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200192 unicode_empty = PyUnicode_New(0, 0); \
193 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200194 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200195 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
196 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200197 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200198 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000199
Serhiy Storchaka678db842013-01-26 12:16:36 +0200200#define _Py_RETURN_UNICODE_EMPTY() \
201 do { \
202 _Py_INCREF_UNICODE_EMPTY(); \
203 return unicode_empty; \
204 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000205
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200206/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700207static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200208_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
209
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200210/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200211static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200212
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000213/* Single character Unicode strings in the Latin-1 range are being
214 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200215static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000216
Christian Heimes190d79e2008-01-30 11:58:22 +0000217/* Fast detection of the most frequent whitespace characters */
218const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000219 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000220/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000221/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000222/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x000C: * FORM FEED */
224/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000225 0, 1, 1, 1, 1, 1, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000227/* case 0x001C: * FILE SEPARATOR */
228/* case 0x001D: * GROUP SEPARATOR */
229/* case 0x001E: * RECORD SEPARATOR */
230/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000231 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000232/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000233 1, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000237
Benjamin Peterson14339b62009-01-31 16:36:08 +0000238 0, 0, 0, 0, 0, 0, 0, 0,
239 0, 0, 0, 0, 0, 0, 0, 0,
240 0, 0, 0, 0, 0, 0, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0,
242 0, 0, 0, 0, 0, 0, 0, 0,
243 0, 0, 0, 0, 0, 0, 0, 0,
244 0, 0, 0, 0, 0, 0, 0, 0,
245 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000246};
247
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200248/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200249static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200250static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100251static int unicode_modifiable(PyObject *unicode);
252
Victor Stinnerfe226c02011-10-03 03:52:20 +0200253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100255_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200256static PyObject *
257_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
258static PyObject *
259_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
260
261static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000262unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000263 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100264 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000265 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
266
Alexander Belopolsky40018472011-02-26 01:02:56 +0000267static void
268raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300269 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100270 PyObject *unicode,
271 Py_ssize_t startpos, Py_ssize_t endpos,
272 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000273
Christian Heimes190d79e2008-01-30 11:58:22 +0000274/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200275static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000276 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000277/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000278/* 0x000B, * LINE TABULATION */
279/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000280/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000281 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000282 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000283/* 0x001C, * FILE SEPARATOR */
284/* 0x001D, * GROUP SEPARATOR */
285/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 0, 0, 0, 0, 1, 1, 1, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000291
Benjamin Peterson14339b62009-01-31 16:36:08 +0000292 0, 0, 0, 0, 0, 0, 0, 0,
293 0, 0, 0, 0, 0, 0, 0, 0,
294 0, 0, 0, 0, 0, 0, 0, 0,
295 0, 0, 0, 0, 0, 0, 0, 0,
296 0, 0, 0, 0, 0, 0, 0, 0,
297 0, 0, 0, 0, 0, 0, 0, 0,
298 0, 0, 0, 0, 0, 0, 0, 0,
299 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000300};
301
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300302#include "clinic/unicodeobject.c.h"
303
Victor Stinner50149202015-09-22 00:26:54 +0200304typedef enum {
305 _Py_ERROR_UNKNOWN=0,
306 _Py_ERROR_STRICT,
307 _Py_ERROR_SURROGATEESCAPE,
308 _Py_ERROR_REPLACE,
309 _Py_ERROR_IGNORE,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200310 _Py_ERROR_BACKSLASHREPLACE,
311 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200312 _Py_ERROR_XMLCHARREFREPLACE,
313 _Py_ERROR_OTHER
314} _Py_error_handler;
315
316static _Py_error_handler
317get_error_handler(const char *errors)
318{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200319 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200320 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200321 }
322 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200323 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200324 }
325 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200326 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200327 }
328 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200329 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200330 }
331 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200332 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200333 }
334 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200335 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200336 }
337 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200338 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200339 }
Victor Stinner50149202015-09-22 00:26:54 +0200340 return _Py_ERROR_OTHER;
341}
342
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300343/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
344 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000345Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000346PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000347{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000348#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000349 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000350#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000351 /* This is actually an illegal character, so it should
352 not be passed to unichr. */
353 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000354#endif
355}
356
Victor Stinner910337b2011-10-03 03:20:16 +0200357#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200358int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100359_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200360{
361 PyASCIIObject *ascii;
362 unsigned int kind;
363
364 assert(PyUnicode_Check(op));
365
366 ascii = (PyASCIIObject *)op;
367 kind = ascii->state.kind;
368
Victor Stinnera3b334d2011-10-03 13:53:37 +0200369 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200370 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200371 assert(ascii->state.ready == 1);
372 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200373 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200374 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200375 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200376
Victor Stinnera41463c2011-10-04 01:05:08 +0200377 if (ascii->state.compact == 1) {
378 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200379 assert(kind == PyUnicode_1BYTE_KIND
380 || kind == PyUnicode_2BYTE_KIND
381 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200382 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200383 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200384 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100385 }
386 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200387 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
388
389 data = unicode->data.any;
390 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100391 assert(ascii->length == 0);
392 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200393 assert(ascii->state.compact == 0);
394 assert(ascii->state.ascii == 0);
395 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100396 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200397 assert(ascii->wstr != NULL);
398 assert(data == NULL);
399 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200400 }
401 else {
402 assert(kind == PyUnicode_1BYTE_KIND
403 || kind == PyUnicode_2BYTE_KIND
404 || kind == PyUnicode_4BYTE_KIND);
405 assert(ascii->state.compact == 0);
406 assert(ascii->state.ready == 1);
407 assert(data != NULL);
408 if (ascii->state.ascii) {
409 assert (compact->utf8 == data);
410 assert (compact->utf8_length == ascii->length);
411 }
412 else
413 assert (compact->utf8 != data);
414 }
415 }
416 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200417 if (
418#if SIZEOF_WCHAR_T == 2
419 kind == PyUnicode_2BYTE_KIND
420#else
421 kind == PyUnicode_4BYTE_KIND
422#endif
423 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200424 {
425 assert(ascii->wstr == data);
426 assert(compact->wstr_length == ascii->length);
427 } else
428 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200429 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200430
431 if (compact->utf8 == NULL)
432 assert(compact->utf8_length == 0);
433 if (ascii->wstr == NULL)
434 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200435 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200436 /* check that the best kind is used */
437 if (check_content && kind != PyUnicode_WCHAR_KIND)
438 {
439 Py_ssize_t i;
440 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200441 void *data;
442 Py_UCS4 ch;
443
444 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200445 for (i=0; i < ascii->length; i++)
446 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200447 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200448 if (ch > maxchar)
449 maxchar = ch;
450 }
451 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100452 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200453 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100454 assert(maxchar <= 255);
455 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200456 else
457 assert(maxchar < 128);
458 }
Victor Stinner77faf692011-11-20 18:56:05 +0100459 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200460 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100461 assert(maxchar <= 0xFFFF);
462 }
463 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200464 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100465 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100466 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200467 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200468 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400469 return 1;
470}
Victor Stinner910337b2011-10-03 03:20:16 +0200471#endif
472
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100473static PyObject*
474unicode_result_wchar(PyObject *unicode)
475{
476#ifndef Py_DEBUG
477 Py_ssize_t len;
478
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100479 len = _PyUnicode_WSTR_LENGTH(unicode);
480 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100481 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200482 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100483 }
484
485 if (len == 1) {
486 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100487 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100488 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
489 Py_DECREF(unicode);
490 return latin1_char;
491 }
492 }
493
494 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200495 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100496 return NULL;
497 }
498#else
Victor Stinneraa771272012-10-04 02:32:58 +0200499 assert(Py_REFCNT(unicode) == 1);
500
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100501 /* don't make the result ready in debug mode to ensure that the caller
502 makes the string ready before using it */
503 assert(_PyUnicode_CheckConsistency(unicode, 1));
504#endif
505 return unicode;
506}
507
508static PyObject*
509unicode_result_ready(PyObject *unicode)
510{
511 Py_ssize_t length;
512
513 length = PyUnicode_GET_LENGTH(unicode);
514 if (length == 0) {
515 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100516 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200517 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100518 }
519 return unicode_empty;
520 }
521
522 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200523 void *data = PyUnicode_DATA(unicode);
524 int kind = PyUnicode_KIND(unicode);
525 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100526 if (ch < 256) {
527 PyObject *latin1_char = unicode_latin1[ch];
528 if (latin1_char != NULL) {
529 if (unicode != latin1_char) {
530 Py_INCREF(latin1_char);
531 Py_DECREF(unicode);
532 }
533 return latin1_char;
534 }
535 else {
536 assert(_PyUnicode_CheckConsistency(unicode, 1));
537 Py_INCREF(unicode);
538 unicode_latin1[ch] = unicode;
539 return unicode;
540 }
541 }
542 }
543
544 assert(_PyUnicode_CheckConsistency(unicode, 1));
545 return unicode;
546}
547
548static PyObject*
549unicode_result(PyObject *unicode)
550{
551 assert(_PyUnicode_CHECK(unicode));
552 if (PyUnicode_IS_READY(unicode))
553 return unicode_result_ready(unicode);
554 else
555 return unicode_result_wchar(unicode);
556}
557
Victor Stinnerc4b49542011-12-11 22:44:26 +0100558static PyObject*
559unicode_result_unchanged(PyObject *unicode)
560{
561 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500562 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100563 return NULL;
564 Py_INCREF(unicode);
565 return unicode;
566 }
567 else
568 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100569 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100570}
571
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200572/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
573 ASCII, Latin1, UTF-8, etc. */
574static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200575backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200576 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
577{
Victor Stinnerad771582015-10-09 12:38:53 +0200578 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200579 Py_UCS4 ch;
580 enum PyUnicode_Kind kind;
581 void *data;
582
583 assert(PyUnicode_IS_READY(unicode));
584 kind = PyUnicode_KIND(unicode);
585 data = PyUnicode_DATA(unicode);
586
587 size = 0;
588 /* determine replacement size */
589 for (i = collstart; i < collend; ++i) {
590 Py_ssize_t incr;
591
592 ch = PyUnicode_READ(kind, data, i);
593 if (ch < 0x100)
594 incr = 2+2;
595 else if (ch < 0x10000)
596 incr = 2+4;
597 else {
598 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200599 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200600 }
601 if (size > PY_SSIZE_T_MAX - incr) {
602 PyErr_SetString(PyExc_OverflowError,
603 "encoded result is too long for a Python string");
604 return NULL;
605 }
606 size += incr;
607 }
608
Victor Stinnerad771582015-10-09 12:38:53 +0200609 str = _PyBytesWriter_Prepare(writer, str, size);
610 if (str == NULL)
611 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200612
613 /* generate replacement */
614 for (i = collstart; i < collend; ++i) {
615 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200616 *str++ = '\\';
617 if (ch >= 0x00010000) {
618 *str++ = 'U';
619 *str++ = Py_hexdigits[(ch>>28)&0xf];
620 *str++ = Py_hexdigits[(ch>>24)&0xf];
621 *str++ = Py_hexdigits[(ch>>20)&0xf];
622 *str++ = Py_hexdigits[(ch>>16)&0xf];
623 *str++ = Py_hexdigits[(ch>>12)&0xf];
624 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200625 }
Victor Stinner797485e2015-10-09 03:17:30 +0200626 else if (ch >= 0x100) {
627 *str++ = 'u';
628 *str++ = Py_hexdigits[(ch>>12)&0xf];
629 *str++ = Py_hexdigits[(ch>>8)&0xf];
630 }
631 else
632 *str++ = 'x';
633 *str++ = Py_hexdigits[(ch>>4)&0xf];
634 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200635 }
636 return str;
637}
638
639/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
640 ASCII, Latin1, UTF-8, etc. */
641static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200642xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200643 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
644{
Victor Stinnerad771582015-10-09 12:38:53 +0200645 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200646 Py_UCS4 ch;
647 enum PyUnicode_Kind kind;
648 void *data;
649
650 assert(PyUnicode_IS_READY(unicode));
651 kind = PyUnicode_KIND(unicode);
652 data = PyUnicode_DATA(unicode);
653
654 size = 0;
655 /* determine replacement size */
656 for (i = collstart; i < collend; ++i) {
657 Py_ssize_t incr;
658
659 ch = PyUnicode_READ(kind, data, i);
660 if (ch < 10)
661 incr = 2+1+1;
662 else if (ch < 100)
663 incr = 2+2+1;
664 else if (ch < 1000)
665 incr = 2+3+1;
666 else if (ch < 10000)
667 incr = 2+4+1;
668 else if (ch < 100000)
669 incr = 2+5+1;
670 else if (ch < 1000000)
671 incr = 2+6+1;
672 else {
673 assert(ch <= MAX_UNICODE);
674 incr = 2+7+1;
675 }
676 if (size > PY_SSIZE_T_MAX - incr) {
677 PyErr_SetString(PyExc_OverflowError,
678 "encoded result is too long for a Python string");
679 return NULL;
680 }
681 size += incr;
682 }
683
Victor Stinnerad771582015-10-09 12:38:53 +0200684 str = _PyBytesWriter_Prepare(writer, str, size);
685 if (str == NULL)
686 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200687
688 /* generate replacement */
689 for (i = collstart; i < collend; ++i) {
690 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
691 }
692 return str;
693}
694
Thomas Wouters477c8d52006-05-27 19:21:47 +0000695/* --- Bloom Filters ----------------------------------------------------- */
696
697/* stuff to implement simple "bloom filters" for Unicode characters.
698 to keep things simple, we use a single bitmask, using the least 5
699 bits from each unicode characters as the bit index. */
700
701/* the linebreak mask is set up by Unicode_Init below */
702
Antoine Pitrouf068f942010-01-13 14:19:12 +0000703#if LONG_BIT >= 128
704#define BLOOM_WIDTH 128
705#elif LONG_BIT >= 64
706#define BLOOM_WIDTH 64
707#elif LONG_BIT >= 32
708#define BLOOM_WIDTH 32
709#else
710#error "LONG_BIT is smaller than 32"
711#endif
712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713#define BLOOM_MASK unsigned long
714
Serhiy Storchaka05997252013-01-26 12:14:02 +0200715static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716
Antoine Pitrouf068f942010-01-13 14:19:12 +0000717#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718
Benjamin Peterson29060642009-01-31 22:14:21 +0000719#define BLOOM_LINEBREAK(ch) \
720 ((ch) < 128U ? ascii_linebreak[(ch)] : \
721 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000722
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700723static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200724make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000725{
Victor Stinnera85af502013-04-09 21:53:54 +0200726#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
727 do { \
728 TYPE *data = (TYPE *)PTR; \
729 TYPE *end = data + LEN; \
730 Py_UCS4 ch; \
731 for (; data != end; data++) { \
732 ch = *data; \
733 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
734 } \
735 break; \
736 } while (0)
737
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738 /* calculate simple bloom-style bitmask for a given unicode string */
739
Antoine Pitrouf068f942010-01-13 14:19:12 +0000740 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741
742 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200743 switch (kind) {
744 case PyUnicode_1BYTE_KIND:
745 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
746 break;
747 case PyUnicode_2BYTE_KIND:
748 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
749 break;
750 case PyUnicode_4BYTE_KIND:
751 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
752 break;
753 default:
754 assert(0);
755 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000756 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200757
758#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000759}
760
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300761static int
762ensure_unicode(PyObject *obj)
763{
764 if (!PyUnicode_Check(obj)) {
765 PyErr_Format(PyExc_TypeError,
766 "must be str, not %.100s",
767 Py_TYPE(obj)->tp_name);
768 return -1;
769 }
770 return PyUnicode_READY(obj);
771}
772
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200773/* Compilation of templated routines */
774
775#include "stringlib/asciilib.h"
776#include "stringlib/fastsearch.h"
777#include "stringlib/partition.h"
778#include "stringlib/split.h"
779#include "stringlib/count.h"
780#include "stringlib/find.h"
781#include "stringlib/find_max_char.h"
782#include "stringlib/localeutil.h"
783#include "stringlib/undef.h"
784
785#include "stringlib/ucs1lib.h"
786#include "stringlib/fastsearch.h"
787#include "stringlib/partition.h"
788#include "stringlib/split.h"
789#include "stringlib/count.h"
790#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300791#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200792#include "stringlib/find_max_char.h"
793#include "stringlib/localeutil.h"
794#include "stringlib/undef.h"
795
796#include "stringlib/ucs2lib.h"
797#include "stringlib/fastsearch.h"
798#include "stringlib/partition.h"
799#include "stringlib/split.h"
800#include "stringlib/count.h"
801#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300802#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200803#include "stringlib/find_max_char.h"
804#include "stringlib/localeutil.h"
805#include "stringlib/undef.h"
806
807#include "stringlib/ucs4lib.h"
808#include "stringlib/fastsearch.h"
809#include "stringlib/partition.h"
810#include "stringlib/split.h"
811#include "stringlib/count.h"
812#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300813#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200814#include "stringlib/find_max_char.h"
815#include "stringlib/localeutil.h"
816#include "stringlib/undef.h"
817
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200818#include "stringlib/unicodedefs.h"
819#include "stringlib/fastsearch.h"
820#include "stringlib/count.h"
821#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100822#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200823
Guido van Rossumd57fd912000-03-10 22:53:23 +0000824/* --- Unicode Object ----------------------------------------------------- */
825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200826static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200827fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200828
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700829static inline Py_ssize_t
830findchar(const void *s, int kind,
831 Py_ssize_t size, Py_UCS4 ch,
832 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200833{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200834 switch (kind) {
835 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200836 if ((Py_UCS1) ch != ch)
837 return -1;
838 if (direction > 0)
839 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
840 else
841 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200842 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200843 if ((Py_UCS2) ch != ch)
844 return -1;
845 if (direction > 0)
846 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
847 else
848 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200849 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200850 if (direction > 0)
851 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
852 else
853 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200854 default:
855 assert(0);
856 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200857 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200858}
859
Victor Stinnerafffce42012-10-03 23:03:17 +0200860#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000861/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200862 earlier.
863
864 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
865 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
866 invalid character in Unicode 6.0. */
867static void
868unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
869{
870 int kind = PyUnicode_KIND(unicode);
871 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
872 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
873 if (length <= old_length)
874 return;
875 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
876}
877#endif
878
Victor Stinnerfe226c02011-10-03 03:52:20 +0200879static PyObject*
880resize_compact(PyObject *unicode, Py_ssize_t length)
881{
882 Py_ssize_t char_size;
883 Py_ssize_t struct_size;
884 Py_ssize_t new_size;
885 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100886 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200887#ifdef Py_DEBUG
888 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
889#endif
890
Victor Stinner79891572012-05-03 13:43:07 +0200891 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200892 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100893 assert(PyUnicode_IS_COMPACT(unicode));
894
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200895 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100896 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200897 struct_size = sizeof(PyASCIIObject);
898 else
899 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200900 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200901
Victor Stinnerfe226c02011-10-03 03:52:20 +0200902 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
903 PyErr_NoMemory();
904 return NULL;
905 }
906 new_size = (struct_size + (length + 1) * char_size);
907
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200908 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
909 PyObject_DEL(_PyUnicode_UTF8(unicode));
910 _PyUnicode_UTF8(unicode) = NULL;
911 _PyUnicode_UTF8_LENGTH(unicode) = 0;
912 }
Victor Stinner84def372011-12-11 20:04:56 +0100913 _Py_DEC_REFTOTAL;
914 _Py_ForgetReference(unicode);
915
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300916 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100917 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100918 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200919 PyErr_NoMemory();
920 return NULL;
921 }
Victor Stinner84def372011-12-11 20:04:56 +0100922 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200923 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100924
Victor Stinnerfe226c02011-10-03 03:52:20 +0200925 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200926 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200927 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100928 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200929 _PyUnicode_WSTR_LENGTH(unicode) = length;
930 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100931 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
932 PyObject_DEL(_PyUnicode_WSTR(unicode));
933 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100934 if (!PyUnicode_IS_ASCII(unicode))
935 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100936 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200937#ifdef Py_DEBUG
938 unicode_fill_invalid(unicode, old_length);
939#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
941 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200942 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200943 return unicode;
944}
945
Alexander Belopolsky40018472011-02-26 01:02:56 +0000946static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200947resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000948{
Victor Stinner95663112011-10-04 01:03:50 +0200949 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100950 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200951 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200952 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000953
Victor Stinnerfe226c02011-10-03 03:52:20 +0200954 if (PyUnicode_IS_READY(unicode)) {
955 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200956 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200957 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200958#ifdef Py_DEBUG
959 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
960#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200961
962 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200963 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200964 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
965 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200966
967 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
968 PyErr_NoMemory();
969 return -1;
970 }
971 new_size = (length + 1) * char_size;
972
Victor Stinner7a9105a2011-12-12 00:13:42 +0100973 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
974 {
975 PyObject_DEL(_PyUnicode_UTF8(unicode));
976 _PyUnicode_UTF8(unicode) = NULL;
977 _PyUnicode_UTF8_LENGTH(unicode) = 0;
978 }
979
Victor Stinnerfe226c02011-10-03 03:52:20 +0200980 data = (PyObject *)PyObject_REALLOC(data, new_size);
981 if (data == NULL) {
982 PyErr_NoMemory();
983 return -1;
984 }
985 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200986 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200987 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200988 _PyUnicode_WSTR_LENGTH(unicode) = length;
989 }
990 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200991 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200992 _PyUnicode_UTF8_LENGTH(unicode) = length;
993 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200994 _PyUnicode_LENGTH(unicode) = length;
995 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200996#ifdef Py_DEBUG
997 unicode_fill_invalid(unicode, old_length);
998#endif
Victor Stinner95663112011-10-04 01:03:50 +0200999 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001000 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001001 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001002 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001003 }
Victor Stinner95663112011-10-04 01:03:50 +02001004 assert(_PyUnicode_WSTR(unicode) != NULL);
1005
1006 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001007 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001008 PyErr_NoMemory();
1009 return -1;
1010 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001011 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001012 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001013 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001014 if (!wstr) {
1015 PyErr_NoMemory();
1016 return -1;
1017 }
1018 _PyUnicode_WSTR(unicode) = wstr;
1019 _PyUnicode_WSTR(unicode)[length] = 0;
1020 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001021 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001022 return 0;
1023}
1024
Victor Stinnerfe226c02011-10-03 03:52:20 +02001025static PyObject*
1026resize_copy(PyObject *unicode, Py_ssize_t length)
1027{
1028 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001029 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001030 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001031
Benjamin Petersonbac79492012-01-14 13:34:47 -05001032 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +01001033 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001034
1035 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1036 if (copy == NULL)
1037 return NULL;
1038
1039 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001040 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001041 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001042 }
1043 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001044 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001045
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001046 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001047 if (w == NULL)
1048 return NULL;
1049 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1050 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001051 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001052 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001053 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001054 }
1055}
1056
Guido van Rossumd57fd912000-03-10 22:53:23 +00001057/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001058 Ux0000 terminated; some code (e.g. new_identifier)
1059 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001060
1061 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001062 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001063
1064*/
1065
Alexander Belopolsky40018472011-02-26 01:02:56 +00001066static PyUnicodeObject *
1067_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001068{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001069 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001071
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001073 if (length == 0 && unicode_empty != NULL) {
1074 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001075 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001076 }
1077
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001078 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001079 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001080 return (PyUnicodeObject *)PyErr_NoMemory();
1081 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082 if (length < 0) {
1083 PyErr_SetString(PyExc_SystemError,
1084 "Negative size passed to _PyUnicode_New");
1085 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001086 }
1087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001088 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1089 if (unicode == NULL)
1090 return NULL;
1091 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001092
1093 _PyUnicode_WSTR_LENGTH(unicode) = length;
1094 _PyUnicode_HASH(unicode) = -1;
1095 _PyUnicode_STATE(unicode).interned = 0;
1096 _PyUnicode_STATE(unicode).kind = 0;
1097 _PyUnicode_STATE(unicode).compact = 0;
1098 _PyUnicode_STATE(unicode).ready = 0;
1099 _PyUnicode_STATE(unicode).ascii = 0;
1100 _PyUnicode_DATA_ANY(unicode) = NULL;
1101 _PyUnicode_LENGTH(unicode) = 0;
1102 _PyUnicode_UTF8(unicode) = NULL;
1103 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001105 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1106 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001107 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001108 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001109 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001111
Jeremy Hyltond8082792003-09-16 19:41:39 +00001112 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001113 * the caller fails before initializing str -- unicode_resize()
1114 * reads str[0], and the Keep-Alive optimization can keep memory
1115 * allocated for str alive across a call to unicode_dealloc(unicode).
1116 * We don't want unicode_resize to read uninitialized memory in
1117 * that case.
1118 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 _PyUnicode_WSTR(unicode)[0] = 0;
1120 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001121
Victor Stinner7931d9a2011-11-04 00:22:48 +01001122 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001123 return unicode;
1124}
1125
Victor Stinnerf42dc442011-10-02 23:33:16 +02001126static const char*
1127unicode_kind_name(PyObject *unicode)
1128{
Victor Stinner42dfd712011-10-03 14:41:45 +02001129 /* don't check consistency: unicode_kind_name() is called from
1130 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001131 if (!PyUnicode_IS_COMPACT(unicode))
1132 {
1133 if (!PyUnicode_IS_READY(unicode))
1134 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001135 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001136 {
1137 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001138 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001139 return "legacy ascii";
1140 else
1141 return "legacy latin1";
1142 case PyUnicode_2BYTE_KIND:
1143 return "legacy UCS2";
1144 case PyUnicode_4BYTE_KIND:
1145 return "legacy UCS4";
1146 default:
1147 return "<legacy invalid kind>";
1148 }
1149 }
1150 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001151 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001152 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001153 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001154 return "ascii";
1155 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001156 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001157 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001158 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001159 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001160 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001161 default:
1162 return "<invalid compact kind>";
1163 }
1164}
1165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001167/* Functions wrapping macros for use in debugger */
1168char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001169 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001170}
1171
1172void *_PyUnicode_compact_data(void *unicode) {
1173 return _PyUnicode_COMPACT_DATA(unicode);
1174}
1175void *_PyUnicode_data(void *unicode){
1176 printf("obj %p\n", unicode);
1177 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1178 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1179 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1180 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1181 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1182 return PyUnicode_DATA(unicode);
1183}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001184
1185void
1186_PyUnicode_Dump(PyObject *op)
1187{
1188 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001189 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1190 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1191 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001192
Victor Stinnera849a4b2011-10-03 12:12:11 +02001193 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001194 {
1195 if (ascii->state.ascii)
1196 data = (ascii + 1);
1197 else
1198 data = (compact + 1);
1199 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001200 else
1201 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001202 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1203 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001204
Victor Stinnera849a4b2011-10-03 12:12:11 +02001205 if (ascii->wstr == data)
1206 printf("shared ");
1207 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001208
Victor Stinnera3b334d2011-10-03 13:53:37 +02001209 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001210 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001211 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1212 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001213 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1214 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001215 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001216 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001217}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001218#endif
1219
1220PyObject *
1221PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1222{
1223 PyObject *obj;
1224 PyCompactUnicodeObject *unicode;
1225 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001226 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001227 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228 Py_ssize_t char_size;
1229 Py_ssize_t struct_size;
1230
1231 /* Optimization for empty strings */
1232 if (size == 0 && unicode_empty != NULL) {
1233 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001234 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001235 }
1236
Victor Stinner9e9d6892011-10-04 01:02:02 +02001237 is_ascii = 0;
1238 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001239 struct_size = sizeof(PyCompactUnicodeObject);
1240 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001241 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001242 char_size = 1;
1243 is_ascii = 1;
1244 struct_size = sizeof(PyASCIIObject);
1245 }
1246 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001247 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001248 char_size = 1;
1249 }
1250 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001251 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001252 char_size = 2;
1253 if (sizeof(wchar_t) == 2)
1254 is_sharing = 1;
1255 }
1256 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001257 if (maxchar > MAX_UNICODE) {
1258 PyErr_SetString(PyExc_SystemError,
1259 "invalid maximum character passed to PyUnicode_New");
1260 return NULL;
1261 }
Victor Stinner8f825062012-04-27 13:55:39 +02001262 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001263 char_size = 4;
1264 if (sizeof(wchar_t) == 4)
1265 is_sharing = 1;
1266 }
1267
1268 /* Ensure we won't overflow the size. */
1269 if (size < 0) {
1270 PyErr_SetString(PyExc_SystemError,
1271 "Negative size passed to PyUnicode_New");
1272 return NULL;
1273 }
1274 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1275 return PyErr_NoMemory();
1276
1277 /* Duplicated allocation code from _PyObject_New() instead of a call to
1278 * PyObject_New() so we are able to allocate space for the object and
1279 * it's data buffer.
1280 */
1281 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1282 if (obj == NULL)
1283 return PyErr_NoMemory();
1284 obj = PyObject_INIT(obj, &PyUnicode_Type);
1285 if (obj == NULL)
1286 return NULL;
1287
1288 unicode = (PyCompactUnicodeObject *)obj;
1289 if (is_ascii)
1290 data = ((PyASCIIObject*)obj) + 1;
1291 else
1292 data = unicode + 1;
1293 _PyUnicode_LENGTH(unicode) = size;
1294 _PyUnicode_HASH(unicode) = -1;
1295 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001296 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297 _PyUnicode_STATE(unicode).compact = 1;
1298 _PyUnicode_STATE(unicode).ready = 1;
1299 _PyUnicode_STATE(unicode).ascii = is_ascii;
1300 if (is_ascii) {
1301 ((char*)data)[size] = 0;
1302 _PyUnicode_WSTR(unicode) = NULL;
1303 }
Victor Stinner8f825062012-04-27 13:55:39 +02001304 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001305 ((char*)data)[size] = 0;
1306 _PyUnicode_WSTR(unicode) = NULL;
1307 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001308 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001309 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001310 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311 else {
1312 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001313 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001314 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001316 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 ((Py_UCS4*)data)[size] = 0;
1318 if (is_sharing) {
1319 _PyUnicode_WSTR_LENGTH(unicode) = size;
1320 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1321 }
1322 else {
1323 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1324 _PyUnicode_WSTR(unicode) = NULL;
1325 }
1326 }
Victor Stinner8f825062012-04-27 13:55:39 +02001327#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001328 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001329#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001330 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001331 return obj;
1332}
1333
1334#if SIZEOF_WCHAR_T == 2
1335/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1336 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001337 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338
1339 This function assumes that unicode can hold one more code point than wstr
1340 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001341static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001343 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344{
1345 const wchar_t *iter;
1346 Py_UCS4 *ucs4_out;
1347
Victor Stinner910337b2011-10-03 03:20:16 +02001348 assert(unicode != NULL);
1349 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1351 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1352
1353 for (iter = begin; iter < end; ) {
1354 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1355 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001356 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1357 && (iter+1) < end
1358 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001359 {
Victor Stinner551ac952011-11-29 22:58:13 +01001360 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001361 iter += 2;
1362 }
1363 else {
1364 *ucs4_out++ = *iter;
1365 iter++;
1366 }
1367 }
1368 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1369 _PyUnicode_GET_LENGTH(unicode)));
1370
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371}
1372#endif
1373
Victor Stinnercd9950f2011-10-02 00:34:53 +02001374static int
Victor Stinner488fa492011-12-12 00:01:39 +01001375unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001376{
Victor Stinner488fa492011-12-12 00:01:39 +01001377 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001378 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001379 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001380 return -1;
1381 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001382 return 0;
1383}
1384
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001385static int
1386_copy_characters(PyObject *to, Py_ssize_t to_start,
1387 PyObject *from, Py_ssize_t from_start,
1388 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001390 unsigned int from_kind, to_kind;
1391 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001392
Victor Stinneree4544c2012-05-09 22:24:08 +02001393 assert(0 <= how_many);
1394 assert(0 <= from_start);
1395 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001396 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001397 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001398 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399
Victor Stinnerd3f08822012-05-29 12:57:52 +02001400 assert(PyUnicode_Check(to));
1401 assert(PyUnicode_IS_READY(to));
1402 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1403
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001404 if (how_many == 0)
1405 return 0;
1406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001408 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001409 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001410 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411
Victor Stinnerf1852262012-06-16 16:38:26 +02001412#ifdef Py_DEBUG
1413 if (!check_maxchar
1414 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1415 {
1416 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1417 Py_UCS4 ch;
1418 Py_ssize_t i;
1419 for (i=0; i < how_many; i++) {
1420 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1421 assert(ch <= to_maxchar);
1422 }
1423 }
1424#endif
1425
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001426 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001427 if (check_maxchar
1428 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1429 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001430 /* Writing Latin-1 characters into an ASCII string requires to
1431 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001432 Py_UCS4 max_char;
1433 max_char = ucs1lib_find_max_char(from_data,
1434 (Py_UCS1*)from_data + how_many);
1435 if (max_char >= 128)
1436 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001437 }
Christian Heimesf051e432016-09-13 20:22:02 +02001438 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001439 (char*)from_data + from_kind * from_start,
1440 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001441 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001442 else if (from_kind == PyUnicode_1BYTE_KIND
1443 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001444 {
1445 _PyUnicode_CONVERT_BYTES(
1446 Py_UCS1, Py_UCS2,
1447 PyUnicode_1BYTE_DATA(from) + from_start,
1448 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1449 PyUnicode_2BYTE_DATA(to) + to_start
1450 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001451 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001452 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001453 && to_kind == PyUnicode_4BYTE_KIND)
1454 {
1455 _PyUnicode_CONVERT_BYTES(
1456 Py_UCS1, Py_UCS4,
1457 PyUnicode_1BYTE_DATA(from) + from_start,
1458 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1459 PyUnicode_4BYTE_DATA(to) + to_start
1460 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001461 }
1462 else if (from_kind == PyUnicode_2BYTE_KIND
1463 && to_kind == PyUnicode_4BYTE_KIND)
1464 {
1465 _PyUnicode_CONVERT_BYTES(
1466 Py_UCS2, Py_UCS4,
1467 PyUnicode_2BYTE_DATA(from) + from_start,
1468 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1469 PyUnicode_4BYTE_DATA(to) + to_start
1470 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001471 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001472 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001473 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1474
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001475 if (!check_maxchar) {
1476 if (from_kind == PyUnicode_2BYTE_KIND
1477 && to_kind == PyUnicode_1BYTE_KIND)
1478 {
1479 _PyUnicode_CONVERT_BYTES(
1480 Py_UCS2, Py_UCS1,
1481 PyUnicode_2BYTE_DATA(from) + from_start,
1482 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1483 PyUnicode_1BYTE_DATA(to) + to_start
1484 );
1485 }
1486 else if (from_kind == PyUnicode_4BYTE_KIND
1487 && to_kind == PyUnicode_1BYTE_KIND)
1488 {
1489 _PyUnicode_CONVERT_BYTES(
1490 Py_UCS4, Py_UCS1,
1491 PyUnicode_4BYTE_DATA(from) + from_start,
1492 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1493 PyUnicode_1BYTE_DATA(to) + to_start
1494 );
1495 }
1496 else if (from_kind == PyUnicode_4BYTE_KIND
1497 && to_kind == PyUnicode_2BYTE_KIND)
1498 {
1499 _PyUnicode_CONVERT_BYTES(
1500 Py_UCS4, Py_UCS2,
1501 PyUnicode_4BYTE_DATA(from) + from_start,
1502 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1503 PyUnicode_2BYTE_DATA(to) + to_start
1504 );
1505 }
1506 else {
1507 assert(0);
1508 return -1;
1509 }
1510 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001511 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001512 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001513 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001514 Py_ssize_t i;
1515
Victor Stinnera0702ab2011-09-29 14:14:38 +02001516 for (i=0; i < how_many; i++) {
1517 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001518 if (ch > to_maxchar)
1519 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001520 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1521 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001522 }
1523 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001524 return 0;
1525}
1526
Victor Stinnerd3f08822012-05-29 12:57:52 +02001527void
1528_PyUnicode_FastCopyCharacters(
1529 PyObject *to, Py_ssize_t to_start,
1530 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001531{
1532 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1533}
1534
1535Py_ssize_t
1536PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1537 PyObject *from, Py_ssize_t from_start,
1538 Py_ssize_t how_many)
1539{
1540 int err;
1541
1542 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1543 PyErr_BadInternalCall();
1544 return -1;
1545 }
1546
Benjamin Petersonbac79492012-01-14 13:34:47 -05001547 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001548 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001549 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001550 return -1;
1551
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001552 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001553 PyErr_SetString(PyExc_IndexError, "string index out of range");
1554 return -1;
1555 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001556 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001557 PyErr_SetString(PyExc_IndexError, "string index out of range");
1558 return -1;
1559 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001560 if (how_many < 0) {
1561 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1562 return -1;
1563 }
1564 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001565 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1566 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001567 "Cannot write %zi characters at %zi "
1568 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001569 how_many, to_start, PyUnicode_GET_LENGTH(to));
1570 return -1;
1571 }
1572
1573 if (how_many == 0)
1574 return 0;
1575
Victor Stinner488fa492011-12-12 00:01:39 +01001576 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001577 return -1;
1578
1579 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1580 if (err) {
1581 PyErr_Format(PyExc_SystemError,
1582 "Cannot copy %s characters "
1583 "into a string of %s characters",
1584 unicode_kind_name(from),
1585 unicode_kind_name(to));
1586 return -1;
1587 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001588 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001589}
1590
Victor Stinner17222162011-09-28 22:15:37 +02001591/* Find the maximum code point and count the number of surrogate pairs so a
1592 correct string length can be computed before converting a string to UCS4.
1593 This function counts single surrogates as a character and not as a pair.
1594
1595 Return 0 on success, or -1 on error. */
1596static int
1597find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1598 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001599{
1600 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001601 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602
Victor Stinnerc53be962011-10-02 21:33:54 +02001603 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001604 *num_surrogates = 0;
1605 *maxchar = 0;
1606
1607 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001609 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1610 && (iter+1) < end
1611 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1612 {
1613 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1614 ++(*num_surrogates);
1615 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001616 }
1617 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001618#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001619 {
1620 ch = *iter;
1621 iter++;
1622 }
1623 if (ch > *maxchar) {
1624 *maxchar = ch;
1625 if (*maxchar > MAX_UNICODE) {
1626 PyErr_Format(PyExc_ValueError,
1627 "character U+%x is not in range [U+0000; U+10ffff]",
1628 ch);
1629 return -1;
1630 }
1631 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001632 }
1633 return 0;
1634}
1635
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001636int
1637_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001638{
1639 wchar_t *end;
1640 Py_UCS4 maxchar = 0;
1641 Py_ssize_t num_surrogates;
1642#if SIZEOF_WCHAR_T == 2
1643 Py_ssize_t length_wo_surrogates;
1644#endif
1645
Georg Brandl7597add2011-10-05 16:36:47 +02001646 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001647 strings were created using _PyObject_New() and where no canonical
1648 representation (the str field) has been set yet aka strings
1649 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001650 assert(_PyUnicode_CHECK(unicode));
1651 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001652 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001653 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001654 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001655 /* Actually, it should neither be interned nor be anything else: */
1656 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001659 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001660 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001662
1663 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001664 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1665 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001666 PyErr_NoMemory();
1667 return -1;
1668 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001669 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001670 _PyUnicode_WSTR(unicode), end,
1671 PyUnicode_1BYTE_DATA(unicode));
1672 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1673 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1674 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1675 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001676 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001677 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001678 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001679 }
1680 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001681 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001682 _PyUnicode_UTF8(unicode) = NULL;
1683 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001684 }
1685 PyObject_FREE(_PyUnicode_WSTR(unicode));
1686 _PyUnicode_WSTR(unicode) = NULL;
1687 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1688 }
1689 /* In this case we might have to convert down from 4-byte native
1690 wchar_t to 2-byte unicode. */
1691 else if (maxchar < 65536) {
1692 assert(num_surrogates == 0 &&
1693 "FindMaxCharAndNumSurrogatePairs() messed up");
1694
Victor Stinner506f5922011-09-28 22:34:18 +02001695#if SIZEOF_WCHAR_T == 2
1696 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001697 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001698 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1699 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1700 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001701 _PyUnicode_UTF8(unicode) = NULL;
1702 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001703#else
1704 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001705 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001706 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001707 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001708 PyErr_NoMemory();
1709 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 }
Victor Stinner506f5922011-09-28 22:34:18 +02001711 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1712 _PyUnicode_WSTR(unicode), end,
1713 PyUnicode_2BYTE_DATA(unicode));
1714 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1715 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1716 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001717 _PyUnicode_UTF8(unicode) = NULL;
1718 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001719 PyObject_FREE(_PyUnicode_WSTR(unicode));
1720 _PyUnicode_WSTR(unicode) = NULL;
1721 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1722#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001723 }
1724 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1725 else {
1726#if SIZEOF_WCHAR_T == 2
1727 /* in case the native representation is 2-bytes, we need to allocate a
1728 new normalized 4-byte version. */
1729 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001730 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1731 PyErr_NoMemory();
1732 return -1;
1733 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001734 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1735 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001736 PyErr_NoMemory();
1737 return -1;
1738 }
1739 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1740 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001741 _PyUnicode_UTF8(unicode) = NULL;
1742 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001743 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1744 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001745 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001746 PyObject_FREE(_PyUnicode_WSTR(unicode));
1747 _PyUnicode_WSTR(unicode) = NULL;
1748 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1749#else
1750 assert(num_surrogates == 0);
1751
Victor Stinnerc3c74152011-10-02 20:39:55 +02001752 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001753 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001754 _PyUnicode_UTF8(unicode) = NULL;
1755 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001756 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1757#endif
1758 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1759 }
1760 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001761 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001762 return 0;
1763}
1764
Alexander Belopolsky40018472011-02-26 01:02:56 +00001765static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001766unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001767{
Walter Dörwald16807132007-05-25 13:52:07 +00001768 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001769 case SSTATE_NOT_INTERNED:
1770 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001771
Benjamin Peterson29060642009-01-31 22:14:21 +00001772 case SSTATE_INTERNED_MORTAL:
1773 /* revive dead object temporarily for DelItem */
1774 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001775 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001776 Py_FatalError(
1777 "deletion of interned string failed");
1778 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001779
Benjamin Peterson29060642009-01-31 22:14:21 +00001780 case SSTATE_INTERNED_IMMORTAL:
1781 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001782
Benjamin Peterson29060642009-01-31 22:14:21 +00001783 default:
1784 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001785 }
1786
Victor Stinner03490912011-10-03 23:45:12 +02001787 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001788 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001789 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001790 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001791 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1792 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001793
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001794 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001795}
1796
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001797#ifdef Py_DEBUG
1798static int
1799unicode_is_singleton(PyObject *unicode)
1800{
1801 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1802 if (unicode == unicode_empty)
1803 return 1;
1804 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1805 {
1806 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1807 if (ch < 256 && unicode_latin1[ch] == unicode)
1808 return 1;
1809 }
1810 return 0;
1811}
1812#endif
1813
Alexander Belopolsky40018472011-02-26 01:02:56 +00001814static int
Victor Stinner488fa492011-12-12 00:01:39 +01001815unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001816{
Victor Stinner488fa492011-12-12 00:01:39 +01001817 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001818 if (Py_REFCNT(unicode) != 1)
1819 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001820 if (_PyUnicode_HASH(unicode) != -1)
1821 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001822 if (PyUnicode_CHECK_INTERNED(unicode))
1823 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001824 if (!PyUnicode_CheckExact(unicode))
1825 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001826#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001827 /* singleton refcount is greater than 1 */
1828 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001829#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001830 return 1;
1831}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001832
Victor Stinnerfe226c02011-10-03 03:52:20 +02001833static int
1834unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1835{
1836 PyObject *unicode;
1837 Py_ssize_t old_length;
1838
1839 assert(p_unicode != NULL);
1840 unicode = *p_unicode;
1841
1842 assert(unicode != NULL);
1843 assert(PyUnicode_Check(unicode));
1844 assert(0 <= length);
1845
Victor Stinner910337b2011-10-03 03:20:16 +02001846 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001847 old_length = PyUnicode_WSTR_LENGTH(unicode);
1848 else
1849 old_length = PyUnicode_GET_LENGTH(unicode);
1850 if (old_length == length)
1851 return 0;
1852
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001853 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001854 _Py_INCREF_UNICODE_EMPTY();
1855 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001856 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001857 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001858 return 0;
1859 }
1860
Victor Stinner488fa492011-12-12 00:01:39 +01001861 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001862 PyObject *copy = resize_copy(unicode, length);
1863 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001864 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001865 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001866 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001867 }
1868
Victor Stinnerfe226c02011-10-03 03:52:20 +02001869 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001870 PyObject *new_unicode = resize_compact(unicode, length);
1871 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001872 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001873 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001874 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001875 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001876 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001877}
1878
Alexander Belopolsky40018472011-02-26 01:02:56 +00001879int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001880PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001881{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001882 PyObject *unicode;
1883 if (p_unicode == NULL) {
1884 PyErr_BadInternalCall();
1885 return -1;
1886 }
1887 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001888 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001889 {
1890 PyErr_BadInternalCall();
1891 return -1;
1892 }
1893 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001894}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001895
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001896/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001897
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001898 WARNING: The function doesn't copy the terminating null character and
1899 doesn't check the maximum character (may write a latin1 character in an
1900 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001901static void
1902unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1903 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001904{
1905 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1906 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001907 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001908
1909 switch (kind) {
1910 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001911 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001912#ifdef Py_DEBUG
1913 if (PyUnicode_IS_ASCII(unicode)) {
1914 Py_UCS4 maxchar = ucs1lib_find_max_char(
1915 (const Py_UCS1*)str,
1916 (const Py_UCS1*)str + len);
1917 assert(maxchar < 128);
1918 }
1919#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001920 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001921 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001922 }
1923 case PyUnicode_2BYTE_KIND: {
1924 Py_UCS2 *start = (Py_UCS2 *)data + index;
1925 Py_UCS2 *ucs2 = start;
1926 assert(index <= PyUnicode_GET_LENGTH(unicode));
1927
Victor Stinner184252a2012-06-16 02:57:41 +02001928 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001929 *ucs2 = (Py_UCS2)*str;
1930
1931 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001932 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001933 }
1934 default: {
1935 Py_UCS4 *start = (Py_UCS4 *)data + index;
1936 Py_UCS4 *ucs4 = start;
1937 assert(kind == PyUnicode_4BYTE_KIND);
1938 assert(index <= PyUnicode_GET_LENGTH(unicode));
1939
Victor Stinner184252a2012-06-16 02:57:41 +02001940 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001941 *ucs4 = (Py_UCS4)*str;
1942
1943 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001944 }
1945 }
1946}
1947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948static PyObject*
1949get_latin1_char(unsigned char ch)
1950{
Victor Stinnera464fc12011-10-02 20:39:30 +02001951 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001952 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001953 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 if (!unicode)
1955 return NULL;
1956 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001957 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001958 unicode_latin1[ch] = unicode;
1959 }
1960 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001961 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001962}
1963
Victor Stinner985a82a2014-01-03 12:53:47 +01001964static PyObject*
1965unicode_char(Py_UCS4 ch)
1966{
1967 PyObject *unicode;
1968
1969 assert(ch <= MAX_UNICODE);
1970
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001971 if (ch < 256)
1972 return get_latin1_char(ch);
1973
Victor Stinner985a82a2014-01-03 12:53:47 +01001974 unicode = PyUnicode_New(1, ch);
1975 if (unicode == NULL)
1976 return NULL;
1977 switch (PyUnicode_KIND(unicode)) {
1978 case PyUnicode_1BYTE_KIND:
1979 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1980 break;
1981 case PyUnicode_2BYTE_KIND:
1982 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1983 break;
1984 default:
1985 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1986 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1987 }
1988 assert(_PyUnicode_CheckConsistency(unicode, 1));
1989 return unicode;
1990}
1991
Alexander Belopolsky40018472011-02-26 01:02:56 +00001992PyObject *
1993PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001994{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001995 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001996 Py_UCS4 maxchar = 0;
1997 Py_ssize_t num_surrogates;
1998
1999 if (u == NULL)
2000 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002001
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002002 /* If the Unicode data is known at construction time, we can apply
2003 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002005 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002006 if (size == 0)
2007 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 /* Single character Unicode objects in the Latin-1 range are
2010 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002011 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002012 return get_latin1_char((unsigned char)*u);
2013
2014 /* If not empty and not single character, copy the Unicode data
2015 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002016 if (find_maxchar_surrogates(u, u + size,
2017 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018 return NULL;
2019
Victor Stinner8faf8212011-12-08 22:14:11 +01002020 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002021 if (!unicode)
2022 return NULL;
2023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002024 switch (PyUnicode_KIND(unicode)) {
2025 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002026 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002027 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2028 break;
2029 case PyUnicode_2BYTE_KIND:
2030#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002031 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002032#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002033 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2035#endif
2036 break;
2037 case PyUnicode_4BYTE_KIND:
2038#if SIZEOF_WCHAR_T == 2
2039 /* This is the only case which has to process surrogates, thus
2040 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002041 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002042#else
2043 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002044 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002045#endif
2046 break;
2047 default:
2048 assert(0 && "Impossible state");
2049 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002050
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002051 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002052}
2053
Alexander Belopolsky40018472011-02-26 01:02:56 +00002054PyObject *
2055PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002056{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002057 if (size < 0) {
2058 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002059 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002060 return NULL;
2061 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002062 if (u != NULL)
2063 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2064 else
2065 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002066}
2067
Alexander Belopolsky40018472011-02-26 01:02:56 +00002068PyObject *
2069PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002070{
2071 size_t size = strlen(u);
2072 if (size > PY_SSIZE_T_MAX) {
2073 PyErr_SetString(PyExc_OverflowError, "input too long");
2074 return NULL;
2075 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002076 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002077}
2078
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002079PyObject *
2080_PyUnicode_FromId(_Py_Identifier *id)
2081{
2082 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002083 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2084 strlen(id->string),
2085 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002086 if (!id->object)
2087 return NULL;
2088 PyUnicode_InternInPlace(&id->object);
2089 assert(!id->next);
2090 id->next = static_strings;
2091 static_strings = id;
2092 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002093 return id->object;
2094}
2095
2096void
2097_PyUnicode_ClearStaticStrings()
2098{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002099 _Py_Identifier *tmp, *s = static_strings;
2100 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002101 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002102 tmp = s->next;
2103 s->next = NULL;
2104 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002105 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002106 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002107}
2108
Benjamin Peterson0df54292012-03-26 14:50:32 -04002109/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002110
Victor Stinnerd3f08822012-05-29 12:57:52 +02002111PyObject*
2112_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002113{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002114 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002115 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002116 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002117#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002118 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002119#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002120 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002121 }
Victor Stinner785938e2011-12-11 20:09:03 +01002122 unicode = PyUnicode_New(size, 127);
2123 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002124 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002125 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2126 assert(_PyUnicode_CheckConsistency(unicode, 1));
2127 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002128}
2129
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002130static Py_UCS4
2131kind_maxchar_limit(unsigned int kind)
2132{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002133 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002134 case PyUnicode_1BYTE_KIND:
2135 return 0x80;
2136 case PyUnicode_2BYTE_KIND:
2137 return 0x100;
2138 case PyUnicode_4BYTE_KIND:
2139 return 0x10000;
2140 default:
2141 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002142 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002143 }
2144}
2145
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -07002146static inline Py_UCS4
Victor Stinnere6abb482012-05-02 01:15:40 +02002147align_maxchar(Py_UCS4 maxchar)
2148{
2149 if (maxchar <= 127)
2150 return 127;
2151 else if (maxchar <= 255)
2152 return 255;
2153 else if (maxchar <= 65535)
2154 return 65535;
2155 else
2156 return MAX_UNICODE;
2157}
2158
Victor Stinner702c7342011-10-05 13:50:52 +02002159static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002160_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002161{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002162 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002163 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002164
Serhiy Storchaka678db842013-01-26 12:16:36 +02002165 if (size == 0)
2166 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002167 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002168 if (size == 1)
2169 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002170
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002171 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002172 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 if (!res)
2174 return NULL;
2175 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002176 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002178}
2179
Victor Stinnere57b1c02011-09-28 22:20:48 +02002180static PyObject*
2181_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002182{
2183 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002184 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002185
Serhiy Storchaka678db842013-01-26 12:16:36 +02002186 if (size == 0)
2187 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002188 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002189 if (size == 1)
2190 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002191
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002192 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002193 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002194 if (!res)
2195 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002196 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002198 else {
2199 _PyUnicode_CONVERT_BYTES(
2200 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2201 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002202 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002203 return res;
2204}
2205
Victor Stinnere57b1c02011-09-28 22:20:48 +02002206static PyObject*
2207_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002208{
2209 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002210 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002211
Serhiy Storchaka678db842013-01-26 12:16:36 +02002212 if (size == 0)
2213 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002214 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002215 if (size == 1)
2216 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002217
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002218 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002219 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002220 if (!res)
2221 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002222 if (max_char < 256)
2223 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2224 PyUnicode_1BYTE_DATA(res));
2225 else if (max_char < 0x10000)
2226 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2227 PyUnicode_2BYTE_DATA(res));
2228 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002229 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002230 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002231 return res;
2232}
2233
2234PyObject*
2235PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2236{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002237 if (size < 0) {
2238 PyErr_SetString(PyExc_ValueError, "size must be positive");
2239 return NULL;
2240 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002241 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002242 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002243 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002244 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002245 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002247 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002248 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002249 PyErr_SetString(PyExc_SystemError, "invalid kind");
2250 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002252}
2253
Victor Stinnerece58de2012-04-23 23:36:38 +02002254Py_UCS4
2255_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2256{
2257 enum PyUnicode_Kind kind;
2258 void *startptr, *endptr;
2259
2260 assert(PyUnicode_IS_READY(unicode));
2261 assert(0 <= start);
2262 assert(end <= PyUnicode_GET_LENGTH(unicode));
2263 assert(start <= end);
2264
2265 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2266 return PyUnicode_MAX_CHAR_VALUE(unicode);
2267
2268 if (start == end)
2269 return 127;
2270
Victor Stinner94d558b2012-04-27 22:26:58 +02002271 if (PyUnicode_IS_ASCII(unicode))
2272 return 127;
2273
Victor Stinnerece58de2012-04-23 23:36:38 +02002274 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002275 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002276 endptr = (char *)startptr + end * kind;
2277 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002278 switch(kind) {
2279 case PyUnicode_1BYTE_KIND:
2280 return ucs1lib_find_max_char(startptr, endptr);
2281 case PyUnicode_2BYTE_KIND:
2282 return ucs2lib_find_max_char(startptr, endptr);
2283 case PyUnicode_4BYTE_KIND:
2284 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002285 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002286 assert(0);
2287 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002288 }
2289}
2290
Victor Stinner25a4b292011-10-06 12:31:55 +02002291/* Ensure that a string uses the most efficient storage, if it is not the
2292 case: create a new string with of the right kind. Write NULL into *p_unicode
2293 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002294static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002295unicode_adjust_maxchar(PyObject **p_unicode)
2296{
2297 PyObject *unicode, *copy;
2298 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002299 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002300 unsigned int kind;
2301
2302 assert(p_unicode != NULL);
2303 unicode = *p_unicode;
2304 assert(PyUnicode_IS_READY(unicode));
2305 if (PyUnicode_IS_ASCII(unicode))
2306 return;
2307
2308 len = PyUnicode_GET_LENGTH(unicode);
2309 kind = PyUnicode_KIND(unicode);
2310 if (kind == PyUnicode_1BYTE_KIND) {
2311 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002312 max_char = ucs1lib_find_max_char(u, u + len);
2313 if (max_char >= 128)
2314 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002315 }
2316 else if (kind == PyUnicode_2BYTE_KIND) {
2317 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002318 max_char = ucs2lib_find_max_char(u, u + len);
2319 if (max_char >= 256)
2320 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002321 }
2322 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002323 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002324 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002325 max_char = ucs4lib_find_max_char(u, u + len);
2326 if (max_char >= 0x10000)
2327 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002328 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002329 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002330 if (copy != NULL)
2331 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002332 Py_DECREF(unicode);
2333 *p_unicode = copy;
2334}
2335
Victor Stinner034f6cf2011-09-30 02:26:44 +02002336PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002337_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002338{
Victor Stinner87af4f22011-11-21 23:03:47 +01002339 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002340 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002341
Victor Stinner034f6cf2011-09-30 02:26:44 +02002342 if (!PyUnicode_Check(unicode)) {
2343 PyErr_BadInternalCall();
2344 return NULL;
2345 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002346 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002347 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002348
Victor Stinner87af4f22011-11-21 23:03:47 +01002349 length = PyUnicode_GET_LENGTH(unicode);
2350 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002351 if (!copy)
2352 return NULL;
2353 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2354
Christian Heimesf051e432016-09-13 20:22:02 +02002355 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002356 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002357 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002358 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002359}
2360
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002361
Victor Stinnerbc603d12011-10-02 01:00:40 +02002362/* Widen Unicode objects to larger buffers. Don't write terminating null
2363 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002364
2365void*
2366_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2367{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002368 Py_ssize_t len;
2369 void *result;
2370 unsigned int skind;
2371
Benjamin Petersonbac79492012-01-14 13:34:47 -05002372 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002373 return NULL;
2374
2375 len = PyUnicode_GET_LENGTH(s);
2376 skind = PyUnicode_KIND(s);
2377 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002378 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002379 return NULL;
2380 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002381 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002382 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002383 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002384 if (!result)
2385 return PyErr_NoMemory();
2386 assert(skind == PyUnicode_1BYTE_KIND);
2387 _PyUnicode_CONVERT_BYTES(
2388 Py_UCS1, Py_UCS2,
2389 PyUnicode_1BYTE_DATA(s),
2390 PyUnicode_1BYTE_DATA(s) + len,
2391 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002392 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002393 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002394 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002395 if (!result)
2396 return PyErr_NoMemory();
2397 if (skind == PyUnicode_2BYTE_KIND) {
2398 _PyUnicode_CONVERT_BYTES(
2399 Py_UCS2, Py_UCS4,
2400 PyUnicode_2BYTE_DATA(s),
2401 PyUnicode_2BYTE_DATA(s) + len,
2402 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002404 else {
2405 assert(skind == PyUnicode_1BYTE_KIND);
2406 _PyUnicode_CONVERT_BYTES(
2407 Py_UCS1, Py_UCS4,
2408 PyUnicode_1BYTE_DATA(s),
2409 PyUnicode_1BYTE_DATA(s) + len,
2410 result);
2411 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002413 default:
2414 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002415 }
Victor Stinner01698042011-10-04 00:04:26 +02002416 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 return NULL;
2418}
2419
2420static Py_UCS4*
2421as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2422 int copy_null)
2423{
2424 int kind;
2425 void *data;
2426 Py_ssize_t len, targetlen;
2427 if (PyUnicode_READY(string) == -1)
2428 return NULL;
2429 kind = PyUnicode_KIND(string);
2430 data = PyUnicode_DATA(string);
2431 len = PyUnicode_GET_LENGTH(string);
2432 targetlen = len;
2433 if (copy_null)
2434 targetlen++;
2435 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002436 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002437 if (!target) {
2438 PyErr_NoMemory();
2439 return NULL;
2440 }
2441 }
2442 else {
2443 if (targetsize < targetlen) {
2444 PyErr_Format(PyExc_SystemError,
2445 "string is longer than the buffer");
2446 if (copy_null && 0 < targetsize)
2447 target[0] = 0;
2448 return NULL;
2449 }
2450 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002451 if (kind == PyUnicode_1BYTE_KIND) {
2452 Py_UCS1 *start = (Py_UCS1 *) data;
2453 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002454 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002455 else if (kind == PyUnicode_2BYTE_KIND) {
2456 Py_UCS2 *start = (Py_UCS2 *) data;
2457 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2458 }
2459 else {
2460 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002461 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002462 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002463 if (copy_null)
2464 target[len] = 0;
2465 return target;
2466}
2467
2468Py_UCS4*
2469PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2470 int copy_null)
2471{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002472 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002473 PyErr_BadInternalCall();
2474 return NULL;
2475 }
2476 return as_ucs4(string, target, targetsize, copy_null);
2477}
2478
2479Py_UCS4*
2480PyUnicode_AsUCS4Copy(PyObject *string)
2481{
2482 return as_ucs4(string, NULL, 0, 1);
2483}
2484
2485#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002486
Alexander Belopolsky40018472011-02-26 01:02:56 +00002487PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002488PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002489{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002490 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002491 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002492 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002493 PyErr_BadInternalCall();
2494 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002495 }
2496
Martin v. Löwis790465f2008-04-05 20:41:37 +00002497 if (size == -1) {
2498 size = wcslen(w);
2499 }
2500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002501 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002502}
2503
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002504#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002505
Victor Stinner15a11362012-10-06 23:48:20 +02002506/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002507 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2508 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2509#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002510
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002511static int
2512unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2513 Py_ssize_t width, Py_ssize_t precision)
2514{
2515 Py_ssize_t length, fill, arglen;
2516 Py_UCS4 maxchar;
2517
2518 if (PyUnicode_READY(str) == -1)
2519 return -1;
2520
2521 length = PyUnicode_GET_LENGTH(str);
2522 if ((precision == -1 || precision >= length)
2523 && width <= length)
2524 return _PyUnicodeWriter_WriteStr(writer, str);
2525
2526 if (precision != -1)
2527 length = Py_MIN(precision, length);
2528
2529 arglen = Py_MAX(length, width);
2530 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2531 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2532 else
2533 maxchar = writer->maxchar;
2534
2535 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2536 return -1;
2537
2538 if (width > length) {
2539 fill = width - length;
2540 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2541 return -1;
2542 writer->pos += fill;
2543 }
2544
2545 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2546 str, 0, length);
2547 writer->pos += length;
2548 return 0;
2549}
2550
2551static int
2552unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2553 Py_ssize_t width, Py_ssize_t precision)
2554{
2555 /* UTF-8 */
2556 Py_ssize_t length;
2557 PyObject *unicode;
2558 int res;
2559
2560 length = strlen(str);
2561 if (precision != -1)
2562 length = Py_MIN(length, precision);
2563 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2564 if (unicode == NULL)
2565 return -1;
2566
2567 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2568 Py_DECREF(unicode);
2569 return res;
2570}
2571
Victor Stinner96865452011-03-01 23:44:09 +00002572static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002573unicode_fromformat_arg(_PyUnicodeWriter *writer,
2574 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002575{
Victor Stinnere215d962012-10-06 23:03:36 +02002576 const char *p;
2577 Py_ssize_t len;
2578 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002579 Py_ssize_t width;
2580 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002581 int longflag;
2582 int longlongflag;
2583 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002584 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002585
2586 p = f;
2587 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002588 zeropad = 0;
2589 if (*f == '0') {
2590 zeropad = 1;
2591 f++;
2592 }
Victor Stinner96865452011-03-01 23:44:09 +00002593
2594 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 width = -1;
2596 if (Py_ISDIGIT((unsigned)*f)) {
2597 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002598 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002599 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002600 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002601 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002602 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002603 return NULL;
2604 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002605 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002606 f++;
2607 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002608 }
2609 precision = -1;
2610 if (*f == '.') {
2611 f++;
2612 if (Py_ISDIGIT((unsigned)*f)) {
2613 precision = (*f - '0');
2614 f++;
2615 while (Py_ISDIGIT((unsigned)*f)) {
2616 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2617 PyErr_SetString(PyExc_ValueError,
2618 "precision too big");
2619 return NULL;
2620 }
2621 precision = (precision * 10) + (*f - '0');
2622 f++;
2623 }
2624 }
Victor Stinner96865452011-03-01 23:44:09 +00002625 if (*f == '%') {
2626 /* "%.3%s" => f points to "3" */
2627 f--;
2628 }
2629 }
2630 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002631 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002632 f--;
2633 }
Victor Stinner96865452011-03-01 23:44:09 +00002634
2635 /* Handle %ld, %lu, %lld and %llu. */
2636 longflag = 0;
2637 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002638 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002639 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002640 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002641 longflag = 1;
2642 ++f;
2643 }
Victor Stinner96865452011-03-01 23:44:09 +00002644 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002645 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002646 longlongflag = 1;
2647 f += 2;
2648 }
Victor Stinner96865452011-03-01 23:44:09 +00002649 }
2650 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002651 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002652 size_tflag = 1;
2653 ++f;
2654 }
Victor Stinnere215d962012-10-06 23:03:36 +02002655
2656 if (f[1] == '\0')
2657 writer->overallocate = 0;
2658
2659 switch (*f) {
2660 case 'c':
2661 {
2662 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002663 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002664 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002665 "character argument not in range(0x110000)");
2666 return NULL;
2667 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002668 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002669 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002670 break;
2671 }
2672
2673 case 'i':
2674 case 'd':
2675 case 'u':
2676 case 'x':
2677 {
2678 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002679 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002680 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002681
2682 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002683 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002684 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002685 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002686 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002687 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002688 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002689 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002690 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002691 va_arg(*vargs, size_t));
2692 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002693 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002694 va_arg(*vargs, unsigned int));
2695 }
2696 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002697 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002698 }
2699 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002700 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002701 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002702 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002703 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002704 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002705 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002706 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002707 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002708 va_arg(*vargs, Py_ssize_t));
2709 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002710 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002711 va_arg(*vargs, int));
2712 }
2713 assert(len >= 0);
2714
Victor Stinnere215d962012-10-06 23:03:36 +02002715 if (precision < len)
2716 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002717
2718 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002719 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2720 return NULL;
2721
Victor Stinnere215d962012-10-06 23:03:36 +02002722 if (width > precision) {
2723 Py_UCS4 fillchar;
2724 fill = width - precision;
2725 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002726 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2727 return NULL;
2728 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002729 }
Victor Stinner15a11362012-10-06 23:48:20 +02002730 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002731 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002732 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2733 return NULL;
2734 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002735 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002736
Victor Stinner4a587072013-11-19 12:54:53 +01002737 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2738 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002739 break;
2740 }
2741
2742 case 'p':
2743 {
2744 char number[MAX_LONG_LONG_CHARS];
2745
2746 len = sprintf(number, "%p", va_arg(*vargs, void*));
2747 assert(len >= 0);
2748
2749 /* %p is ill-defined: ensure leading 0x. */
2750 if (number[1] == 'X')
2751 number[1] = 'x';
2752 else if (number[1] != 'x') {
2753 memmove(number + 2, number,
2754 strlen(number) + 1);
2755 number[0] = '0';
2756 number[1] = 'x';
2757 len += 2;
2758 }
2759
Victor Stinner4a587072013-11-19 12:54:53 +01002760 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002761 return NULL;
2762 break;
2763 }
2764
2765 case 's':
2766 {
2767 /* UTF-8 */
2768 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002769 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002770 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002771 break;
2772 }
2773
2774 case 'U':
2775 {
2776 PyObject *obj = va_arg(*vargs, PyObject *);
2777 assert(obj && _PyUnicode_CHECK(obj));
2778
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002779 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002780 return NULL;
2781 break;
2782 }
2783
2784 case 'V':
2785 {
2786 PyObject *obj = va_arg(*vargs, PyObject *);
2787 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002788 if (obj) {
2789 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002790 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002791 return NULL;
2792 }
2793 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002794 assert(str != NULL);
2795 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002796 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002797 }
2798 break;
2799 }
2800
2801 case 'S':
2802 {
2803 PyObject *obj = va_arg(*vargs, PyObject *);
2804 PyObject *str;
2805 assert(obj);
2806 str = PyObject_Str(obj);
2807 if (!str)
2808 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002809 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002810 Py_DECREF(str);
2811 return NULL;
2812 }
2813 Py_DECREF(str);
2814 break;
2815 }
2816
2817 case 'R':
2818 {
2819 PyObject *obj = va_arg(*vargs, PyObject *);
2820 PyObject *repr;
2821 assert(obj);
2822 repr = PyObject_Repr(obj);
2823 if (!repr)
2824 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002825 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002826 Py_DECREF(repr);
2827 return NULL;
2828 }
2829 Py_DECREF(repr);
2830 break;
2831 }
2832
2833 case 'A':
2834 {
2835 PyObject *obj = va_arg(*vargs, PyObject *);
2836 PyObject *ascii;
2837 assert(obj);
2838 ascii = PyObject_ASCII(obj);
2839 if (!ascii)
2840 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002841 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002842 Py_DECREF(ascii);
2843 return NULL;
2844 }
2845 Py_DECREF(ascii);
2846 break;
2847 }
2848
2849 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002850 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002851 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002852 break;
2853
2854 default:
2855 /* if we stumble upon an unknown formatting code, copy the rest
2856 of the format string to the output string. (we cannot just
2857 skip the code, since there's no way to know what's in the
2858 argument list) */
2859 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002860 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002861 return NULL;
2862 f = p+len;
2863 return f;
2864 }
2865
2866 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002867 return f;
2868}
2869
Walter Dörwaldd2034312007-05-18 16:29:38 +00002870PyObject *
2871PyUnicode_FromFormatV(const char *format, va_list vargs)
2872{
Victor Stinnere215d962012-10-06 23:03:36 +02002873 va_list vargs2;
2874 const char *f;
2875 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002876
Victor Stinner8f674cc2013-04-17 23:02:17 +02002877 _PyUnicodeWriter_Init(&writer);
2878 writer.min_length = strlen(format) + 100;
2879 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002880
Benjamin Peterson0c212142016-09-20 20:39:33 -07002881 // Copy varags to be able to pass a reference to a subfunction.
2882 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002883
2884 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002885 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002886 f = unicode_fromformat_arg(&writer, f, &vargs2);
2887 if (f == NULL)
2888 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002889 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002890 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002891 const char *p;
2892 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002893
Victor Stinnere215d962012-10-06 23:03:36 +02002894 p = f;
2895 do
2896 {
2897 if ((unsigned char)*p > 127) {
2898 PyErr_Format(PyExc_ValueError,
2899 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2900 "string, got a non-ASCII byte: 0x%02x",
2901 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002902 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002903 }
2904 p++;
2905 }
2906 while (*p != '\0' && *p != '%');
2907 len = p - f;
2908
2909 if (*p == '\0')
2910 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002911
2912 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002913 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002914
2915 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002916 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002918 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002919 return _PyUnicodeWriter_Finish(&writer);
2920
2921 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002922 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002923 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002924 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002925}
2926
Walter Dörwaldd2034312007-05-18 16:29:38 +00002927PyObject *
2928PyUnicode_FromFormat(const char *format, ...)
2929{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002930 PyObject* ret;
2931 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002932
2933#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002934 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002935#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002936 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002937#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002938 ret = PyUnicode_FromFormatV(format, vargs);
2939 va_end(vargs);
2940 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002941}
2942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002943#ifdef HAVE_WCHAR_H
2944
Victor Stinner5593d8a2010-10-02 11:11:27 +00002945/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2946 convert a Unicode object to a wide character string.
2947
Victor Stinnerd88d9832011-09-06 02:00:05 +02002948 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002949 character) required to convert the unicode object. Ignore size argument.
2950
Victor Stinnerd88d9832011-09-06 02:00:05 +02002951 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002952 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002953 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002954static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002955unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002956 wchar_t *w,
2957 Py_ssize_t size)
2958{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002959 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002960 const wchar_t *wstr;
2961
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002962 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002963 if (wstr == NULL)
2964 return -1;
2965
Victor Stinner5593d8a2010-10-02 11:11:27 +00002966 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002967 if (size > res)
2968 size = res + 1;
2969 else
2970 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002971 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002972 return res;
2973 }
2974 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002975 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002976}
2977
2978Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002979PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002980 wchar_t *w,
2981 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002982{
2983 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002984 PyErr_BadInternalCall();
2985 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002986 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002987 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002988}
2989
Victor Stinner137c34c2010-09-29 10:25:54 +00002990wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002991PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002992 Py_ssize_t *size)
2993{
2994 wchar_t* buffer;
2995 Py_ssize_t buflen;
2996
2997 if (unicode == NULL) {
2998 PyErr_BadInternalCall();
2999 return NULL;
3000 }
3001
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003002 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003003 if (buflen == -1)
3004 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003005 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00003006 if (buffer == NULL) {
3007 PyErr_NoMemory();
3008 return NULL;
3009 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003010 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02003011 if (buflen == -1) {
3012 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003013 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02003014 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00003015 if (size != NULL)
3016 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003017 return buffer;
3018}
3019
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003020#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003021
Alexander Belopolsky40018472011-02-26 01:02:56 +00003022PyObject *
3023PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003024{
Victor Stinner8faf8212011-12-08 22:14:11 +01003025 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003026 PyErr_SetString(PyExc_ValueError,
3027 "chr() arg not in range(0x110000)");
3028 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003029 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003030
Victor Stinner985a82a2014-01-03 12:53:47 +01003031 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003032}
3033
Alexander Belopolsky40018472011-02-26 01:02:56 +00003034PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003035PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003036{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003037 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003038 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003039 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003040 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003041 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003042 Py_INCREF(obj);
3043 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003044 }
3045 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003046 /* For a Unicode subtype that's not a Unicode object,
3047 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003048 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003049 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003050 PyErr_Format(PyExc_TypeError,
3051 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003052 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003053 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003054}
3055
Alexander Belopolsky40018472011-02-26 01:02:56 +00003056PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003057PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003058 const char *encoding,
3059 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003060{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003061 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003062 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003063
Guido van Rossumd57fd912000-03-10 22:53:23 +00003064 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003065 PyErr_BadInternalCall();
3066 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003067 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003068
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003069 /* Decoding bytes objects is the most common case and should be fast */
3070 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003071 if (PyBytes_GET_SIZE(obj) == 0)
3072 _Py_RETURN_UNICODE_EMPTY();
3073 v = PyUnicode_Decode(
3074 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3075 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003076 return v;
3077 }
3078
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003079 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003080 PyErr_SetString(PyExc_TypeError,
3081 "decoding str is not supported");
3082 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003083 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003084
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003085 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3086 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3087 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003088 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003089 Py_TYPE(obj)->tp_name);
3090 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003091 }
Tim Petersced69f82003-09-16 20:30:58 +00003092
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003093 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003094 PyBuffer_Release(&buffer);
3095 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003096 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003097
Serhiy Storchaka05997252013-01-26 12:14:02 +02003098 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003099 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003100 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003101}
3102
Victor Stinnerebe17e02016-10-12 13:57:45 +02003103/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3104 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3105 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003106int
3107_Py_normalize_encoding(const char *encoding,
3108 char *lower,
3109 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003110{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003111 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003112 char *l;
3113 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003114 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003115
Victor Stinner942889a2016-09-05 15:40:10 -07003116 assert(encoding != NULL);
3117
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003118 e = encoding;
3119 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003120 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003121 punct = 0;
3122 while (1) {
3123 char c = *e;
3124 if (c == 0) {
3125 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003126 }
Victor Stinner942889a2016-09-05 15:40:10 -07003127
3128 if (Py_ISALNUM(c) || c == '.') {
3129 if (punct && l != lower) {
3130 if (l == l_end) {
3131 return 0;
3132 }
3133 *l++ = '_';
3134 }
3135 punct = 0;
3136
3137 if (l == l_end) {
3138 return 0;
3139 }
3140 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003141 }
3142 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003143 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003144 }
Victor Stinner942889a2016-09-05 15:40:10 -07003145
3146 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003147 }
3148 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003149 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003150}
3151
Alexander Belopolsky40018472011-02-26 01:02:56 +00003152PyObject *
3153PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003154 Py_ssize_t size,
3155 const char *encoding,
3156 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003157{
3158 PyObject *buffer = NULL, *unicode;
3159 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003160 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3161
3162 if (encoding == NULL) {
3163 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3164 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003165
Fred Drakee4315f52000-05-09 19:53:39 +00003166 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003167 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3168 char *lower = buflower;
3169
3170 /* Fast paths */
3171 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3172 lower += 3;
3173 if (*lower == '_') {
3174 /* Match "utf8" and "utf_8" */
3175 lower++;
3176 }
3177
3178 if (lower[0] == '8' && lower[1] == 0) {
3179 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3180 }
3181 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3182 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3183 }
3184 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3185 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3186 }
3187 }
3188 else {
3189 if (strcmp(lower, "ascii") == 0
3190 || strcmp(lower, "us_ascii") == 0) {
3191 return PyUnicode_DecodeASCII(s, size, errors);
3192 }
Steve Dowercc16be82016-09-08 10:35:16 -07003193 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003194 else if (strcmp(lower, "mbcs") == 0) {
3195 return PyUnicode_DecodeMBCS(s, size, errors);
3196 }
3197 #endif
3198 else if (strcmp(lower, "latin1") == 0
3199 || strcmp(lower, "latin_1") == 0
3200 || strcmp(lower, "iso_8859_1") == 0
3201 || strcmp(lower, "iso8859_1") == 0) {
3202 return PyUnicode_DecodeLatin1(s, size, errors);
3203 }
3204 }
Victor Stinner37296e82010-06-10 13:36:23 +00003205 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003206
3207 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003208 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003209 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003210 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003211 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003212 if (buffer == NULL)
3213 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003214 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003215 if (unicode == NULL)
3216 goto onError;
3217 if (!PyUnicode_Check(unicode)) {
3218 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003219 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3220 "use codecs.decode() to decode to arbitrary types",
3221 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003222 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003223 Py_DECREF(unicode);
3224 goto onError;
3225 }
3226 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003227 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003228
Benjamin Peterson29060642009-01-31 22:14:21 +00003229 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003230 Py_XDECREF(buffer);
3231 return NULL;
3232}
3233
Alexander Belopolsky40018472011-02-26 01:02:56 +00003234PyObject *
3235PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003236 const char *encoding,
3237 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003238{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003239 if (!PyUnicode_Check(unicode)) {
3240 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003241 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003242 }
3243
Serhiy Storchaka00939072016-10-27 21:05:49 +03003244 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3245 "PyUnicode_AsDecodedObject() is deprecated; "
3246 "use PyCodec_Decode() to decode from str", 1) < 0)
3247 return NULL;
3248
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003249 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003250 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003251
3252 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003253 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003254}
3255
Alexander Belopolsky40018472011-02-26 01:02:56 +00003256PyObject *
3257PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003258 const char *encoding,
3259 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003260{
3261 PyObject *v;
3262
3263 if (!PyUnicode_Check(unicode)) {
3264 PyErr_BadArgument();
3265 goto onError;
3266 }
3267
Serhiy Storchaka00939072016-10-27 21:05:49 +03003268 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3269 "PyUnicode_AsDecodedUnicode() is deprecated; "
3270 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3271 return NULL;
3272
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003273 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003274 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003275
3276 /* Decode via the codec registry */
3277 v = PyCodec_Decode(unicode, encoding, errors);
3278 if (v == NULL)
3279 goto onError;
3280 if (!PyUnicode_Check(v)) {
3281 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003282 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3283 "use codecs.decode() to decode to arbitrary types",
3284 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003285 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003286 Py_DECREF(v);
3287 goto onError;
3288 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003289 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003290
Benjamin Peterson29060642009-01-31 22:14:21 +00003291 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003292 return NULL;
3293}
3294
Alexander Belopolsky40018472011-02-26 01:02:56 +00003295PyObject *
3296PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003297 Py_ssize_t size,
3298 const char *encoding,
3299 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003300{
3301 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003302
Guido van Rossumd57fd912000-03-10 22:53:23 +00003303 unicode = PyUnicode_FromUnicode(s, size);
3304 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003305 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003306 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3307 Py_DECREF(unicode);
3308 return v;
3309}
3310
Alexander Belopolsky40018472011-02-26 01:02:56 +00003311PyObject *
3312PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003313 const char *encoding,
3314 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003315{
3316 PyObject *v;
3317
3318 if (!PyUnicode_Check(unicode)) {
3319 PyErr_BadArgument();
3320 goto onError;
3321 }
3322
Serhiy Storchaka00939072016-10-27 21:05:49 +03003323 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3324 "PyUnicode_AsEncodedObject() is deprecated; "
3325 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3326 "or PyCodec_Encode() for generic encoding", 1) < 0)
3327 return NULL;
3328
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003329 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003330 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003331
3332 /* Encode via the codec registry */
3333 v = PyCodec_Encode(unicode, encoding, errors);
3334 if (v == NULL)
3335 goto onError;
3336 return v;
3337
Benjamin Peterson29060642009-01-31 22:14:21 +00003338 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003339 return NULL;
3340}
3341
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003342static size_t
3343wcstombs_errorpos(const wchar_t *wstr)
3344{
3345 size_t len;
3346#if SIZEOF_WCHAR_T == 2
3347 wchar_t buf[3];
3348#else
3349 wchar_t buf[2];
3350#endif
3351 char outbuf[MB_LEN_MAX];
3352 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003353
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003354#if SIZEOF_WCHAR_T == 2
3355 buf[2] = 0;
3356#else
3357 buf[1] = 0;
3358#endif
3359 start = wstr;
3360 while (*wstr != L'\0')
3361 {
3362 previous = wstr;
3363#if SIZEOF_WCHAR_T == 2
3364 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3365 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3366 {
3367 buf[0] = wstr[0];
3368 buf[1] = wstr[1];
3369 wstr += 2;
3370 }
3371 else {
3372 buf[0] = *wstr;
3373 buf[1] = 0;
3374 wstr++;
3375 }
3376#else
3377 buf[0] = *wstr;
3378 wstr++;
3379#endif
3380 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003381 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003382 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003383 }
3384
3385 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003386 return 0;
3387}
3388
Victor Stinner1b579672011-12-17 05:47:23 +01003389static int
3390locale_error_handler(const char *errors, int *surrogateescape)
3391{
Victor Stinner50149202015-09-22 00:26:54 +02003392 _Py_error_handler error_handler = get_error_handler(errors);
3393 switch (error_handler)
3394 {
3395 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003396 *surrogateescape = 0;
3397 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003398 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003399 *surrogateescape = 1;
3400 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003401 default:
3402 PyErr_Format(PyExc_ValueError,
3403 "only 'strict' and 'surrogateescape' error handlers "
3404 "are supported, not '%s'",
3405 errors);
3406 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003407 }
Victor Stinner1b579672011-12-17 05:47:23 +01003408}
3409
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003410PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003411PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003412{
3413 Py_ssize_t wlen, wlen2;
3414 wchar_t *wstr;
3415 PyObject *bytes = NULL;
3416 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003417 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003418 PyObject *exc;
3419 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003420 int surrogateescape;
3421
3422 if (locale_error_handler(errors, &surrogateescape) < 0)
3423 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003424
3425 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3426 if (wstr == NULL)
3427 return NULL;
3428
3429 wlen2 = wcslen(wstr);
3430 if (wlen2 != wlen) {
3431 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003432 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003433 return NULL;
3434 }
3435
3436 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003437 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003438 char *str;
3439
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003440 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003441 if (str == NULL) {
3442 if (error_pos == (size_t)-1) {
3443 PyErr_NoMemory();
3444 PyMem_Free(wstr);
3445 return NULL;
3446 }
3447 else {
3448 goto encode_error;
3449 }
3450 }
3451 PyMem_Free(wstr);
3452
3453 bytes = PyBytes_FromString(str);
3454 PyMem_Free(str);
3455 }
3456 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003457 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003458 size_t len, len2;
3459
3460 len = wcstombs(NULL, wstr, 0);
3461 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003462 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003463 goto encode_error;
3464 }
3465
3466 bytes = PyBytes_FromStringAndSize(NULL, len);
3467 if (bytes == NULL) {
3468 PyMem_Free(wstr);
3469 return NULL;
3470 }
3471
3472 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3473 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003474 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003475 goto encode_error;
3476 }
3477 PyMem_Free(wstr);
3478 }
3479 return bytes;
3480
3481encode_error:
3482 errmsg = strerror(errno);
3483 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003484
3485 if (error_pos == (size_t)-1)
3486 error_pos = wcstombs_errorpos(wstr);
3487
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003488 PyMem_Free(wstr);
3489 Py_XDECREF(bytes);
3490
Victor Stinner2f197072011-12-17 07:08:30 +01003491 if (errmsg != NULL) {
3492 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003493 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003494 if (wstr != NULL) {
3495 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003496 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003497 } else
3498 errmsg = NULL;
3499 }
3500 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003501 reason = PyUnicode_FromString(
3502 "wcstombs() encountered an unencodable "
3503 "wide character");
3504 if (reason == NULL)
3505 return NULL;
3506
3507 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3508 "locale", unicode,
3509 (Py_ssize_t)error_pos,
3510 (Py_ssize_t)(error_pos+1),
3511 reason);
3512 Py_DECREF(reason);
3513 if (exc != NULL) {
3514 PyCodec_StrictErrors(exc);
3515 Py_XDECREF(exc);
3516 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003517 return NULL;
3518}
3519
Victor Stinnerad158722010-10-27 00:25:46 +00003520PyObject *
3521PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003522{
Steve Dowercc16be82016-09-08 10:35:16 -07003523#if defined(__APPLE__)
3524 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003525#else
Victor Stinner793b5312011-04-27 00:24:21 +02003526 PyInterpreterState *interp = PyThreadState_GET()->interp;
3527 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3528 cannot use it to encode and decode filenames before it is loaded. Load
3529 the Python codec requires to encode at least its own filename. Use the C
3530 version of the locale codec until the codec registry is initialized and
3531 the Python codec is loaded.
3532
3533 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3534 cannot only rely on it: check also interp->fscodec_initialized for
3535 subinterpreters. */
3536 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003537 return PyUnicode_AsEncodedString(unicode,
3538 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003539 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003540 }
3541 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003542 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003543 }
Victor Stinnerad158722010-10-27 00:25:46 +00003544#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003545}
3546
Alexander Belopolsky40018472011-02-26 01:02:56 +00003547PyObject *
3548PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003549 const char *encoding,
3550 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003551{
3552 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003553 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003554
Guido van Rossumd57fd912000-03-10 22:53:23 +00003555 if (!PyUnicode_Check(unicode)) {
3556 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003557 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003558 }
Fred Drakee4315f52000-05-09 19:53:39 +00003559
Victor Stinner942889a2016-09-05 15:40:10 -07003560 if (encoding == NULL) {
3561 return _PyUnicode_AsUTF8String(unicode, errors);
3562 }
3563
Fred Drakee4315f52000-05-09 19:53:39 +00003564 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003565 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3566 char *lower = buflower;
3567
3568 /* Fast paths */
3569 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3570 lower += 3;
3571 if (*lower == '_') {
3572 /* Match "utf8" and "utf_8" */
3573 lower++;
3574 }
3575
3576 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003577 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003578 }
3579 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3580 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3581 }
3582 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3583 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3584 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003585 }
Victor Stinner942889a2016-09-05 15:40:10 -07003586 else {
3587 if (strcmp(lower, "ascii") == 0
3588 || strcmp(lower, "us_ascii") == 0) {
3589 return _PyUnicode_AsASCIIString(unicode, errors);
3590 }
Steve Dowercc16be82016-09-08 10:35:16 -07003591#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003592 else if (strcmp(lower, "mbcs") == 0) {
3593 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3594 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003595#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003596 else if (strcmp(lower, "latin1") == 0 ||
3597 strcmp(lower, "latin_1") == 0 ||
3598 strcmp(lower, "iso_8859_1") == 0 ||
3599 strcmp(lower, "iso8859_1") == 0) {
3600 return _PyUnicode_AsLatin1String(unicode, errors);
3601 }
3602 }
Victor Stinner37296e82010-06-10 13:36:23 +00003603 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003604
3605 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003606 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003607 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003608 return NULL;
3609
3610 /* The normal path */
3611 if (PyBytes_Check(v))
3612 return v;
3613
3614 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003615 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003616 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003617 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003618
3619 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003620 "encoder %s returned bytearray instead of bytes; "
3621 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003622 encoding);
3623 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003624 Py_DECREF(v);
3625 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003626 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003627
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003628 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3629 Py_DECREF(v);
3630 return b;
3631 }
3632
3633 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003634 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3635 "use codecs.encode() to encode to arbitrary types",
3636 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003637 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003638 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003639 return NULL;
3640}
3641
Alexander Belopolsky40018472011-02-26 01:02:56 +00003642PyObject *
3643PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003644 const char *encoding,
3645 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003646{
3647 PyObject *v;
3648
3649 if (!PyUnicode_Check(unicode)) {
3650 PyErr_BadArgument();
3651 goto onError;
3652 }
3653
Serhiy Storchaka00939072016-10-27 21:05:49 +03003654 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3655 "PyUnicode_AsEncodedUnicode() is deprecated; "
3656 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3657 return NULL;
3658
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003659 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003660 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003661
3662 /* Encode via the codec registry */
3663 v = PyCodec_Encode(unicode, encoding, errors);
3664 if (v == NULL)
3665 goto onError;
3666 if (!PyUnicode_Check(v)) {
3667 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003668 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3669 "use codecs.encode() to encode to arbitrary types",
3670 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003671 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003672 Py_DECREF(v);
3673 goto onError;
3674 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003675 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003676
Benjamin Peterson29060642009-01-31 22:14:21 +00003677 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003678 return NULL;
3679}
3680
Victor Stinner2f197072011-12-17 07:08:30 +01003681static size_t
3682mbstowcs_errorpos(const char *str, size_t len)
3683{
3684#ifdef HAVE_MBRTOWC
3685 const char *start = str;
3686 mbstate_t mbs;
3687 size_t converted;
3688 wchar_t ch;
3689
3690 memset(&mbs, 0, sizeof mbs);
3691 while (len)
3692 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003693 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003694 if (converted == 0)
3695 /* Reached end of string */
3696 break;
3697 if (converted == (size_t)-1 || converted == (size_t)-2) {
3698 /* Conversion error or incomplete character */
3699 return str - start;
3700 }
3701 else {
3702 str += converted;
3703 len -= converted;
3704 }
3705 }
3706 /* failed to find the undecodable byte sequence */
3707 return 0;
3708#endif
3709 return 0;
3710}
3711
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003712PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003713PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003714 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003715{
3716 wchar_t smallbuf[256];
3717 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3718 wchar_t *wstr;
3719 size_t wlen, wlen2;
3720 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003721 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003722 size_t error_pos;
3723 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003724 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3725 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003726
3727 if (locale_error_handler(errors, &surrogateescape) < 0)
3728 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003729
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003730 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3731 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003732 return NULL;
3733 }
3734
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003735 if (surrogateescape) {
3736 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003737 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003738 if (wstr == NULL) {
3739 if (wlen == (size_t)-1)
3740 PyErr_NoMemory();
3741 else
3742 PyErr_SetFromErrno(PyExc_OSError);
3743 return NULL;
3744 }
3745
3746 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003747 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003748 }
3749 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003750 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003751#ifndef HAVE_BROKEN_MBSTOWCS
3752 wlen = mbstowcs(NULL, str, 0);
3753#else
3754 wlen = len;
3755#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003756 if (wlen == (size_t)-1)
3757 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003758 if (wlen+1 <= smallbuf_len) {
3759 wstr = smallbuf;
3760 }
3761 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003762 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003763 if (!wstr)
3764 return PyErr_NoMemory();
3765 }
3766
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003767 wlen2 = mbstowcs(wstr, str, wlen+1);
3768 if (wlen2 == (size_t)-1) {
3769 if (wstr != smallbuf)
3770 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003771 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003772 }
3773#ifdef HAVE_BROKEN_MBSTOWCS
3774 assert(wlen2 == wlen);
3775#endif
3776 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3777 if (wstr != smallbuf)
3778 PyMem_Free(wstr);
3779 }
3780 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003781
3782decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003783 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003784 errmsg = strerror(errno);
3785 assert(errmsg != NULL);
3786
3787 error_pos = mbstowcs_errorpos(str, len);
3788 if (errmsg != NULL) {
3789 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003790 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003791 if (wstr != NULL) {
3792 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003793 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003794 }
Victor Stinner2f197072011-12-17 07:08:30 +01003795 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003796 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003797 reason = PyUnicode_FromString(
3798 "mbstowcs() encountered an invalid multibyte sequence");
3799 if (reason == NULL)
3800 return NULL;
3801
3802 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3803 "locale", str, len,
3804 (Py_ssize_t)error_pos,
3805 (Py_ssize_t)(error_pos+1),
3806 reason);
3807 Py_DECREF(reason);
3808 if (exc != NULL) {
3809 PyCodec_StrictErrors(exc);
3810 Py_XDECREF(exc);
3811 }
3812 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003813}
3814
3815PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003816PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003817{
3818 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003819 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003820}
3821
3822
3823PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003824PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003825 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003826 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3827}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003828
Christian Heimes5894ba72007-11-04 11:43:14 +00003829PyObject*
3830PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3831{
Steve Dowercc16be82016-09-08 10:35:16 -07003832#if defined(__APPLE__)
3833 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003834#else
Victor Stinner793b5312011-04-27 00:24:21 +02003835 PyInterpreterState *interp = PyThreadState_GET()->interp;
3836 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3837 cannot use it to encode and decode filenames before it is loaded. Load
3838 the Python codec requires to encode at least its own filename. Use the C
3839 version of the locale codec until the codec registry is initialized and
3840 the Python codec is loaded.
3841
3842 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3843 cannot only rely on it: check also interp->fscodec_initialized for
3844 subinterpreters. */
3845 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003846 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003847 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003848 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003849 }
3850 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003851 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003852 }
Victor Stinnerad158722010-10-27 00:25:46 +00003853#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003854}
3855
Martin v. Löwis011e8422009-05-05 04:43:17 +00003856
3857int
3858PyUnicode_FSConverter(PyObject* arg, void* addr)
3859{
Brett Cannonec6ce872016-09-06 15:50:29 -07003860 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003861 PyObject *output = NULL;
3862 Py_ssize_t size;
3863 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003864 if (arg == NULL) {
3865 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003866 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003867 return 1;
3868 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003869 path = PyOS_FSPath(arg);
3870 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003871 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003872 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003873 if (PyBytes_Check(path)) {
3874 output = path;
3875 }
3876 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3877 output = PyUnicode_EncodeFSDefault(path);
3878 Py_DECREF(path);
3879 if (!output) {
3880 return 0;
3881 }
3882 assert(PyBytes_Check(output));
3883 }
3884
Victor Stinner0ea2a462010-04-30 00:22:08 +00003885 size = PyBytes_GET_SIZE(output);
3886 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003887 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003888 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003889 Py_DECREF(output);
3890 return 0;
3891 }
3892 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003893 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003894}
3895
3896
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003897int
3898PyUnicode_FSDecoder(PyObject* arg, void* addr)
3899{
Brett Cannona5711202016-09-06 19:36:01 -07003900 int is_buffer = 0;
3901 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003902 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003903 if (arg == NULL) {
3904 Py_DECREF(*(PyObject**)addr);
3905 return 1;
3906 }
Brett Cannona5711202016-09-06 19:36:01 -07003907
3908 is_buffer = PyObject_CheckBuffer(arg);
3909 if (!is_buffer) {
3910 path = PyOS_FSPath(arg);
3911 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003912 return 0;
3913 }
Brett Cannona5711202016-09-06 19:36:01 -07003914 }
3915 else {
3916 path = arg;
3917 Py_INCREF(arg);
3918 }
3919
3920 if (PyUnicode_Check(path)) {
3921 if (PyUnicode_READY(path) == -1) {
3922 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003923 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003924 }
3925 output = path;
3926 }
3927 else if (PyBytes_Check(path) || is_buffer) {
3928 PyObject *path_bytes = NULL;
3929
3930 if (!PyBytes_Check(path) &&
3931 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3932 "path should be string, bytes, or os.PathLike, not %.200s",
3933 Py_TYPE(arg)->tp_name)) {
3934 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003935 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003936 }
3937 path_bytes = PyBytes_FromObject(path);
3938 Py_DECREF(path);
3939 if (!path_bytes) {
3940 return 0;
3941 }
3942 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3943 PyBytes_GET_SIZE(path_bytes));
3944 Py_DECREF(path_bytes);
3945 if (!output) {
3946 return 0;
3947 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003948 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003949 else {
3950 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003951 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003952 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003953 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003954 return 0;
3955 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003956 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003957 Py_DECREF(output);
3958 return 0;
3959 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003960 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003961 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003962 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003963 Py_DECREF(output);
3964 return 0;
3965 }
3966 *(PyObject**)addr = output;
3967 return Py_CLEANUP_SUPPORTED;
3968}
3969
3970
Martin v. Löwis5b222132007-06-10 09:51:05 +00003971char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003972PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003973{
Christian Heimesf3863112007-11-22 07:46:41 +00003974 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003975
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003976 if (!PyUnicode_Check(unicode)) {
3977 PyErr_BadArgument();
3978 return NULL;
3979 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003980 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003981 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003982
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003983 if (PyUnicode_UTF8(unicode) == NULL) {
3984 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003985 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003986 if (bytes == NULL)
3987 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003988 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3989 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003990 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003991 Py_DECREF(bytes);
3992 return NULL;
3993 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003994 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003995 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003996 PyBytes_AS_STRING(bytes),
3997 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003998 Py_DECREF(bytes);
3999 }
4000
4001 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004002 *psize = PyUnicode_UTF8_LENGTH(unicode);
4003 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004004}
4005
4006char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004007PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004008{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004009 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4010}
4011
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004012Py_UNICODE *
4013PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4014{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004015 const unsigned char *one_byte;
4016#if SIZEOF_WCHAR_T == 4
4017 const Py_UCS2 *two_bytes;
4018#else
4019 const Py_UCS4 *four_bytes;
4020 const Py_UCS4 *ucs4_end;
4021 Py_ssize_t num_surrogates;
4022#endif
4023 wchar_t *w;
4024 wchar_t *wchar_end;
4025
4026 if (!PyUnicode_Check(unicode)) {
4027 PyErr_BadArgument();
4028 return NULL;
4029 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004030 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004031 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004032 assert(_PyUnicode_KIND(unicode) != 0);
4033 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004034
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004035 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004036#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004037 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4038 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004039 num_surrogates = 0;
4040
4041 for (; four_bytes < ucs4_end; ++four_bytes) {
4042 if (*four_bytes > 0xFFFF)
4043 ++num_surrogates;
4044 }
4045
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004046 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4047 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4048 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004049 PyErr_NoMemory();
4050 return NULL;
4051 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004052 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004053
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004054 w = _PyUnicode_WSTR(unicode);
4055 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4056 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004057 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4058 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004059 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004060 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004061 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4062 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004063 }
4064 else
4065 *w = *four_bytes;
4066
4067 if (w > wchar_end) {
4068 assert(0 && "Miscalculated string end");
4069 }
4070 }
4071 *w = 0;
4072#else
4073 /* sizeof(wchar_t) == 4 */
4074 Py_FatalError("Impossible unicode object state, wstr and str "
4075 "should share memory already.");
4076 return NULL;
4077#endif
4078 }
4079 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004080 if ((size_t)_PyUnicode_LENGTH(unicode) >
4081 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4082 PyErr_NoMemory();
4083 return NULL;
4084 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004085 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4086 (_PyUnicode_LENGTH(unicode) + 1));
4087 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004088 PyErr_NoMemory();
4089 return NULL;
4090 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004091 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4092 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4093 w = _PyUnicode_WSTR(unicode);
4094 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004095
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004096 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4097 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004098 for (; w < wchar_end; ++one_byte, ++w)
4099 *w = *one_byte;
4100 /* null-terminate the wstr */
4101 *w = 0;
4102 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004103 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004104#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004105 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004106 for (; w < wchar_end; ++two_bytes, ++w)
4107 *w = *two_bytes;
4108 /* null-terminate the wstr */
4109 *w = 0;
4110#else
4111 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004112 PyObject_FREE(_PyUnicode_WSTR(unicode));
4113 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004114 Py_FatalError("Impossible unicode object state, wstr "
4115 "and str should share memory already.");
4116 return NULL;
4117#endif
4118 }
4119 else {
4120 assert(0 && "This should never happen.");
4121 }
4122 }
4123 }
4124 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004125 *size = PyUnicode_WSTR_LENGTH(unicode);
4126 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004127}
4128
Alexander Belopolsky40018472011-02-26 01:02:56 +00004129Py_UNICODE *
4130PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004131{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004132 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004133}
4134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004135
Alexander Belopolsky40018472011-02-26 01:02:56 +00004136Py_ssize_t
4137PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004138{
4139 if (!PyUnicode_Check(unicode)) {
4140 PyErr_BadArgument();
4141 goto onError;
4142 }
4143 return PyUnicode_GET_SIZE(unicode);
4144
Benjamin Peterson29060642009-01-31 22:14:21 +00004145 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004146 return -1;
4147}
4148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004149Py_ssize_t
4150PyUnicode_GetLength(PyObject *unicode)
4151{
Victor Stinner07621332012-06-16 04:53:46 +02004152 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004153 PyErr_BadArgument();
4154 return -1;
4155 }
Victor Stinner07621332012-06-16 04:53:46 +02004156 if (PyUnicode_READY(unicode) == -1)
4157 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004158 return PyUnicode_GET_LENGTH(unicode);
4159}
4160
4161Py_UCS4
4162PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4163{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004164 void *data;
4165 int kind;
4166
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004167 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4168 PyErr_BadArgument();
4169 return (Py_UCS4)-1;
4170 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004171 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004172 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004173 return (Py_UCS4)-1;
4174 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004175 data = PyUnicode_DATA(unicode);
4176 kind = PyUnicode_KIND(unicode);
4177 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004178}
4179
4180int
4181PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4182{
4183 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004184 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004185 return -1;
4186 }
Victor Stinner488fa492011-12-12 00:01:39 +01004187 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004188 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004189 PyErr_SetString(PyExc_IndexError, "string index out of range");
4190 return -1;
4191 }
Victor Stinner488fa492011-12-12 00:01:39 +01004192 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004193 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004194 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4195 PyErr_SetString(PyExc_ValueError, "character out of range");
4196 return -1;
4197 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004198 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4199 index, ch);
4200 return 0;
4201}
4202
Alexander Belopolsky40018472011-02-26 01:02:56 +00004203const char *
4204PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004205{
Victor Stinner42cb4622010-09-01 19:39:01 +00004206 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004207}
4208
Victor Stinner554f3f02010-06-16 23:33:54 +00004209/* create or adjust a UnicodeDecodeError */
4210static void
4211make_decode_exception(PyObject **exceptionObject,
4212 const char *encoding,
4213 const char *input, Py_ssize_t length,
4214 Py_ssize_t startpos, Py_ssize_t endpos,
4215 const char *reason)
4216{
4217 if (*exceptionObject == NULL) {
4218 *exceptionObject = PyUnicodeDecodeError_Create(
4219 encoding, input, length, startpos, endpos, reason);
4220 }
4221 else {
4222 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4223 goto onError;
4224 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4225 goto onError;
4226 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4227 goto onError;
4228 }
4229 return;
4230
4231onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004232 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004233}
4234
Steve Dowercc16be82016-09-08 10:35:16 -07004235#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004236/* error handling callback helper:
4237 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004238 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004239 and adjust various state variables.
4240 return 0 on success, -1 on error
4241*/
4242
Alexander Belopolsky40018472011-02-26 01:02:56 +00004243static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004244unicode_decode_call_errorhandler_wchar(
4245 const char *errors, PyObject **errorHandler,
4246 const char *encoding, const char *reason,
4247 const char **input, const char **inend, Py_ssize_t *startinpos,
4248 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4249 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004250{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004251 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004252
4253 PyObject *restuple = NULL;
4254 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004255 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004256 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004257 Py_ssize_t requiredsize;
4258 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004259 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004260 wchar_t *repwstr;
4261 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004262
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004263 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4264 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004265
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004266 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004267 *errorHandler = PyCodec_LookupError(errors);
4268 if (*errorHandler == NULL)
4269 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004270 }
4271
Victor Stinner554f3f02010-06-16 23:33:54 +00004272 make_decode_exception(exceptionObject,
4273 encoding,
4274 *input, *inend - *input,
4275 *startinpos, *endinpos,
4276 reason);
4277 if (*exceptionObject == NULL)
4278 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004279
4280 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4281 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004282 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004283 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004284 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004285 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004286 }
4287 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004288 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004289
4290 /* Copy back the bytes variables, which might have been modified by the
4291 callback */
4292 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4293 if (!inputobj)
4294 goto onError;
4295 if (!PyBytes_Check(inputobj)) {
4296 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4297 }
4298 *input = PyBytes_AS_STRING(inputobj);
4299 insize = PyBytes_GET_SIZE(inputobj);
4300 *inend = *input + insize;
4301 /* we can DECREF safely, as the exception has another reference,
4302 so the object won't go away. */
4303 Py_DECREF(inputobj);
4304
4305 if (newpos<0)
4306 newpos = insize+newpos;
4307 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004308 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004309 goto onError;
4310 }
4311
4312 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4313 if (repwstr == NULL)
4314 goto onError;
4315 /* need more space? (at least enough for what we
4316 have+the replacement+the rest of the string (starting
4317 at the new input position), so we won't have to check space
4318 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004319 requiredsize = *outpos;
4320 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4321 goto overflow;
4322 requiredsize += repwlen;
4323 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4324 goto overflow;
4325 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004326 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004327 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004328 requiredsize = 2*outsize;
4329 if (unicode_resize(output, requiredsize) < 0)
4330 goto onError;
4331 }
4332 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4333 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004334 *endinpos = newpos;
4335 *inptr = *input + newpos;
4336
4337 /* we made it! */
4338 Py_XDECREF(restuple);
4339 return 0;
4340
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004341 overflow:
4342 PyErr_SetString(PyExc_OverflowError,
4343 "decoded result is too long for a Python string");
4344
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004345 onError:
4346 Py_XDECREF(restuple);
4347 return -1;
4348}
Steve Dowercc16be82016-09-08 10:35:16 -07004349#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004350
4351static int
4352unicode_decode_call_errorhandler_writer(
4353 const char *errors, PyObject **errorHandler,
4354 const char *encoding, const char *reason,
4355 const char **input, const char **inend, Py_ssize_t *startinpos,
4356 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4357 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4358{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004359 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004360
4361 PyObject *restuple = NULL;
4362 PyObject *repunicode = NULL;
4363 Py_ssize_t insize;
4364 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004365 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004366 PyObject *inputobj = NULL;
4367
4368 if (*errorHandler == NULL) {
4369 *errorHandler = PyCodec_LookupError(errors);
4370 if (*errorHandler == NULL)
4371 goto onError;
4372 }
4373
4374 make_decode_exception(exceptionObject,
4375 encoding,
4376 *input, *inend - *input,
4377 *startinpos, *endinpos,
4378 reason);
4379 if (*exceptionObject == NULL)
4380 goto onError;
4381
4382 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4383 if (restuple == NULL)
4384 goto onError;
4385 if (!PyTuple_Check(restuple)) {
4386 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4387 goto onError;
4388 }
4389 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004390 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004391
4392 /* Copy back the bytes variables, which might have been modified by the
4393 callback */
4394 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4395 if (!inputobj)
4396 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004397 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004398 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004399 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004400 *input = PyBytes_AS_STRING(inputobj);
4401 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004402 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004403 /* we can DECREF safely, as the exception has another reference,
4404 so the object won't go away. */
4405 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004406
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004407 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004408 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004409 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004410 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004411 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004412 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004413
Victor Stinner8f674cc2013-04-17 23:02:17 +02004414 if (PyUnicode_READY(repunicode) < 0)
4415 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004416 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004417 if (replen > 1) {
4418 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004419 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004420 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4421 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4422 goto onError;
4423 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004424 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004425 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004426
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004427 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004428 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004429
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004430 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004431 Py_XDECREF(restuple);
4432 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004433
Benjamin Peterson29060642009-01-31 22:14:21 +00004434 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004435 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004436 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004437}
4438
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004439/* --- UTF-7 Codec -------------------------------------------------------- */
4440
Antoine Pitrou244651a2009-05-04 18:56:13 +00004441/* See RFC2152 for details. We encode conservatively and decode liberally. */
4442
4443/* Three simple macros defining base-64. */
4444
4445/* Is c a base-64 character? */
4446
4447#define IS_BASE64(c) \
4448 (((c) >= 'A' && (c) <= 'Z') || \
4449 ((c) >= 'a' && (c) <= 'z') || \
4450 ((c) >= '0' && (c) <= '9') || \
4451 (c) == '+' || (c) == '/')
4452
4453/* given that c is a base-64 character, what is its base-64 value? */
4454
4455#define FROM_BASE64(c) \
4456 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4457 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4458 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4459 (c) == '+' ? 62 : 63)
4460
4461/* What is the base-64 character of the bottom 6 bits of n? */
4462
4463#define TO_BASE64(n) \
4464 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4465
4466/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4467 * decoded as itself. We are permissive on decoding; the only ASCII
4468 * byte not decoding to itself is the + which begins a base64
4469 * string. */
4470
4471#define DECODE_DIRECT(c) \
4472 ((c) <= 127 && (c) != '+')
4473
4474/* The UTF-7 encoder treats ASCII characters differently according to
4475 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4476 * the above). See RFC2152. This array identifies these different
4477 * sets:
4478 * 0 : "Set D"
4479 * alphanumeric and '(),-./:?
4480 * 1 : "Set O"
4481 * !"#$%&*;<=>@[]^_`{|}
4482 * 2 : "whitespace"
4483 * ht nl cr sp
4484 * 3 : special (must be base64 encoded)
4485 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4486 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004487
Tim Petersced69f82003-09-16 20:30:58 +00004488static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004489char utf7_category[128] = {
4490/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4491 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4492/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4493 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4494/* sp ! " # $ % & ' ( ) * + , - . / */
4495 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4496/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4497 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4498/* @ A B C D E F G H I J K L M N O */
4499 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4500/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4501 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4502/* ` a b c d e f g h i j k l m n o */
4503 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4504/* p q r s t u v w x y z { | } ~ del */
4505 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004506};
4507
Antoine Pitrou244651a2009-05-04 18:56:13 +00004508/* ENCODE_DIRECT: this character should be encoded as itself. The
4509 * answer depends on whether we are encoding set O as itself, and also
4510 * on whether we are encoding whitespace as itself. RFC2152 makes it
4511 * clear that the answers to these questions vary between
4512 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004513
Antoine Pitrou244651a2009-05-04 18:56:13 +00004514#define ENCODE_DIRECT(c, directO, directWS) \
4515 ((c) < 128 && (c) > 0 && \
4516 ((utf7_category[(c)] == 0) || \
4517 (directWS && (utf7_category[(c)] == 2)) || \
4518 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004519
Alexander Belopolsky40018472011-02-26 01:02:56 +00004520PyObject *
4521PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004522 Py_ssize_t size,
4523 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004525 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4526}
4527
Antoine Pitrou244651a2009-05-04 18:56:13 +00004528/* The decoder. The only state we preserve is our read position,
4529 * i.e. how many characters we have consumed. So if we end in the
4530 * middle of a shift sequence we have to back off the read position
4531 * and the output to the beginning of the sequence, otherwise we lose
4532 * all the shift state (seen bits, number of bits seen, high
4533 * surrogate). */
4534
Alexander Belopolsky40018472011-02-26 01:02:56 +00004535PyObject *
4536PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004537 Py_ssize_t size,
4538 const char *errors,
4539 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004540{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004541 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004542 Py_ssize_t startinpos;
4543 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004545 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004546 const char *errmsg = "";
4547 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004548 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 unsigned int base64bits = 0;
4550 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004551 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004552 PyObject *errorHandler = NULL;
4553 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004554
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004555 if (size == 0) {
4556 if (consumed)
4557 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004558 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004559 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004560
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004561 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004562 _PyUnicodeWriter_Init(&writer);
4563 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004564
4565 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004566 e = s + size;
4567
4568 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004569 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004570 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004571 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004572
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 if (inShift) { /* in a base-64 section */
4574 if (IS_BASE64(ch)) { /* consume a base-64 character */
4575 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4576 base64bits += 6;
4577 s++;
4578 if (base64bits >= 16) {
4579 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004580 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 base64bits -= 16;
4582 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004583 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 if (surrogate) {
4585 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004586 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4587 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004588 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004589 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004590 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004591 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004592 }
4593 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004594 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004595 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004597 }
4598 }
Victor Stinner551ac952011-11-29 22:58:13 +01004599 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004600 /* first surrogate */
4601 surrogate = outCh;
4602 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004603 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004604 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004605 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004606 }
4607 }
4608 }
4609 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004610 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004611 if (base64bits > 0) { /* left-over bits */
4612 if (base64bits >= 6) {
4613 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004614 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004615 errmsg = "partial character in shift sequence";
4616 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004617 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004618 else {
4619 /* Some bits remain; they should be zero */
4620 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004621 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004622 errmsg = "non-zero padding bits in shift sequence";
4623 goto utf7Error;
4624 }
4625 }
4626 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004627 if (surrogate && DECODE_DIRECT(ch)) {
4628 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4629 goto onError;
4630 }
4631 surrogate = 0;
4632 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004633 /* '-' is absorbed; other terminating
4634 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004635 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004636 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004637 }
4638 }
4639 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004640 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004641 s++; /* consume '+' */
4642 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004643 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004644 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004645 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004646 }
4647 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004648 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004649 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004650 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004651 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004652 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004653 }
4654 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004655 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004656 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004657 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004658 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004659 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004660 else {
4661 startinpos = s-starts;
4662 s++;
4663 errmsg = "unexpected special character";
4664 goto utf7Error;
4665 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004666 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004667utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004668 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004669 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004670 errors, &errorHandler,
4671 "utf7", errmsg,
4672 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004673 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004674 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004675 }
4676
Antoine Pitrou244651a2009-05-04 18:56:13 +00004677 /* end of string */
4678
4679 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4680 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004681 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004682 if (surrogate ||
4683 (base64bits >= 6) ||
4684 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004685 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004686 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004687 errors, &errorHandler,
4688 "utf7", "unterminated shift sequence",
4689 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004690 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004691 goto onError;
4692 if (s < e)
4693 goto restart;
4694 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004695 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004696
4697 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004698 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004699 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004700 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004701 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004702 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004703 writer.kind, writer.data, shiftOutStart);
4704 Py_XDECREF(errorHandler);
4705 Py_XDECREF(exc);
4706 _PyUnicodeWriter_Dealloc(&writer);
4707 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004708 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004709 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004710 }
4711 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004712 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004713 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004714 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004715
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004716 Py_XDECREF(errorHandler);
4717 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004718 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004719
Benjamin Peterson29060642009-01-31 22:14:21 +00004720 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004721 Py_XDECREF(errorHandler);
4722 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004723 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004724 return NULL;
4725}
4726
4727
Alexander Belopolsky40018472011-02-26 01:02:56 +00004728PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004729_PyUnicode_EncodeUTF7(PyObject *str,
4730 int base64SetO,
4731 int base64WhiteSpace,
4732 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004733{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004734 int kind;
4735 void *data;
4736 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004737 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004738 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004739 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004740 unsigned int base64bits = 0;
4741 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004742 char * out;
4743 char * start;
4744
Benjamin Petersonbac79492012-01-14 13:34:47 -05004745 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004746 return NULL;
4747 kind = PyUnicode_KIND(str);
4748 data = PyUnicode_DATA(str);
4749 len = PyUnicode_GET_LENGTH(str);
4750
4751 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004752 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004753
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004754 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004755 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004756 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004757 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004758 if (v == NULL)
4759 return NULL;
4760
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004761 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004762 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004763 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004764
Antoine Pitrou244651a2009-05-04 18:56:13 +00004765 if (inShift) {
4766 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4767 /* shifting out */
4768 if (base64bits) { /* output remaining bits */
4769 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4770 base64buffer = 0;
4771 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004772 }
4773 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004774 /* Characters not in the BASE64 set implicitly unshift the sequence
4775 so no '-' is required, except if the character is itself a '-' */
4776 if (IS_BASE64(ch) || ch == '-') {
4777 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004778 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004779 *out++ = (char) ch;
4780 }
4781 else {
4782 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004783 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004784 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004785 else { /* not in a shift sequence */
4786 if (ch == '+') {
4787 *out++ = '+';
4788 *out++ = '-';
4789 }
4790 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4791 *out++ = (char) ch;
4792 }
4793 else {
4794 *out++ = '+';
4795 inShift = 1;
4796 goto encode_char;
4797 }
4798 }
4799 continue;
4800encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004801 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004802 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004803
Antoine Pitrou244651a2009-05-04 18:56:13 +00004804 /* code first surrogate */
4805 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004806 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004807 while (base64bits >= 6) {
4808 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4809 base64bits -= 6;
4810 }
4811 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004812 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004813 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004814 base64bits += 16;
4815 base64buffer = (base64buffer << 16) | ch;
4816 while (base64bits >= 6) {
4817 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4818 base64bits -= 6;
4819 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004820 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004821 if (base64bits)
4822 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4823 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004824 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004825 if (_PyBytes_Resize(&v, out - start) < 0)
4826 return NULL;
4827 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004828}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004829PyObject *
4830PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4831 Py_ssize_t size,
4832 int base64SetO,
4833 int base64WhiteSpace,
4834 const char *errors)
4835{
4836 PyObject *result;
4837 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4838 if (tmp == NULL)
4839 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004840 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004841 base64WhiteSpace, errors);
4842 Py_DECREF(tmp);
4843 return result;
4844}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004845
Antoine Pitrou244651a2009-05-04 18:56:13 +00004846#undef IS_BASE64
4847#undef FROM_BASE64
4848#undef TO_BASE64
4849#undef DECODE_DIRECT
4850#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004851
Guido van Rossumd57fd912000-03-10 22:53:23 +00004852/* --- UTF-8 Codec -------------------------------------------------------- */
4853
Alexander Belopolsky40018472011-02-26 01:02:56 +00004854PyObject *
4855PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004856 Py_ssize_t size,
4857 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004858{
Walter Dörwald69652032004-09-07 20:24:22 +00004859 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4860}
4861
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004862#include "stringlib/asciilib.h"
4863#include "stringlib/codecs.h"
4864#include "stringlib/undef.h"
4865
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004866#include "stringlib/ucs1lib.h"
4867#include "stringlib/codecs.h"
4868#include "stringlib/undef.h"
4869
4870#include "stringlib/ucs2lib.h"
4871#include "stringlib/codecs.h"
4872#include "stringlib/undef.h"
4873
4874#include "stringlib/ucs4lib.h"
4875#include "stringlib/codecs.h"
4876#include "stringlib/undef.h"
4877
Antoine Pitrouab868312009-01-10 15:40:25 +00004878/* Mask to quickly check whether a C 'long' contains a
4879 non-ASCII, UTF8-encoded char. */
4880#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004881# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004882#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004883# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004884#else
4885# error C 'long' size should be either 4 or 8!
4886#endif
4887
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004888static Py_ssize_t
4889ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004890{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004891 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004892 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004893
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004894 /*
4895 * Issue #17237: m68k is a bit different from most architectures in
4896 * that objects do not use "natural alignment" - for example, int and
4897 * long are only aligned at 2-byte boundaries. Therefore the assert()
4898 * won't work; also, tests have shown that skipping the "optimised
4899 * version" will even speed up m68k.
4900 */
4901#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004902#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004903 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4904 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004905 /* Fast path, see in STRINGLIB(utf8_decode) for
4906 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004907 /* Help allocation */
4908 const char *_p = p;
4909 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004910 while (_p < aligned_end) {
4911 unsigned long value = *(const unsigned long *) _p;
4912 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004913 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004914 *((unsigned long *)q) = value;
4915 _p += SIZEOF_LONG;
4916 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004917 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004918 p = _p;
4919 while (p < end) {
4920 if ((unsigned char)*p & 0x80)
4921 break;
4922 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004923 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004924 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004925 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004926#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004927#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004928 while (p < end) {
4929 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4930 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004931 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004932 /* Help allocation */
4933 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004934 while (_p < aligned_end) {
4935 unsigned long value = *(unsigned long *) _p;
4936 if (value & ASCII_CHAR_MASK)
4937 break;
4938 _p += SIZEOF_LONG;
4939 }
4940 p = _p;
4941 if (_p == end)
4942 break;
4943 }
4944 if ((unsigned char)*p & 0x80)
4945 break;
4946 ++p;
4947 }
4948 memcpy(dest, start, p - start);
4949 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004950}
Antoine Pitrouab868312009-01-10 15:40:25 +00004951
Victor Stinner785938e2011-12-11 20:09:03 +01004952PyObject *
4953PyUnicode_DecodeUTF8Stateful(const char *s,
4954 Py_ssize_t size,
4955 const char *errors,
4956 Py_ssize_t *consumed)
4957{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004958 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004959 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004960 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004961
4962 Py_ssize_t startinpos;
4963 Py_ssize_t endinpos;
4964 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004965 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004966 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004967 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004968
4969 if (size == 0) {
4970 if (consumed)
4971 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004972 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004973 }
4974
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004975 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4976 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004977 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004978 *consumed = 1;
4979 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004980 }
4981
Victor Stinner8f674cc2013-04-17 23:02:17 +02004982 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004983 writer.min_length = size;
4984 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004985 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004986
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004987 writer.pos = ascii_decode(s, end, writer.data);
4988 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004989 while (s < end) {
4990 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004991 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004992
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004993 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004994 if (PyUnicode_IS_ASCII(writer.buffer))
4995 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004996 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004997 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004998 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004999 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005000 } else {
5001 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005002 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005003 }
5004
5005 switch (ch) {
5006 case 0:
5007 if (s == end || consumed)
5008 goto End;
5009 errmsg = "unexpected end of data";
5010 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005011 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005012 break;
5013 case 1:
5014 errmsg = "invalid start byte";
5015 startinpos = s - starts;
5016 endinpos = startinpos + 1;
5017 break;
5018 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005019 case 3:
5020 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005021 errmsg = "invalid continuation byte";
5022 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005023 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005024 break;
5025 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005026 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005027 goto onError;
5028 continue;
5029 }
5030
Victor Stinner1d65d912015-10-05 13:43:50 +02005031 if (error_handler == _Py_ERROR_UNKNOWN)
5032 error_handler = get_error_handler(errors);
5033
5034 switch (error_handler) {
5035 case _Py_ERROR_IGNORE:
5036 s += (endinpos - startinpos);
5037 break;
5038
5039 case _Py_ERROR_REPLACE:
5040 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5041 goto onError;
5042 s += (endinpos - startinpos);
5043 break;
5044
5045 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005046 {
5047 Py_ssize_t i;
5048
Victor Stinner1d65d912015-10-05 13:43:50 +02005049 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5050 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005051 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005052 ch = (Py_UCS4)(unsigned char)(starts[i]);
5053 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5054 ch + 0xdc00);
5055 writer.pos++;
5056 }
5057 s += (endinpos - startinpos);
5058 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005059 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005060
5061 default:
5062 if (unicode_decode_call_errorhandler_writer(
5063 errors, &error_handler_obj,
5064 "utf-8", errmsg,
5065 &starts, &end, &startinpos, &endinpos, &exc, &s,
5066 &writer))
5067 goto onError;
5068 }
Victor Stinner785938e2011-12-11 20:09:03 +01005069 }
5070
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005071End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005072 if (consumed)
5073 *consumed = s - starts;
5074
Victor Stinner1d65d912015-10-05 13:43:50 +02005075 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005076 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005077 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005078
5079onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005080 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005081 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005082 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005083 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005084}
5085
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005086#ifdef __APPLE__
5087
5088/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005089 used to decode the command line arguments on Mac OS X.
5090
5091 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005092 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005093
5094wchar_t*
5095_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5096{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005097 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005098 wchar_t *unicode;
5099 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005100
5101 /* Note: size will always be longer than the resulting Unicode
5102 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005103 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005104 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005105 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005106 if (!unicode)
5107 return NULL;
5108
5109 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005110 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005111 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005112 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005113 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005114#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005115 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005116#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005117 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005118#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005119 if (ch > 0xFF) {
5120#if SIZEOF_WCHAR_T == 4
5121 assert(0);
5122#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005123 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005124 /* compute and append the two surrogates: */
5125 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5126 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5127#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005128 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005129 else {
5130 if (!ch && s == e)
5131 break;
5132 /* surrogateescape */
5133 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5134 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005135 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005136 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005137 return unicode;
5138}
5139
5140#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005142/* Primary internal function which creates utf8 encoded bytes objects.
5143
5144 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005145 and allocate exactly as much space needed at the end. Else allocate the
5146 maximum possible needed (4 result bytes per Unicode character), and return
5147 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005148*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005149PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005150_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005151{
Victor Stinner6099a032011-12-18 14:22:26 +01005152 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005153 void *data;
5154 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005156 if (!PyUnicode_Check(unicode)) {
5157 PyErr_BadArgument();
5158 return NULL;
5159 }
5160
5161 if (PyUnicode_READY(unicode) == -1)
5162 return NULL;
5163
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005164 if (PyUnicode_UTF8(unicode))
5165 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5166 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005167
5168 kind = PyUnicode_KIND(unicode);
5169 data = PyUnicode_DATA(unicode);
5170 size = PyUnicode_GET_LENGTH(unicode);
5171
Benjamin Petersonead6b532011-12-20 17:23:42 -06005172 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005173 default:
5174 assert(0);
5175 case PyUnicode_1BYTE_KIND:
5176 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5177 assert(!PyUnicode_IS_ASCII(unicode));
5178 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5179 case PyUnicode_2BYTE_KIND:
5180 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5181 case PyUnicode_4BYTE_KIND:
5182 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005183 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005184}
5185
Alexander Belopolsky40018472011-02-26 01:02:56 +00005186PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005187PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5188 Py_ssize_t size,
5189 const char *errors)
5190{
5191 PyObject *v, *unicode;
5192
5193 unicode = PyUnicode_FromUnicode(s, size);
5194 if (unicode == NULL)
5195 return NULL;
5196 v = _PyUnicode_AsUTF8String(unicode, errors);
5197 Py_DECREF(unicode);
5198 return v;
5199}
5200
5201PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005202PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005203{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005204 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005205}
5206
Walter Dörwald41980ca2007-08-16 21:55:45 +00005207/* --- UTF-32 Codec ------------------------------------------------------- */
5208
5209PyObject *
5210PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005211 Py_ssize_t size,
5212 const char *errors,
5213 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005214{
5215 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5216}
5217
5218PyObject *
5219PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005220 Py_ssize_t size,
5221 const char *errors,
5222 int *byteorder,
5223 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005224{
5225 const char *starts = s;
5226 Py_ssize_t startinpos;
5227 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005228 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005229 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005230 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005231 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005232 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005233 PyObject *errorHandler = NULL;
5234 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005235
Walter Dörwald41980ca2007-08-16 21:55:45 +00005236 q = (unsigned char *)s;
5237 e = q + size;
5238
5239 if (byteorder)
5240 bo = *byteorder;
5241
5242 /* Check for BOM marks (U+FEFF) in the input and adjust current
5243 byte order setting accordingly. In native mode, the leading BOM
5244 mark is skipped, in all other modes, it is copied to the output
5245 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005246 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005247 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005248 if (bom == 0x0000FEFF) {
5249 bo = -1;
5250 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005251 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005252 else if (bom == 0xFFFE0000) {
5253 bo = 1;
5254 q += 4;
5255 }
5256 if (byteorder)
5257 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005258 }
5259
Victor Stinnere64322e2012-10-30 23:12:47 +01005260 if (q == e) {
5261 if (consumed)
5262 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005263 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264 }
5265
Victor Stinnere64322e2012-10-30 23:12:47 +01005266#ifdef WORDS_BIGENDIAN
5267 le = bo < 0;
5268#else
5269 le = bo <= 0;
5270#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005271 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005272
Victor Stinner8f674cc2013-04-17 23:02:17 +02005273 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005274 writer.min_length = (e - q + 3) / 4;
5275 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005276 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005277
Victor Stinnere64322e2012-10-30 23:12:47 +01005278 while (1) {
5279 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005280 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005281
Victor Stinnere64322e2012-10-30 23:12:47 +01005282 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005283 enum PyUnicode_Kind kind = writer.kind;
5284 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005285 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005286 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005287 if (le) {
5288 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005289 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005290 if (ch > maxch)
5291 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005292 if (kind != PyUnicode_1BYTE_KIND &&
5293 Py_UNICODE_IS_SURROGATE(ch))
5294 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005295 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005296 q += 4;
5297 } while (q <= last);
5298 }
5299 else {
5300 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005301 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005302 if (ch > maxch)
5303 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005304 if (kind != PyUnicode_1BYTE_KIND &&
5305 Py_UNICODE_IS_SURROGATE(ch))
5306 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005307 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005308 q += 4;
5309 } while (q <= last);
5310 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005311 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005312 }
5313
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005314 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005315 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005316 startinpos = ((const char *)q) - starts;
5317 endinpos = startinpos + 4;
5318 }
5319 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005320 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005321 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005322 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005323 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005324 startinpos = ((const char *)q) - starts;
5325 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005326 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005327 else {
5328 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005329 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005330 goto onError;
5331 q += 4;
5332 continue;
5333 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005334 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005335 startinpos = ((const char *)q) - starts;
5336 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005338
5339 /* The remaining input chars are ignored if the callback
5340 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005341 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005342 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005343 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005344 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005345 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005346 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005347 }
5348
Walter Dörwald41980ca2007-08-16 21:55:45 +00005349 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005350 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005351
Walter Dörwald41980ca2007-08-16 21:55:45 +00005352 Py_XDECREF(errorHandler);
5353 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005354 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005355
Benjamin Peterson29060642009-01-31 22:14:21 +00005356 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005357 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005358 Py_XDECREF(errorHandler);
5359 Py_XDECREF(exc);
5360 return NULL;
5361}
5362
5363PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005364_PyUnicode_EncodeUTF32(PyObject *str,
5365 const char *errors,
5366 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005367{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005368 enum PyUnicode_Kind kind;
5369 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005370 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005371 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005372 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005373#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005374 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005375#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005376 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005377#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005378 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005379 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005380 PyObject *errorHandler = NULL;
5381 PyObject *exc = NULL;
5382 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005383
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005384 if (!PyUnicode_Check(str)) {
5385 PyErr_BadArgument();
5386 return NULL;
5387 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005388 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005389 return NULL;
5390 kind = PyUnicode_KIND(str);
5391 data = PyUnicode_DATA(str);
5392 len = PyUnicode_GET_LENGTH(str);
5393
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005394 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005395 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005396 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005397 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005398 if (v == NULL)
5399 return NULL;
5400
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005401 /* output buffer is 4-bytes aligned */
5402 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005403 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005404 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005405 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005406 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005407 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005408
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005409 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005410 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005411 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005412 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005413 else
5414 encoding = "utf-32";
5415
5416 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005417 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5418 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005419 }
5420
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005421 pos = 0;
5422 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005423 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005424
5425 if (kind == PyUnicode_2BYTE_KIND) {
5426 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5427 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005428 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005429 else {
5430 assert(kind == PyUnicode_4BYTE_KIND);
5431 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5432 &out, native_ordering);
5433 }
5434 if (pos == len)
5435 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005436
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005437 rep = unicode_encode_call_errorhandler(
5438 errors, &errorHandler,
5439 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005440 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005441 if (!rep)
5442 goto error;
5443
5444 if (PyBytes_Check(rep)) {
5445 repsize = PyBytes_GET_SIZE(rep);
5446 if (repsize & 3) {
5447 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005448 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005449 "surrogates not allowed");
5450 goto error;
5451 }
5452 moreunits = repsize / 4;
5453 }
5454 else {
5455 assert(PyUnicode_Check(rep));
5456 if (PyUnicode_READY(rep) < 0)
5457 goto error;
5458 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5459 if (!PyUnicode_IS_ASCII(rep)) {
5460 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005461 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005462 "surrogates not allowed");
5463 goto error;
5464 }
5465 }
5466
5467 /* four bytes are reserved for each surrogate */
5468 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005469 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005470 Py_ssize_t morebytes = 4 * (moreunits - 1);
5471 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5472 /* integer overflow */
5473 PyErr_NoMemory();
5474 goto error;
5475 }
5476 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5477 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005478 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005479 }
5480
5481 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005482 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005483 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005484 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005485 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005486 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5487 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005488 }
5489
5490 Py_CLEAR(rep);
5491 }
5492
5493 /* Cut back to size actually needed. This is necessary for, for example,
5494 encoding of a string containing isolated surrogates and the 'ignore'
5495 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005496 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005497 if (nsize != PyBytes_GET_SIZE(v))
5498 _PyBytes_Resize(&v, nsize);
5499 Py_XDECREF(errorHandler);
5500 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005501 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005502 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005503 error:
5504 Py_XDECREF(rep);
5505 Py_XDECREF(errorHandler);
5506 Py_XDECREF(exc);
5507 Py_XDECREF(v);
5508 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005509}
5510
Alexander Belopolsky40018472011-02-26 01:02:56 +00005511PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005512PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5513 Py_ssize_t size,
5514 const char *errors,
5515 int byteorder)
5516{
5517 PyObject *result;
5518 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5519 if (tmp == NULL)
5520 return NULL;
5521 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5522 Py_DECREF(tmp);
5523 return result;
5524}
5525
5526PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005527PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005528{
Victor Stinnerb960b342011-11-20 19:12:52 +01005529 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005530}
5531
Guido van Rossumd57fd912000-03-10 22:53:23 +00005532/* --- UTF-16 Codec ------------------------------------------------------- */
5533
Tim Peters772747b2001-08-09 22:21:55 +00005534PyObject *
5535PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005536 Py_ssize_t size,
5537 const char *errors,
5538 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005539{
Walter Dörwald69652032004-09-07 20:24:22 +00005540 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5541}
5542
5543PyObject *
5544PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005545 Py_ssize_t size,
5546 const char *errors,
5547 int *byteorder,
5548 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005549{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005550 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005551 Py_ssize_t startinpos;
5552 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005553 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005554 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005555 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005556 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005557 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005558 PyObject *errorHandler = NULL;
5559 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005560 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005561
Tim Peters772747b2001-08-09 22:21:55 +00005562 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005563 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005564
5565 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005566 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005567
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005568 /* Check for BOM marks (U+FEFF) in the input and adjust current
5569 byte order setting accordingly. In native mode, the leading BOM
5570 mark is skipped, in all other modes, it is copied to the output
5571 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005572 if (bo == 0 && size >= 2) {
5573 const Py_UCS4 bom = (q[1] << 8) | q[0];
5574 if (bom == 0xFEFF) {
5575 q += 2;
5576 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005577 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005578 else if (bom == 0xFFFE) {
5579 q += 2;
5580 bo = 1;
5581 }
5582 if (byteorder)
5583 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005584 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005585
Antoine Pitrou63065d72012-05-15 23:48:04 +02005586 if (q == e) {
5587 if (consumed)
5588 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005589 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005590 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005591
Christian Heimes743e0cd2012-10-17 23:52:17 +02005592#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005593 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005594 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005595#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005596 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005597 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005598#endif
Tim Peters772747b2001-08-09 22:21:55 +00005599
Antoine Pitrou63065d72012-05-15 23:48:04 +02005600 /* Note: size will always be longer than the resulting Unicode
5601 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005602 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005603 writer.min_length = (e - q + 1) / 2;
5604 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005605 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005606
Antoine Pitrou63065d72012-05-15 23:48:04 +02005607 while (1) {
5608 Py_UCS4 ch = 0;
5609 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005610 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005611 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005612 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005613 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005614 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005615 native_ordering);
5616 else
5617 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005618 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005619 native_ordering);
5620 } else if (kind == PyUnicode_2BYTE_KIND) {
5621 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005622 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005623 native_ordering);
5624 } else {
5625 assert(kind == PyUnicode_4BYTE_KIND);
5626 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005627 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005628 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005629 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005630 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631
Antoine Pitrou63065d72012-05-15 23:48:04 +02005632 switch (ch)
5633 {
5634 case 0:
5635 /* remaining byte at the end? (size should be even) */
5636 if (q == e || consumed)
5637 goto End;
5638 errmsg = "truncated data";
5639 startinpos = ((const char *)q) - starts;
5640 endinpos = ((const char *)e) - starts;
5641 break;
5642 /* The remaining input chars are ignored if the callback
5643 chooses to skip the input */
5644 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005645 q -= 2;
5646 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005647 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005648 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005649 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005650 endinpos = ((const char *)e) - starts;
5651 break;
5652 case 2:
5653 errmsg = "illegal encoding";
5654 startinpos = ((const char *)q) - 2 - starts;
5655 endinpos = startinpos + 2;
5656 break;
5657 case 3:
5658 errmsg = "illegal UTF-16 surrogate";
5659 startinpos = ((const char *)q) - 4 - starts;
5660 endinpos = startinpos + 2;
5661 break;
5662 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005663 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005664 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005665 continue;
5666 }
5667
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005668 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005669 errors,
5670 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005671 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005672 &starts,
5673 (const char **)&e,
5674 &startinpos,
5675 &endinpos,
5676 &exc,
5677 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005678 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005679 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005680 }
5681
Antoine Pitrou63065d72012-05-15 23:48:04 +02005682End:
Walter Dörwald69652032004-09-07 20:24:22 +00005683 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005684 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005685
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005686 Py_XDECREF(errorHandler);
5687 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005688 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005689
Benjamin Peterson29060642009-01-31 22:14:21 +00005690 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005691 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005692 Py_XDECREF(errorHandler);
5693 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 return NULL;
5695}
5696
Tim Peters772747b2001-08-09 22:21:55 +00005697PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005698_PyUnicode_EncodeUTF16(PyObject *str,
5699 const char *errors,
5700 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005701{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005702 enum PyUnicode_Kind kind;
5703 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005704 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005705 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005706 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005707 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005708#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005709 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005710#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005711 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005712#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005713 const char *encoding;
5714 Py_ssize_t nsize, pos;
5715 PyObject *errorHandler = NULL;
5716 PyObject *exc = NULL;
5717 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005718
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005719 if (!PyUnicode_Check(str)) {
5720 PyErr_BadArgument();
5721 return NULL;
5722 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005723 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005724 return NULL;
5725 kind = PyUnicode_KIND(str);
5726 data = PyUnicode_DATA(str);
5727 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005728
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005729 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005730 if (kind == PyUnicode_4BYTE_KIND) {
5731 const Py_UCS4 *in = (const Py_UCS4 *)data;
5732 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005733 while (in < end) {
5734 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005735 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005736 }
5737 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005738 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005739 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005740 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005741 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005742 nsize = len + pairs + (byteorder == 0);
5743 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005744 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005745 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005746 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005748 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005749 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005750 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005751 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005752 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005753 }
5754 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005755 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005756 }
Tim Peters772747b2001-08-09 22:21:55 +00005757
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005758 if (kind == PyUnicode_1BYTE_KIND) {
5759 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5760 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005761 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005762
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005763 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005764 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005765 }
5766 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005767 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005768 }
5769 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005770 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005771 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005772
5773 pos = 0;
5774 while (pos < len) {
5775 Py_ssize_t repsize, moreunits;
5776
5777 if (kind == PyUnicode_2BYTE_KIND) {
5778 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5779 &out, native_ordering);
5780 }
5781 else {
5782 assert(kind == PyUnicode_4BYTE_KIND);
5783 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5784 &out, native_ordering);
5785 }
5786 if (pos == len)
5787 break;
5788
5789 rep = unicode_encode_call_errorhandler(
5790 errors, &errorHandler,
5791 encoding, "surrogates not allowed",
5792 str, &exc, pos, pos + 1, &pos);
5793 if (!rep)
5794 goto error;
5795
5796 if (PyBytes_Check(rep)) {
5797 repsize = PyBytes_GET_SIZE(rep);
5798 if (repsize & 1) {
5799 raise_encode_exception(&exc, encoding,
5800 str, pos - 1, pos,
5801 "surrogates not allowed");
5802 goto error;
5803 }
5804 moreunits = repsize / 2;
5805 }
5806 else {
5807 assert(PyUnicode_Check(rep));
5808 if (PyUnicode_READY(rep) < 0)
5809 goto error;
5810 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5811 if (!PyUnicode_IS_ASCII(rep)) {
5812 raise_encode_exception(&exc, encoding,
5813 str, pos - 1, pos,
5814 "surrogates not allowed");
5815 goto error;
5816 }
5817 }
5818
5819 /* two bytes are reserved for each surrogate */
5820 if (moreunits > 1) {
5821 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5822 Py_ssize_t morebytes = 2 * (moreunits - 1);
5823 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5824 /* integer overflow */
5825 PyErr_NoMemory();
5826 goto error;
5827 }
5828 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5829 goto error;
5830 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5831 }
5832
5833 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005834 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005835 out += moreunits;
5836 } else /* rep is unicode */ {
5837 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5838 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5839 &out, native_ordering);
5840 }
5841
5842 Py_CLEAR(rep);
5843 }
5844
5845 /* Cut back to size actually needed. This is necessary for, for example,
5846 encoding of a string containing isolated surrogates and the 'ignore' handler
5847 is used. */
5848 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5849 if (nsize != PyBytes_GET_SIZE(v))
5850 _PyBytes_Resize(&v, nsize);
5851 Py_XDECREF(errorHandler);
5852 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005853 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005854 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005855 error:
5856 Py_XDECREF(rep);
5857 Py_XDECREF(errorHandler);
5858 Py_XDECREF(exc);
5859 Py_XDECREF(v);
5860 return NULL;
5861#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862}
5863
Alexander Belopolsky40018472011-02-26 01:02:56 +00005864PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005865PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5866 Py_ssize_t size,
5867 const char *errors,
5868 int byteorder)
5869{
5870 PyObject *result;
5871 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5872 if (tmp == NULL)
5873 return NULL;
5874 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5875 Py_DECREF(tmp);
5876 return result;
5877}
5878
5879PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005880PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005882 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883}
5884
5885/* --- Unicode Escape Codec ----------------------------------------------- */
5886
Fredrik Lundh06d12682001-01-24 07:59:11 +00005887static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005888
Alexander Belopolsky40018472011-02-26 01:02:56 +00005889PyObject *
Eric V. Smith56466482016-10-31 14:46:26 -04005890_PyUnicode_DecodeUnicodeEscape(const char *s,
5891 Py_ssize_t size,
5892 const char *errors,
5893 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005894{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005895 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005896 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005897 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005898 PyObject *errorHandler = NULL;
5899 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005900
Eric V. Smith56466482016-10-31 14:46:26 -04005901 // so we can remember if we've seen an invalid escape char or not
5902 *first_invalid_escape = NULL;
5903
Victor Stinner62ec3312016-09-06 17:04:34 -07005904 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005905 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005906 }
5907 /* Escaped strings will always be longer than the resulting
5908 Unicode string, so we start with size here and then reduce the
5909 length after conversion to the true value.
5910 (but if the error callback returns a long replacement string
5911 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005912 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005913 writer.min_length = size;
5914 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5915 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005916 }
5917
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 end = s + size;
5919 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005920 unsigned char c = (unsigned char) *s++;
5921 Py_UCS4 ch;
5922 int count;
5923 Py_ssize_t startinpos;
5924 Py_ssize_t endinpos;
5925 const char *message;
5926
5927#define WRITE_ASCII_CHAR(ch) \
5928 do { \
5929 assert(ch <= 127); \
5930 assert(writer.pos < writer.size); \
5931 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5932 } while(0)
5933
5934#define WRITE_CHAR(ch) \
5935 do { \
5936 if (ch <= writer.maxchar) { \
5937 assert(writer.pos < writer.size); \
5938 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5939 } \
5940 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5941 goto onError; \
5942 } \
5943 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005944
5945 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005946 if (c != '\\') {
5947 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005948 continue;
5949 }
5950
Victor Stinner62ec3312016-09-06 17:04:34 -07005951 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005952 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005953 if (s >= end) {
5954 message = "\\ at end of string";
5955 goto error;
5956 }
5957 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005958
Victor Stinner62ec3312016-09-06 17:04:34 -07005959 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005960 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005961
Benjamin Peterson29060642009-01-31 22:14:21 +00005962 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005963 case '\n': continue;
5964 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5965 case '\'': WRITE_ASCII_CHAR('\''); continue;
5966 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5967 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005968 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005969 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5970 case 't': WRITE_ASCII_CHAR('\t'); continue;
5971 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5972 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005973 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005974 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005975 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005976 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977
Benjamin Peterson29060642009-01-31 22:14:21 +00005978 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979 case '0': case '1': case '2': case '3':
5980 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005981 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005982 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005983 ch = (ch<<3) + *s++ - '0';
5984 if (s < end && '0' <= *s && *s <= '7') {
5985 ch = (ch<<3) + *s++ - '0';
5986 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005988 WRITE_CHAR(ch);
5989 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005990
Benjamin Peterson29060642009-01-31 22:14:21 +00005991 /* hex escapes */
5992 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005994 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005995 message = "truncated \\xXX escape";
5996 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997
Benjamin Peterson29060642009-01-31 22:14:21 +00005998 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006000 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006001 message = "truncated \\uXXXX escape";
6002 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006005 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006006 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006007 message = "truncated \\UXXXXXXXX escape";
6008 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006009 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006010 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006011 ch <<= 4;
6012 if (c >= '0' && c <= '9') {
6013 ch += c - '0';
6014 }
6015 else if (c >= 'a' && c <= 'f') {
6016 ch += c - ('a' - 10);
6017 }
6018 else if (c >= 'A' && c <= 'F') {
6019 ch += c - ('A' - 10);
6020 }
6021 else {
6022 break;
6023 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006024 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006025 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006026 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006027 }
6028
6029 /* when we get here, ch is a 32-bit unicode character */
6030 if (ch > MAX_UNICODE) {
6031 message = "illegal Unicode character";
6032 goto error;
6033 }
6034
6035 WRITE_CHAR(ch);
6036 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006037
Benjamin Peterson29060642009-01-31 22:14:21 +00006038 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006039 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006040 if (ucnhash_CAPI == NULL) {
6041 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006042 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6043 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006044 if (ucnhash_CAPI == NULL) {
6045 PyErr_SetString(
6046 PyExc_UnicodeError,
6047 "\\N escapes not supported (can't load unicodedata module)"
6048 );
6049 goto onError;
6050 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006051 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006052
6053 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006054 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006055 const char *start = ++s;
6056 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006057 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006058 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006059 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006060 namelen = s - start;
6061 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006062 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006063 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006064 ch = 0xffffffff; /* in case 'getcode' messes up */
6065 if (namelen <= INT_MAX &&
6066 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6067 &ch, 0)) {
6068 assert(ch <= MAX_UNICODE);
6069 WRITE_CHAR(ch);
6070 continue;
6071 }
6072 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006073 }
6074 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006075 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006076
6077 default:
Eric V. Smith56466482016-10-31 14:46:26 -04006078 if (*first_invalid_escape == NULL) {
6079 *first_invalid_escape = s-1; /* Back up one char, since we've
6080 already incremented s. */
6081 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006082 WRITE_ASCII_CHAR('\\');
6083 WRITE_CHAR(c);
6084 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006086
6087 error:
6088 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006089 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006090 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006091 errors, &errorHandler,
6092 "unicodeescape", message,
6093 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006094 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006095 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006096 }
6097 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6098 goto onError;
6099 }
6100
6101#undef WRITE_ASCII_CHAR
6102#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006103 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006104
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006105 Py_XDECREF(errorHandler);
6106 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006107 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006108
Benjamin Peterson29060642009-01-31 22:14:21 +00006109 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006110 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006111 Py_XDECREF(errorHandler);
6112 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006113 return NULL;
6114}
6115
Eric V. Smith56466482016-10-31 14:46:26 -04006116PyObject *
6117PyUnicode_DecodeUnicodeEscape(const char *s,
6118 Py_ssize_t size,
6119 const char *errors)
6120{
6121 const char *first_invalid_escape;
6122 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6123 &first_invalid_escape);
6124 if (result == NULL)
6125 return NULL;
6126 if (first_invalid_escape != NULL) {
6127 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6128 "invalid escape sequence '\\%c'",
6129 *first_invalid_escape) < 0) {
6130 Py_DECREF(result);
6131 return NULL;
6132 }
6133 }
6134 return result;
6135}
6136
Guido van Rossumd57fd912000-03-10 22:53:23 +00006137/* Return a Unicode-Escape string version of the Unicode object.
6138
6139 If quotes is true, the string is enclosed in u"" or u'' quotes as
6140 appropriate.
6141
6142*/
6143
Alexander Belopolsky40018472011-02-26 01:02:56 +00006144PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006145PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006146{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006147 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006148 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006149 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006150 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006151 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006152 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006153
Ezio Melottie7f90372012-10-05 03:33:31 +03006154 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006155 escape.
6156
Ezio Melottie7f90372012-10-05 03:33:31 +03006157 For UCS1 strings it's '\xxx', 4 bytes per source character.
6158 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6159 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006160 */
6161
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006162 if (!PyUnicode_Check(unicode)) {
6163 PyErr_BadArgument();
6164 return NULL;
6165 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006166 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006167 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006168 }
Victor Stinner358af132015-10-12 22:36:57 +02006169
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006170 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006171 if (len == 0) {
6172 return PyBytes_FromStringAndSize(NULL, 0);
6173 }
6174
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006175 kind = PyUnicode_KIND(unicode);
6176 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006177 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6178 bytes, and 1 byte characters 4. */
6179 expandsize = kind * 2 + 2;
6180 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize) {
6181 return PyErr_NoMemory();
6182 }
6183 repr = PyBytes_FromStringAndSize(NULL, 2 + expandsize * len + 1);
6184 if (repr == NULL) {
6185 return NULL;
6186 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006187
Victor Stinner62ec3312016-09-06 17:04:34 -07006188 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006189 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006190 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006191
Victor Stinner62ec3312016-09-06 17:04:34 -07006192 /* U+0000-U+00ff range */
6193 if (ch < 0x100) {
6194 if (ch >= ' ' && ch < 127) {
6195 if (ch != '\\') {
6196 /* Copy printable US ASCII as-is */
6197 *p++ = (char) ch;
6198 }
6199 /* Escape backslashes */
6200 else {
6201 *p++ = '\\';
6202 *p++ = '\\';
6203 }
6204 }
Victor Stinner358af132015-10-12 22:36:57 +02006205
Victor Stinner62ec3312016-09-06 17:04:34 -07006206 /* Map special whitespace to '\t', \n', '\r' */
6207 else if (ch == '\t') {
6208 *p++ = '\\';
6209 *p++ = 't';
6210 }
6211 else if (ch == '\n') {
6212 *p++ = '\\';
6213 *p++ = 'n';
6214 }
6215 else if (ch == '\r') {
6216 *p++ = '\\';
6217 *p++ = 'r';
6218 }
6219
6220 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6221 else {
6222 *p++ = '\\';
6223 *p++ = 'x';
6224 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6225 *p++ = Py_hexdigits[ch & 0x000F];
6226 }
Tim Petersced69f82003-09-16 20:30:58 +00006227 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006228 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6229 else if (ch < 0x10000) {
6230 /* U+0100-U+ffff */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231 *p++ = '\\';
6232 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006233 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6234 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6235 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6236 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006238 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6239 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006240
Victor Stinner62ec3312016-09-06 17:04:34 -07006241 /* Make sure that the first two digits are zero */
6242 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006243 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006244 *p++ = 'U';
6245 *p++ = '0';
6246 *p++ = '0';
6247 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6248 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6249 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6250 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6251 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6252 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006253 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006255
Victor Stinner62ec3312016-09-06 17:04:34 -07006256 assert(p - PyBytes_AS_STRING(repr) > 0);
6257 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6258 return NULL;
6259 }
6260 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006261}
6262
Alexander Belopolsky40018472011-02-26 01:02:56 +00006263PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006264PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6265 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006266{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006267 PyObject *result;
6268 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006269 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006270 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006271 }
6272
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006273 result = PyUnicode_AsUnicodeEscapeString(tmp);
6274 Py_DECREF(tmp);
6275 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006276}
6277
6278/* --- Raw Unicode Escape Codec ------------------------------------------- */
6279
Alexander Belopolsky40018472011-02-26 01:02:56 +00006280PyObject *
6281PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006282 Py_ssize_t size,
6283 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006284{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006285 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006286 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006287 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006288 PyObject *errorHandler = NULL;
6289 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006290
Victor Stinner62ec3312016-09-06 17:04:34 -07006291 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006292 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006293 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006294
Guido van Rossumd57fd912000-03-10 22:53:23 +00006295 /* Escaped strings will always be longer than the resulting
6296 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006297 length after conversion to the true value. (But decoding error
6298 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006299 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006300 writer.min_length = size;
6301 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6302 goto onError;
6303 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006304
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305 end = s + size;
6306 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006307 unsigned char c = (unsigned char) *s++;
6308 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006309 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006310 Py_ssize_t startinpos;
6311 Py_ssize_t endinpos;
6312 const char *message;
6313
6314#define WRITE_CHAR(ch) \
6315 do { \
6316 if (ch <= writer.maxchar) { \
6317 assert(writer.pos < writer.size); \
6318 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6319 } \
6320 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6321 goto onError; \
6322 } \
6323 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006324
Benjamin Peterson29060642009-01-31 22:14:21 +00006325 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006326 if (c != '\\' || s >= end) {
6327 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006328 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006329 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006330
Victor Stinner62ec3312016-09-06 17:04:34 -07006331 c = (unsigned char) *s++;
6332 if (c == 'u') {
6333 count = 4;
6334 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006335 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006336 else if (c == 'U') {
6337 count = 8;
6338 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006339 }
6340 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006341 assert(writer.pos < writer.size);
6342 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6343 WRITE_CHAR(c);
6344 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006345 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006346 startinpos = s - starts - 2;
6347
6348 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6349 for (ch = 0; count && s < end; ++s, --count) {
6350 c = (unsigned char)*s;
6351 ch <<= 4;
6352 if (c >= '0' && c <= '9') {
6353 ch += c - '0';
6354 }
6355 else if (c >= 'a' && c <= 'f') {
6356 ch += c - ('a' - 10);
6357 }
6358 else if (c >= 'A' && c <= 'F') {
6359 ch += c - ('A' - 10);
6360 }
6361 else {
6362 break;
6363 }
6364 }
6365 if (!count) {
6366 if (ch <= MAX_UNICODE) {
6367 WRITE_CHAR(ch);
6368 continue;
6369 }
6370 message = "\\Uxxxxxxxx out of range";
6371 }
6372
6373 endinpos = s-starts;
6374 writer.min_length = end - s + writer.pos;
6375 if (unicode_decode_call_errorhandler_writer(
6376 errors, &errorHandler,
6377 "rawunicodeescape", message,
6378 &starts, &end, &startinpos, &endinpos, &exc, &s,
6379 &writer)) {
6380 goto onError;
6381 }
6382 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6383 goto onError;
6384 }
6385
6386#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006387 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006388 Py_XDECREF(errorHandler);
6389 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006390 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006391
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006393 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394 Py_XDECREF(errorHandler);
6395 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006396 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006397
Guido van Rossumd57fd912000-03-10 22:53:23 +00006398}
6399
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006400
Alexander Belopolsky40018472011-02-26 01:02:56 +00006401PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006402PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006403{
Victor Stinner62ec3312016-09-06 17:04:34 -07006404 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006405 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006406 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006407 int kind;
6408 void *data;
6409 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006410
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006411 if (!PyUnicode_Check(unicode)) {
6412 PyErr_BadArgument();
6413 return NULL;
6414 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006415 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006416 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006417 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006418 kind = PyUnicode_KIND(unicode);
6419 data = PyUnicode_DATA(unicode);
6420 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006421 if (kind == PyUnicode_1BYTE_KIND) {
6422 return PyBytes_FromStringAndSize(data, len);
6423 }
Victor Stinner0e368262011-11-10 20:12:49 +01006424
Victor Stinner62ec3312016-09-06 17:04:34 -07006425 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6426 bytes, and 1 byte characters 4. */
6427 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006428
Victor Stinner62ec3312016-09-06 17:04:34 -07006429 if (len > PY_SSIZE_T_MAX / expandsize) {
6430 return PyErr_NoMemory();
6431 }
6432 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6433 if (repr == NULL) {
6434 return NULL;
6435 }
6436 if (len == 0) {
6437 return repr;
6438 }
6439
6440 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006441 for (pos = 0; pos < len; pos++) {
6442 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006443
Victor Stinner62ec3312016-09-06 17:04:34 -07006444 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6445 if (ch < 0x100) {
6446 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006447 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006448 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6449 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006450 *p++ = '\\';
6451 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006452 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6453 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6454 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6455 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006456 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006457 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6458 else {
6459 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6460 *p++ = '\\';
6461 *p++ = 'U';
6462 *p++ = '0';
6463 *p++ = '0';
6464 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6465 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6466 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6467 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6468 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6469 *p++ = Py_hexdigits[ch & 15];
6470 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006471 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006472
Victor Stinner62ec3312016-09-06 17:04:34 -07006473 assert(p > PyBytes_AS_STRING(repr));
6474 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6475 return NULL;
6476 }
6477 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006478}
6479
Alexander Belopolsky40018472011-02-26 01:02:56 +00006480PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006481PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6482 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006483{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006484 PyObject *result;
6485 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6486 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006487 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006488 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6489 Py_DECREF(tmp);
6490 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006491}
6492
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006493/* --- Unicode Internal Codec ------------------------------------------- */
6494
Alexander Belopolsky40018472011-02-26 01:02:56 +00006495PyObject *
6496_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006497 Py_ssize_t size,
6498 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006499{
6500 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006501 Py_ssize_t startinpos;
6502 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006503 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006504 const char *end;
6505 const char *reason;
6506 PyObject *errorHandler = NULL;
6507 PyObject *exc = NULL;
6508
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006509 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006510 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006511 1))
6512 return NULL;
6513
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006514 if (size == 0)
6515 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006516
Victor Stinner8f674cc2013-04-17 23:02:17 +02006517 _PyUnicodeWriter_Init(&writer);
6518 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6519 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006520 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006521 }
6522 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006523
Victor Stinner8f674cc2013-04-17 23:02:17 +02006524 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006525 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006526 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006527 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006528 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006529 endinpos = end-starts;
6530 reason = "truncated input";
6531 goto error;
6532 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006533 /* We copy the raw representation one byte at a time because the
6534 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006535 ((char *) &uch)[0] = s[0];
6536 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006537#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006538 ((char *) &uch)[2] = s[2];
6539 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006540#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006541 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006542#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006543 /* We have to sanity check the raw data, otherwise doom looms for
6544 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006545 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006546 endinpos = s - starts + Py_UNICODE_SIZE;
6547 reason = "illegal code point (> 0x10FFFF)";
6548 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006549 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006550#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006551 s += Py_UNICODE_SIZE;
6552#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006553 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006554 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006555 Py_UNICODE uch2;
6556 ((char *) &uch2)[0] = s[0];
6557 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006558 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006559 {
Victor Stinner551ac952011-11-29 22:58:13 +01006560 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006561 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006562 }
6563 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006564#endif
6565
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006566 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006567 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006568 continue;
6569
6570 error:
6571 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006572 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006573 errors, &errorHandler,
6574 "unicode_internal", reason,
6575 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006576 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006577 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006578 }
6579
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006580 Py_XDECREF(errorHandler);
6581 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006582 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006583
Benjamin Peterson29060642009-01-31 22:14:21 +00006584 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006585 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006586 Py_XDECREF(errorHandler);
6587 Py_XDECREF(exc);
6588 return NULL;
6589}
6590
Guido van Rossumd57fd912000-03-10 22:53:23 +00006591/* --- Latin-1 Codec ------------------------------------------------------ */
6592
Alexander Belopolsky40018472011-02-26 01:02:56 +00006593PyObject *
6594PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006595 Py_ssize_t size,
6596 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006597{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006598 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006599 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006600}
6601
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006602/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006603static void
6604make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006605 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006606 PyObject *unicode,
6607 Py_ssize_t startpos, Py_ssize_t endpos,
6608 const char *reason)
6609{
6610 if (*exceptionObject == NULL) {
6611 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006612 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006613 encoding, unicode, startpos, endpos, reason);
6614 }
6615 else {
6616 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6617 goto onError;
6618 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6619 goto onError;
6620 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6621 goto onError;
6622 return;
6623 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006624 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006625 }
6626}
6627
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006628/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006629static void
6630raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006631 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006632 PyObject *unicode,
6633 Py_ssize_t startpos, Py_ssize_t endpos,
6634 const char *reason)
6635{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006636 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006637 encoding, unicode, startpos, endpos, reason);
6638 if (*exceptionObject != NULL)
6639 PyCodec_StrictErrors(*exceptionObject);
6640}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006641
6642/* error handling callback helper:
6643 build arguments, call the callback and check the arguments,
6644 put the result into newpos and return the replacement string, which
6645 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006646static PyObject *
6647unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006648 PyObject **errorHandler,
6649 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006650 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006651 Py_ssize_t startpos, Py_ssize_t endpos,
6652 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006654 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006655 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006656 PyObject *restuple;
6657 PyObject *resunicode;
6658
6659 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006660 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006661 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006662 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006663 }
6664
Benjamin Petersonbac79492012-01-14 13:34:47 -05006665 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006666 return NULL;
6667 len = PyUnicode_GET_LENGTH(unicode);
6668
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006669 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006670 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006671 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006672 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006673
6674 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006675 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006676 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006677 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006678 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006679 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006680 Py_DECREF(restuple);
6681 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006683 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006684 &resunicode, newpos)) {
6685 Py_DECREF(restuple);
6686 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006687 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006688 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6689 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6690 Py_DECREF(restuple);
6691 return NULL;
6692 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006693 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006694 *newpos = len + *newpos;
6695 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006696 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006697 Py_DECREF(restuple);
6698 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006699 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006700 Py_INCREF(resunicode);
6701 Py_DECREF(restuple);
6702 return resunicode;
6703}
6704
Alexander Belopolsky40018472011-02-26 01:02:56 +00006705static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006706unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006707 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006708 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006709{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006710 /* input state */
6711 Py_ssize_t pos=0, size;
6712 int kind;
6713 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006714 /* pointer into the output */
6715 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006716 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6717 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006718 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006719 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006720 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006721 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006722 /* output object */
6723 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006724
Benjamin Petersonbac79492012-01-14 13:34:47 -05006725 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006726 return NULL;
6727 size = PyUnicode_GET_LENGTH(unicode);
6728 kind = PyUnicode_KIND(unicode);
6729 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006730 /* allocate enough for a simple encoding without
6731 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006732 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006733 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006734
6735 _PyBytesWriter_Init(&writer);
6736 str = _PyBytesWriter_Alloc(&writer, size);
6737 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006738 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006739
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006740 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006741 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006742
Benjamin Peterson29060642009-01-31 22:14:21 +00006743 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006744 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006745 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006746 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006747 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006748 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006750 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006751 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006752 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006753 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006754 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006755
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006756 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006757 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006758
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006759 /* Only overallocate the buffer if it's not the last write */
6760 writer.overallocate = (collend < size);
6761
Benjamin Peterson29060642009-01-31 22:14:21 +00006762 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006763 if (error_handler == _Py_ERROR_UNKNOWN)
6764 error_handler = get_error_handler(errors);
6765
6766 switch (error_handler) {
6767 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006768 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006769 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006770
6771 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006772 memset(str, '?', collend - collstart);
6773 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006774 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006775 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006776 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006777 break;
Victor Stinner50149202015-09-22 00:26:54 +02006778
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006779 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006780 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006781 writer.min_size -= (collend - collstart);
6782 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006783 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006784 if (str == NULL)
6785 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006786 pos = collend;
6787 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006788
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006789 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006790 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006791 writer.min_size -= (collend - collstart);
6792 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006793 unicode, collstart, collend);
6794 if (str == NULL)
6795 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006796 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006797 break;
Victor Stinner50149202015-09-22 00:26:54 +02006798
Victor Stinnerc3713e92015-09-29 12:32:13 +02006799 case _Py_ERROR_SURROGATEESCAPE:
6800 for (i = collstart; i < collend; ++i) {
6801 ch = PyUnicode_READ(kind, data, i);
6802 if (ch < 0xdc80 || 0xdcff < ch) {
6803 /* Not a UTF-8b surrogate */
6804 break;
6805 }
6806 *str++ = (char)(ch - 0xdc00);
6807 ++pos;
6808 }
6809 if (i >= collend)
6810 break;
6811 collstart = pos;
6812 assert(collstart != collend);
6813 /* fallback to general error handling */
6814
Benjamin Peterson29060642009-01-31 22:14:21 +00006815 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006816 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6817 encoding, reason, unicode, &exc,
6818 collstart, collend, &newpos);
6819 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006820 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006821
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006822 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006823 writer.min_size -= 1;
6824
Victor Stinner6bd525b2015-10-09 13:10:05 +02006825 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006826 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006827 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006828 PyBytes_AS_STRING(rep),
6829 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006830 if (str == NULL)
6831 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006832 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006833 else {
6834 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006835
Victor Stinner6bd525b2015-10-09 13:10:05 +02006836 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006837 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006838
6839 if (PyUnicode_IS_ASCII(rep)) {
6840 /* Fast path: all characters are smaller than limit */
6841 assert(limit >= 128);
6842 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6843 str = _PyBytesWriter_WriteBytes(&writer, str,
6844 PyUnicode_DATA(rep),
6845 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006846 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006847 else {
6848 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6849
6850 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6851 if (str == NULL)
6852 goto onError;
6853
6854 /* check if there is anything unencodable in the
6855 replacement and copy it to the output */
6856 for (i = 0; repsize-->0; ++i, ++str) {
6857 ch = PyUnicode_READ_CHAR(rep, i);
6858 if (ch >= limit) {
6859 raise_encode_exception(&exc, encoding, unicode,
6860 pos, pos+1, reason);
6861 goto onError;
6862 }
6863 *str = (char)ch;
6864 }
6865 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006866 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006867 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006868 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006869 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006870
6871 /* If overallocation was disabled, ensure that it was the last
6872 write. Otherwise, we missed an optimization */
6873 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006874 }
6875 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006876
Victor Stinner50149202015-09-22 00:26:54 +02006877 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006878 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006879 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006880
6881 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006882 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006883 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006884 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006885 Py_XDECREF(exc);
6886 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006887}
6888
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006889/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006890PyObject *
6891PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006892 Py_ssize_t size,
6893 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006894{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006895 PyObject *result;
6896 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6897 if (unicode == NULL)
6898 return NULL;
6899 result = unicode_encode_ucs1(unicode, errors, 256);
6900 Py_DECREF(unicode);
6901 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006902}
6903
Alexander Belopolsky40018472011-02-26 01:02:56 +00006904PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006905_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006906{
6907 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006908 PyErr_BadArgument();
6909 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006910 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006911 if (PyUnicode_READY(unicode) == -1)
6912 return NULL;
6913 /* Fast path: if it is a one-byte string, construct
6914 bytes object directly. */
6915 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6916 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6917 PyUnicode_GET_LENGTH(unicode));
6918 /* Non-Latin-1 characters present. Defer to above function to
6919 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006920 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006921}
6922
6923PyObject*
6924PyUnicode_AsLatin1String(PyObject *unicode)
6925{
6926 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006927}
6928
6929/* --- 7-bit ASCII Codec -------------------------------------------------- */
6930
Alexander Belopolsky40018472011-02-26 01:02:56 +00006931PyObject *
6932PyUnicode_DecodeASCII(const char *s,
6933 Py_ssize_t size,
6934 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006935{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006936 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006937 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006938 int kind;
6939 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006940 Py_ssize_t startinpos;
6941 Py_ssize_t endinpos;
6942 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006943 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006944 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006945 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006946 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006947
Guido van Rossumd57fd912000-03-10 22:53:23 +00006948 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006949 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006950
Guido van Rossumd57fd912000-03-10 22:53:23 +00006951 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006952 if (size == 1 && (unsigned char)s[0] < 128)
6953 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006954
Victor Stinner8f674cc2013-04-17 23:02:17 +02006955 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006956 writer.min_length = size;
6957 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006958 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006959
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006960 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006961 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006962 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006963 writer.pos = outpos;
6964 if (writer.pos == size)
6965 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006966
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006967 s += writer.pos;
6968 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006969 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006970 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006971 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006972 PyUnicode_WRITE(kind, data, writer.pos, c);
6973 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006974 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006975 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006976 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006977
6978 /* byte outsize range 0x00..0x7f: call the error handler */
6979
6980 if (error_handler == _Py_ERROR_UNKNOWN)
6981 error_handler = get_error_handler(errors);
6982
6983 switch (error_handler)
6984 {
6985 case _Py_ERROR_REPLACE:
6986 case _Py_ERROR_SURROGATEESCAPE:
6987 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006988 but we may switch to UCS2 at the first write */
6989 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6990 goto onError;
6991 kind = writer.kind;
6992 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006993
6994 if (error_handler == _Py_ERROR_REPLACE)
6995 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6996 else
6997 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6998 writer.pos++;
6999 ++s;
7000 break;
7001
7002 case _Py_ERROR_IGNORE:
7003 ++s;
7004 break;
7005
7006 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007007 startinpos = s-starts;
7008 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007009 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007010 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007011 "ascii", "ordinal not in range(128)",
7012 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007013 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007014 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007015 kind = writer.kind;
7016 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007017 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007018 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007019 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007020 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007021 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007022
Benjamin Peterson29060642009-01-31 22:14:21 +00007023 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007024 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007025 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007026 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007027 return NULL;
7028}
7029
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007030/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007031PyObject *
7032PyUnicode_EncodeASCII(const Py_UNICODE *p,
7033 Py_ssize_t size,
7034 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007035{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007036 PyObject *result;
7037 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7038 if (unicode == NULL)
7039 return NULL;
7040 result = unicode_encode_ucs1(unicode, errors, 128);
7041 Py_DECREF(unicode);
7042 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007043}
7044
Alexander Belopolsky40018472011-02-26 01:02:56 +00007045PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007046_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007047{
7048 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007049 PyErr_BadArgument();
7050 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007051 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007052 if (PyUnicode_READY(unicode) == -1)
7053 return NULL;
7054 /* Fast path: if it is an ASCII-only string, construct bytes object
7055 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007056 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007057 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7058 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007059 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007060}
7061
7062PyObject *
7063PyUnicode_AsASCIIString(PyObject *unicode)
7064{
7065 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007066}
7067
Steve Dowercc16be82016-09-08 10:35:16 -07007068#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007069
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007070/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007071
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007072#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073#define NEED_RETRY
7074#endif
7075
Victor Stinner3a50e702011-10-18 21:21:00 +02007076#ifndef WC_ERR_INVALID_CHARS
7077# define WC_ERR_INVALID_CHARS 0x0080
7078#endif
7079
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007080static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007081code_page_name(UINT code_page, PyObject **obj)
7082{
7083 *obj = NULL;
7084 if (code_page == CP_ACP)
7085 return "mbcs";
7086 if (code_page == CP_UTF7)
7087 return "CP_UTF7";
7088 if (code_page == CP_UTF8)
7089 return "CP_UTF8";
7090
7091 *obj = PyBytes_FromFormat("cp%u", code_page);
7092 if (*obj == NULL)
7093 return NULL;
7094 return PyBytes_AS_STRING(*obj);
7095}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007096
Victor Stinner3a50e702011-10-18 21:21:00 +02007097static DWORD
7098decode_code_page_flags(UINT code_page)
7099{
7100 if (code_page == CP_UTF7) {
7101 /* The CP_UTF7 decoder only supports flags=0 */
7102 return 0;
7103 }
7104 else
7105 return MB_ERR_INVALID_CHARS;
7106}
7107
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007108/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007109 * Decode a byte string from a Windows code page into unicode object in strict
7110 * mode.
7111 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007112 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7113 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007115static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007116decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007117 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007118 const char *in,
7119 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007120{
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007122 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007123 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007124
7125 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007126 assert(insize > 0);
7127 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7128 if (outsize <= 0)
7129 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007130
7131 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007132 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007133 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007134 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007135 if (*v == NULL)
7136 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007137 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007138 }
7139 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007140 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007141 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007142 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007143 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007144 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007145 }
7146
7147 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007148 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7149 if (outsize <= 0)
7150 goto error;
7151 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007152
Victor Stinner3a50e702011-10-18 21:21:00 +02007153error:
7154 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7155 return -2;
7156 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007157 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007158}
7159
Victor Stinner3a50e702011-10-18 21:21:00 +02007160/*
7161 * Decode a byte string from a code page into unicode object with an error
7162 * handler.
7163 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007164 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007165 * UnicodeDecodeError exception and returns -1 on error.
7166 */
7167static int
7168decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007169 PyObject **v,
7170 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007171 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007172{
7173 const char *startin = in;
7174 const char *endin = in + size;
7175 const DWORD flags = decode_code_page_flags(code_page);
7176 /* Ideally, we should get reason from FormatMessage. This is the Windows
7177 2000 English version of the message. */
7178 const char *reason = "No mapping for the Unicode character exists "
7179 "in the target code page.";
7180 /* each step cannot decode more than 1 character, but a character can be
7181 represented as a surrogate pair */
7182 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007183 int insize;
7184 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007185 PyObject *errorHandler = NULL;
7186 PyObject *exc = NULL;
7187 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007188 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007189 DWORD err;
7190 int ret = -1;
7191
7192 assert(size > 0);
7193
7194 encoding = code_page_name(code_page, &encoding_obj);
7195 if (encoding == NULL)
7196 return -1;
7197
Victor Stinner7d00cc12014-03-17 23:08:06 +01007198 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007199 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7200 UnicodeDecodeError. */
7201 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7202 if (exc != NULL) {
7203 PyCodec_StrictErrors(exc);
7204 Py_CLEAR(exc);
7205 }
7206 goto error;
7207 }
7208
7209 if (*v == NULL) {
7210 /* Create unicode object */
7211 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7212 PyErr_NoMemory();
7213 goto error;
7214 }
Victor Stinnerab595942011-12-17 04:59:06 +01007215 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007216 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 if (*v == NULL)
7218 goto error;
7219 startout = PyUnicode_AS_UNICODE(*v);
7220 }
7221 else {
7222 /* Extend unicode object */
7223 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7224 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7225 PyErr_NoMemory();
7226 goto error;
7227 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007228 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007229 goto error;
7230 startout = PyUnicode_AS_UNICODE(*v) + n;
7231 }
7232
7233 /* Decode the byte string character per character */
7234 out = startout;
7235 while (in < endin)
7236 {
7237 /* Decode a character */
7238 insize = 1;
7239 do
7240 {
7241 outsize = MultiByteToWideChar(code_page, flags,
7242 in, insize,
7243 buffer, Py_ARRAY_LENGTH(buffer));
7244 if (outsize > 0)
7245 break;
7246 err = GetLastError();
7247 if (err != ERROR_NO_UNICODE_TRANSLATION
7248 && err != ERROR_INSUFFICIENT_BUFFER)
7249 {
7250 PyErr_SetFromWindowsErr(0);
7251 goto error;
7252 }
7253 insize++;
7254 }
7255 /* 4=maximum length of a UTF-8 sequence */
7256 while (insize <= 4 && (in + insize) <= endin);
7257
7258 if (outsize <= 0) {
7259 Py_ssize_t startinpos, endinpos, outpos;
7260
Victor Stinner7d00cc12014-03-17 23:08:06 +01007261 /* last character in partial decode? */
7262 if (in + insize >= endin && !final)
7263 break;
7264
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 startinpos = in - startin;
7266 endinpos = startinpos + 1;
7267 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007268 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007269 errors, &errorHandler,
7270 encoding, reason,
7271 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007272 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007273 {
7274 goto error;
7275 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007276 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007277 }
7278 else {
7279 in += insize;
7280 memcpy(out, buffer, outsize * sizeof(wchar_t));
7281 out += outsize;
7282 }
7283 }
7284
7285 /* write a NUL character at the end */
7286 *out = 0;
7287
7288 /* Extend unicode object */
7289 outsize = out - startout;
7290 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007291 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007292 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007293 /* (in - startin) <= size and size is an int */
7294 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007295
7296error:
7297 Py_XDECREF(encoding_obj);
7298 Py_XDECREF(errorHandler);
7299 Py_XDECREF(exc);
7300 return ret;
7301}
7302
Victor Stinner3a50e702011-10-18 21:21:00 +02007303static PyObject *
7304decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007305 const char *s, Py_ssize_t size,
7306 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007307{
Victor Stinner76a31a62011-11-04 00:05:13 +01007308 PyObject *v = NULL;
7309 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007310
Victor Stinner3a50e702011-10-18 21:21:00 +02007311 if (code_page < 0) {
7312 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7313 return NULL;
7314 }
7315
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007316 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007317 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007318
Victor Stinner76a31a62011-11-04 00:05:13 +01007319 do
7320 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007321#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007322 if (size > INT_MAX) {
7323 chunk_size = INT_MAX;
7324 final = 0;
7325 done = 0;
7326 }
7327 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007328#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007329 {
7330 chunk_size = (int)size;
7331 final = (consumed == NULL);
7332 done = 1;
7333 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007334
Victor Stinner76a31a62011-11-04 00:05:13 +01007335 if (chunk_size == 0 && done) {
7336 if (v != NULL)
7337 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007338 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007339 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007340
Victor Stinner76a31a62011-11-04 00:05:13 +01007341 converted = decode_code_page_strict(code_page, &v,
7342 s, chunk_size);
7343 if (converted == -2)
7344 converted = decode_code_page_errors(code_page, &v,
7345 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007346 errors, final);
7347 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007348
7349 if (converted < 0) {
7350 Py_XDECREF(v);
7351 return NULL;
7352 }
7353
7354 if (consumed)
7355 *consumed += converted;
7356
7357 s += converted;
7358 size -= converted;
7359 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007360
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007361 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007362}
7363
Alexander Belopolsky40018472011-02-26 01:02:56 +00007364PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007365PyUnicode_DecodeCodePageStateful(int code_page,
7366 const char *s,
7367 Py_ssize_t size,
7368 const char *errors,
7369 Py_ssize_t *consumed)
7370{
7371 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7372}
7373
7374PyObject *
7375PyUnicode_DecodeMBCSStateful(const char *s,
7376 Py_ssize_t size,
7377 const char *errors,
7378 Py_ssize_t *consumed)
7379{
7380 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7381}
7382
7383PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007384PyUnicode_DecodeMBCS(const char *s,
7385 Py_ssize_t size,
7386 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007387{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007388 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7389}
7390
Victor Stinner3a50e702011-10-18 21:21:00 +02007391static DWORD
7392encode_code_page_flags(UINT code_page, const char *errors)
7393{
7394 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007395 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007396 }
7397 else if (code_page == CP_UTF7) {
7398 /* CP_UTF7 only supports flags=0 */
7399 return 0;
7400 }
7401 else {
7402 if (errors != NULL && strcmp(errors, "replace") == 0)
7403 return 0;
7404 else
7405 return WC_NO_BEST_FIT_CHARS;
7406 }
7407}
7408
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007409/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007410 * Encode a Unicode string to a Windows code page into a byte string in strict
7411 * mode.
7412 *
7413 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007414 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007415 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007416static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007417encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007418 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007419 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007420{
Victor Stinner554f3f02010-06-16 23:33:54 +00007421 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007422 BOOL *pusedDefaultChar = &usedDefaultChar;
7423 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007424 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007425 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 const DWORD flags = encode_code_page_flags(code_page, NULL);
7427 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007428 /* Create a substring so that we can get the UTF-16 representation
7429 of just the slice under consideration. */
7430 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007431
Martin v. Löwis3d325192011-11-04 18:23:06 +01007432 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007433
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007435 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007436 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007437 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007438
Victor Stinner2fc507f2011-11-04 20:06:39 +01007439 substring = PyUnicode_Substring(unicode, offset, offset+len);
7440 if (substring == NULL)
7441 return -1;
7442 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7443 if (p == NULL) {
7444 Py_DECREF(substring);
7445 return -1;
7446 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007447 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007448
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007449 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007450 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007451 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007452 NULL, 0,
7453 NULL, pusedDefaultChar);
7454 if (outsize <= 0)
7455 goto error;
7456 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007457 if (pusedDefaultChar && *pusedDefaultChar) {
7458 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007460 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007461
Victor Stinner3a50e702011-10-18 21:21:00 +02007462 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007463 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007464 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007465 if (*outbytes == NULL) {
7466 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007467 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007468 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007469 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007470 }
7471 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007472 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007473 const Py_ssize_t n = PyBytes_Size(*outbytes);
7474 if (outsize > PY_SSIZE_T_MAX - n) {
7475 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007476 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007477 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007478 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007479 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7480 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007481 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007482 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007483 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007484 }
7485
7486 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007487 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007488 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007489 out, outsize,
7490 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007491 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 if (outsize <= 0)
7493 goto error;
7494 if (pusedDefaultChar && *pusedDefaultChar)
7495 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007496 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007497
Victor Stinner3a50e702011-10-18 21:21:00 +02007498error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007499 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007500 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7501 return -2;
7502 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007503 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007504}
7505
Victor Stinner3a50e702011-10-18 21:21:00 +02007506/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007507 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007508 * error handler.
7509 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007510 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007511 * -1 on other error.
7512 */
7513static int
7514encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007515 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007516 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007517{
Victor Stinner3a50e702011-10-18 21:21:00 +02007518 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007519 Py_ssize_t pos = unicode_offset;
7520 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007521 /* Ideally, we should get reason from FormatMessage. This is the Windows
7522 2000 English version of the message. */
7523 const char *reason = "invalid character";
7524 /* 4=maximum length of a UTF-8 sequence */
7525 char buffer[4];
7526 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7527 Py_ssize_t outsize;
7528 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007529 PyObject *errorHandler = NULL;
7530 PyObject *exc = NULL;
7531 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007532 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007533 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007534 PyObject *rep;
7535 int ret = -1;
7536
7537 assert(insize > 0);
7538
7539 encoding = code_page_name(code_page, &encoding_obj);
7540 if (encoding == NULL)
7541 return -1;
7542
7543 if (errors == NULL || strcmp(errors, "strict") == 0) {
7544 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7545 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007546 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007547 if (exc != NULL) {
7548 PyCodec_StrictErrors(exc);
7549 Py_DECREF(exc);
7550 }
7551 Py_XDECREF(encoding_obj);
7552 return -1;
7553 }
7554
7555 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7556 pusedDefaultChar = &usedDefaultChar;
7557 else
7558 pusedDefaultChar = NULL;
7559
7560 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7561 PyErr_NoMemory();
7562 goto error;
7563 }
7564 outsize = insize * Py_ARRAY_LENGTH(buffer);
7565
7566 if (*outbytes == NULL) {
7567 /* Create string object */
7568 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7569 if (*outbytes == NULL)
7570 goto error;
7571 out = PyBytes_AS_STRING(*outbytes);
7572 }
7573 else {
7574 /* Extend string object */
7575 Py_ssize_t n = PyBytes_Size(*outbytes);
7576 if (n > PY_SSIZE_T_MAX - outsize) {
7577 PyErr_NoMemory();
7578 goto error;
7579 }
7580 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7581 goto error;
7582 out = PyBytes_AS_STRING(*outbytes) + n;
7583 }
7584
7585 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007586 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007587 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007588 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7589 wchar_t chars[2];
7590 int charsize;
7591 if (ch < 0x10000) {
7592 chars[0] = (wchar_t)ch;
7593 charsize = 1;
7594 }
7595 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007596 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7597 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007598 charsize = 2;
7599 }
7600
Victor Stinner3a50e702011-10-18 21:21:00 +02007601 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007602 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007603 buffer, Py_ARRAY_LENGTH(buffer),
7604 NULL, pusedDefaultChar);
7605 if (outsize > 0) {
7606 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7607 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007608 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007609 memcpy(out, buffer, outsize);
7610 out += outsize;
7611 continue;
7612 }
7613 }
7614 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7615 PyErr_SetFromWindowsErr(0);
7616 goto error;
7617 }
7618
Victor Stinner3a50e702011-10-18 21:21:00 +02007619 rep = unicode_encode_call_errorhandler(
7620 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007621 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007622 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007623 if (rep == NULL)
7624 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007625 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007626
7627 if (PyBytes_Check(rep)) {
7628 outsize = PyBytes_GET_SIZE(rep);
7629 if (outsize != 1) {
7630 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7631 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7632 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7633 Py_DECREF(rep);
7634 goto error;
7635 }
7636 out = PyBytes_AS_STRING(*outbytes) + offset;
7637 }
7638 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7639 out += outsize;
7640 }
7641 else {
7642 Py_ssize_t i;
7643 enum PyUnicode_Kind kind;
7644 void *data;
7645
Benjamin Petersonbac79492012-01-14 13:34:47 -05007646 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007647 Py_DECREF(rep);
7648 goto error;
7649 }
7650
7651 outsize = PyUnicode_GET_LENGTH(rep);
7652 if (outsize != 1) {
7653 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7654 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7655 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7656 Py_DECREF(rep);
7657 goto error;
7658 }
7659 out = PyBytes_AS_STRING(*outbytes) + offset;
7660 }
7661 kind = PyUnicode_KIND(rep);
7662 data = PyUnicode_DATA(rep);
7663 for (i=0; i < outsize; i++) {
7664 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7665 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007666 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007667 encoding, unicode,
7668 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007669 "unable to encode error handler result to ASCII");
7670 Py_DECREF(rep);
7671 goto error;
7672 }
7673 *out = (unsigned char)ch;
7674 out++;
7675 }
7676 }
7677 Py_DECREF(rep);
7678 }
7679 /* write a NUL byte */
7680 *out = 0;
7681 outsize = out - PyBytes_AS_STRING(*outbytes);
7682 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7683 if (_PyBytes_Resize(outbytes, outsize) < 0)
7684 goto error;
7685 ret = 0;
7686
7687error:
7688 Py_XDECREF(encoding_obj);
7689 Py_XDECREF(errorHandler);
7690 Py_XDECREF(exc);
7691 return ret;
7692}
7693
Victor Stinner3a50e702011-10-18 21:21:00 +02007694static PyObject *
7695encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007696 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007697 const char *errors)
7698{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007699 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007700 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007701 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007702 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007703
Victor Stinner29dacf22015-01-26 16:41:32 +01007704 if (!PyUnicode_Check(unicode)) {
7705 PyErr_BadArgument();
7706 return NULL;
7707 }
7708
Benjamin Petersonbac79492012-01-14 13:34:47 -05007709 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007710 return NULL;
7711 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007712
Victor Stinner3a50e702011-10-18 21:21:00 +02007713 if (code_page < 0) {
7714 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7715 return NULL;
7716 }
7717
Martin v. Löwis3d325192011-11-04 18:23:06 +01007718 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007719 return PyBytes_FromStringAndSize(NULL, 0);
7720
Victor Stinner7581cef2011-11-03 22:32:33 +01007721 offset = 0;
7722 do
7723 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007724#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007725 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007726 chunks. */
7727 if (len > INT_MAX/2) {
7728 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007729 done = 0;
7730 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007731 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007732#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007733 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007734 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007735 done = 1;
7736 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007737
Victor Stinner76a31a62011-11-04 00:05:13 +01007738 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007739 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007740 errors);
7741 if (ret == -2)
7742 ret = encode_code_page_errors(code_page, &outbytes,
7743 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007744 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007745 if (ret < 0) {
7746 Py_XDECREF(outbytes);
7747 return NULL;
7748 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007749
Victor Stinner7581cef2011-11-03 22:32:33 +01007750 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007751 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007752 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007753
Victor Stinner3a50e702011-10-18 21:21:00 +02007754 return outbytes;
7755}
7756
7757PyObject *
7758PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7759 Py_ssize_t size,
7760 const char *errors)
7761{
Victor Stinner7581cef2011-11-03 22:32:33 +01007762 PyObject *unicode, *res;
7763 unicode = PyUnicode_FromUnicode(p, size);
7764 if (unicode == NULL)
7765 return NULL;
7766 res = encode_code_page(CP_ACP, unicode, errors);
7767 Py_DECREF(unicode);
7768 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007769}
7770
7771PyObject *
7772PyUnicode_EncodeCodePage(int code_page,
7773 PyObject *unicode,
7774 const char *errors)
7775{
Victor Stinner7581cef2011-11-03 22:32:33 +01007776 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007777}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007778
Alexander Belopolsky40018472011-02-26 01:02:56 +00007779PyObject *
7780PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007781{
Victor Stinner7581cef2011-11-03 22:32:33 +01007782 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007783}
7784
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007785#undef NEED_RETRY
7786
Steve Dowercc16be82016-09-08 10:35:16 -07007787#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007788
Guido van Rossumd57fd912000-03-10 22:53:23 +00007789/* --- Character Mapping Codec -------------------------------------------- */
7790
Victor Stinnerfb161b12013-04-18 01:44:27 +02007791static int
7792charmap_decode_string(const char *s,
7793 Py_ssize_t size,
7794 PyObject *mapping,
7795 const char *errors,
7796 _PyUnicodeWriter *writer)
7797{
7798 const char *starts = s;
7799 const char *e;
7800 Py_ssize_t startinpos, endinpos;
7801 PyObject *errorHandler = NULL, *exc = NULL;
7802 Py_ssize_t maplen;
7803 enum PyUnicode_Kind mapkind;
7804 void *mapdata;
7805 Py_UCS4 x;
7806 unsigned char ch;
7807
7808 if (PyUnicode_READY(mapping) == -1)
7809 return -1;
7810
7811 maplen = PyUnicode_GET_LENGTH(mapping);
7812 mapdata = PyUnicode_DATA(mapping);
7813 mapkind = PyUnicode_KIND(mapping);
7814
7815 e = s + size;
7816
7817 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7818 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7819 * is disabled in encoding aliases, latin1 is preferred because
7820 * its implementation is faster. */
7821 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7822 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7823 Py_UCS4 maxchar = writer->maxchar;
7824
7825 assert (writer->kind == PyUnicode_1BYTE_KIND);
7826 while (s < e) {
7827 ch = *s;
7828 x = mapdata_ucs1[ch];
7829 if (x > maxchar) {
7830 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7831 goto onError;
7832 maxchar = writer->maxchar;
7833 outdata = (Py_UCS1 *)writer->data;
7834 }
7835 outdata[writer->pos] = x;
7836 writer->pos++;
7837 ++s;
7838 }
7839 return 0;
7840 }
7841
7842 while (s < e) {
7843 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7844 enum PyUnicode_Kind outkind = writer->kind;
7845 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7846 if (outkind == PyUnicode_1BYTE_KIND) {
7847 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7848 Py_UCS4 maxchar = writer->maxchar;
7849 while (s < e) {
7850 ch = *s;
7851 x = mapdata_ucs2[ch];
7852 if (x > maxchar)
7853 goto Error;
7854 outdata[writer->pos] = x;
7855 writer->pos++;
7856 ++s;
7857 }
7858 break;
7859 }
7860 else if (outkind == PyUnicode_2BYTE_KIND) {
7861 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7862 while (s < e) {
7863 ch = *s;
7864 x = mapdata_ucs2[ch];
7865 if (x == 0xFFFE)
7866 goto Error;
7867 outdata[writer->pos] = x;
7868 writer->pos++;
7869 ++s;
7870 }
7871 break;
7872 }
7873 }
7874 ch = *s;
7875
7876 if (ch < maplen)
7877 x = PyUnicode_READ(mapkind, mapdata, ch);
7878 else
7879 x = 0xfffe; /* invalid value */
7880Error:
7881 if (x == 0xfffe)
7882 {
7883 /* undefined mapping */
7884 startinpos = s-starts;
7885 endinpos = startinpos+1;
7886 if (unicode_decode_call_errorhandler_writer(
7887 errors, &errorHandler,
7888 "charmap", "character maps to <undefined>",
7889 &starts, &e, &startinpos, &endinpos, &exc, &s,
7890 writer)) {
7891 goto onError;
7892 }
7893 continue;
7894 }
7895
7896 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7897 goto onError;
7898 ++s;
7899 }
7900 Py_XDECREF(errorHandler);
7901 Py_XDECREF(exc);
7902 return 0;
7903
7904onError:
7905 Py_XDECREF(errorHandler);
7906 Py_XDECREF(exc);
7907 return -1;
7908}
7909
7910static int
7911charmap_decode_mapping(const char *s,
7912 Py_ssize_t size,
7913 PyObject *mapping,
7914 const char *errors,
7915 _PyUnicodeWriter *writer)
7916{
7917 const char *starts = s;
7918 const char *e;
7919 Py_ssize_t startinpos, endinpos;
7920 PyObject *errorHandler = NULL, *exc = NULL;
7921 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007922 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007923
7924 e = s + size;
7925
7926 while (s < e) {
7927 ch = *s;
7928
7929 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7930 key = PyLong_FromLong((long)ch);
7931 if (key == NULL)
7932 goto onError;
7933
7934 item = PyObject_GetItem(mapping, key);
7935 Py_DECREF(key);
7936 if (item == NULL) {
7937 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7938 /* No mapping found means: mapping is undefined. */
7939 PyErr_Clear();
7940 goto Undefined;
7941 } else
7942 goto onError;
7943 }
7944
7945 /* Apply mapping */
7946 if (item == Py_None)
7947 goto Undefined;
7948 if (PyLong_Check(item)) {
7949 long value = PyLong_AS_LONG(item);
7950 if (value == 0xFFFE)
7951 goto Undefined;
7952 if (value < 0 || value > MAX_UNICODE) {
7953 PyErr_Format(PyExc_TypeError,
7954 "character mapping must be in range(0x%lx)",
7955 (unsigned long)MAX_UNICODE + 1);
7956 goto onError;
7957 }
7958
7959 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7960 goto onError;
7961 }
7962 else if (PyUnicode_Check(item)) {
7963 if (PyUnicode_READY(item) == -1)
7964 goto onError;
7965 if (PyUnicode_GET_LENGTH(item) == 1) {
7966 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7967 if (value == 0xFFFE)
7968 goto Undefined;
7969 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7970 goto onError;
7971 }
7972 else {
7973 writer->overallocate = 1;
7974 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7975 goto onError;
7976 }
7977 }
7978 else {
7979 /* wrong return value */
7980 PyErr_SetString(PyExc_TypeError,
7981 "character mapping must return integer, None or str");
7982 goto onError;
7983 }
7984 Py_CLEAR(item);
7985 ++s;
7986 continue;
7987
7988Undefined:
7989 /* undefined mapping */
7990 Py_CLEAR(item);
7991 startinpos = s-starts;
7992 endinpos = startinpos+1;
7993 if (unicode_decode_call_errorhandler_writer(
7994 errors, &errorHandler,
7995 "charmap", "character maps to <undefined>",
7996 &starts, &e, &startinpos, &endinpos, &exc, &s,
7997 writer)) {
7998 goto onError;
7999 }
8000 }
8001 Py_XDECREF(errorHandler);
8002 Py_XDECREF(exc);
8003 return 0;
8004
8005onError:
8006 Py_XDECREF(item);
8007 Py_XDECREF(errorHandler);
8008 Py_XDECREF(exc);
8009 return -1;
8010}
8011
Alexander Belopolsky40018472011-02-26 01:02:56 +00008012PyObject *
8013PyUnicode_DecodeCharmap(const char *s,
8014 Py_ssize_t size,
8015 PyObject *mapping,
8016 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008017{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008018 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008019
Guido van Rossumd57fd912000-03-10 22:53:23 +00008020 /* Default to Latin-1 */
8021 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008022 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008023
Guido van Rossumd57fd912000-03-10 22:53:23 +00008024 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008025 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008026 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008027 writer.min_length = size;
8028 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008029 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008030
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008031 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008032 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8033 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008034 }
8035 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008036 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8037 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008038 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008039 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008040
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008042 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008043 return NULL;
8044}
8045
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008046/* Charmap encoding: the lookup table */
8047
Alexander Belopolsky40018472011-02-26 01:02:56 +00008048struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 PyObject_HEAD
8050 unsigned char level1[32];
8051 int count2, count3;
8052 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008053};
8054
8055static PyObject*
8056encoding_map_size(PyObject *obj, PyObject* args)
8057{
8058 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008059 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008060 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008061}
8062
8063static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008064 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008065 PyDoc_STR("Return the size (in bytes) of this object") },
8066 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008067};
8068
8069static void
8070encoding_map_dealloc(PyObject* o)
8071{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008072 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008073}
8074
8075static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008076 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008077 "EncodingMap", /*tp_name*/
8078 sizeof(struct encoding_map), /*tp_basicsize*/
8079 0, /*tp_itemsize*/
8080 /* methods */
8081 encoding_map_dealloc, /*tp_dealloc*/
8082 0, /*tp_print*/
8083 0, /*tp_getattr*/
8084 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008085 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008086 0, /*tp_repr*/
8087 0, /*tp_as_number*/
8088 0, /*tp_as_sequence*/
8089 0, /*tp_as_mapping*/
8090 0, /*tp_hash*/
8091 0, /*tp_call*/
8092 0, /*tp_str*/
8093 0, /*tp_getattro*/
8094 0, /*tp_setattro*/
8095 0, /*tp_as_buffer*/
8096 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8097 0, /*tp_doc*/
8098 0, /*tp_traverse*/
8099 0, /*tp_clear*/
8100 0, /*tp_richcompare*/
8101 0, /*tp_weaklistoffset*/
8102 0, /*tp_iter*/
8103 0, /*tp_iternext*/
8104 encoding_map_methods, /*tp_methods*/
8105 0, /*tp_members*/
8106 0, /*tp_getset*/
8107 0, /*tp_base*/
8108 0, /*tp_dict*/
8109 0, /*tp_descr_get*/
8110 0, /*tp_descr_set*/
8111 0, /*tp_dictoffset*/
8112 0, /*tp_init*/
8113 0, /*tp_alloc*/
8114 0, /*tp_new*/
8115 0, /*tp_free*/
8116 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008117};
8118
8119PyObject*
8120PyUnicode_BuildEncodingMap(PyObject* string)
8121{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008122 PyObject *result;
8123 struct encoding_map *mresult;
8124 int i;
8125 int need_dict = 0;
8126 unsigned char level1[32];
8127 unsigned char level2[512];
8128 unsigned char *mlevel1, *mlevel2, *mlevel3;
8129 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008130 int kind;
8131 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008132 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008133 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008135 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 PyErr_BadArgument();
8137 return NULL;
8138 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008139 kind = PyUnicode_KIND(string);
8140 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008141 length = PyUnicode_GET_LENGTH(string);
8142 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008143 memset(level1, 0xFF, sizeof level1);
8144 memset(level2, 0xFF, sizeof level2);
8145
8146 /* If there isn't a one-to-one mapping of NULL to \0,
8147 or if there are non-BMP characters, we need to use
8148 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008149 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008150 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008151 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008152 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008153 ch = PyUnicode_READ(kind, data, i);
8154 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008155 need_dict = 1;
8156 break;
8157 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008158 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008159 /* unmapped character */
8160 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008161 l1 = ch >> 11;
8162 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008163 if (level1[l1] == 0xFF)
8164 level1[l1] = count2++;
8165 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008166 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008167 }
8168
8169 if (count2 >= 0xFF || count3 >= 0xFF)
8170 need_dict = 1;
8171
8172 if (need_dict) {
8173 PyObject *result = PyDict_New();
8174 PyObject *key, *value;
8175 if (!result)
8176 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008177 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008178 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008179 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008180 if (!key || !value)
8181 goto failed1;
8182 if (PyDict_SetItem(result, key, value) == -1)
8183 goto failed1;
8184 Py_DECREF(key);
8185 Py_DECREF(value);
8186 }
8187 return result;
8188 failed1:
8189 Py_XDECREF(key);
8190 Py_XDECREF(value);
8191 Py_DECREF(result);
8192 return NULL;
8193 }
8194
8195 /* Create a three-level trie */
8196 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8197 16*count2 + 128*count3 - 1);
8198 if (!result)
8199 return PyErr_NoMemory();
8200 PyObject_Init(result, &EncodingMapType);
8201 mresult = (struct encoding_map*)result;
8202 mresult->count2 = count2;
8203 mresult->count3 = count3;
8204 mlevel1 = mresult->level1;
8205 mlevel2 = mresult->level23;
8206 mlevel3 = mresult->level23 + 16*count2;
8207 memcpy(mlevel1, level1, 32);
8208 memset(mlevel2, 0xFF, 16*count2);
8209 memset(mlevel3, 0, 128*count3);
8210 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008211 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008212 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008213 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8214 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008215 /* unmapped character */
8216 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008217 o1 = ch>>11;
8218 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008219 i2 = 16*mlevel1[o1] + o2;
8220 if (mlevel2[i2] == 0xFF)
8221 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008222 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008223 i3 = 128*mlevel2[i2] + o3;
8224 mlevel3[i3] = i;
8225 }
8226 return result;
8227}
8228
8229static int
Victor Stinner22168992011-11-20 17:09:18 +01008230encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008231{
8232 struct encoding_map *map = (struct encoding_map*)mapping;
8233 int l1 = c>>11;
8234 int l2 = (c>>7) & 0xF;
8235 int l3 = c & 0x7F;
8236 int i;
8237
Victor Stinner22168992011-11-20 17:09:18 +01008238 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008240 if (c == 0)
8241 return 0;
8242 /* level 1*/
8243 i = map->level1[l1];
8244 if (i == 0xFF) {
8245 return -1;
8246 }
8247 /* level 2*/
8248 i = map->level23[16*i+l2];
8249 if (i == 0xFF) {
8250 return -1;
8251 }
8252 /* level 3 */
8253 i = map->level23[16*map->count2 + 128*i + l3];
8254 if (i == 0) {
8255 return -1;
8256 }
8257 return i;
8258}
8259
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008260/* Lookup the character ch in the mapping. If the character
8261 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008262 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008263static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008264charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008265{
Christian Heimes217cfd12007-12-02 14:31:20 +00008266 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008267 PyObject *x;
8268
8269 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008271 x = PyObject_GetItem(mapping, w);
8272 Py_DECREF(w);
8273 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8275 /* No mapping found means: mapping is undefined. */
8276 PyErr_Clear();
8277 x = Py_None;
8278 Py_INCREF(x);
8279 return x;
8280 } else
8281 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008282 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008283 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008284 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008285 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008286 long value = PyLong_AS_LONG(x);
8287 if (value < 0 || value > 255) {
8288 PyErr_SetString(PyExc_TypeError,
8289 "character mapping must be in range(256)");
8290 Py_DECREF(x);
8291 return NULL;
8292 }
8293 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008294 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008295 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008296 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008297 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 /* wrong return value */
8299 PyErr_Format(PyExc_TypeError,
8300 "character mapping must return integer, bytes or None, not %.400s",
8301 x->ob_type->tp_name);
8302 Py_DECREF(x);
8303 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008304 }
8305}
8306
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008307static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008308charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008309{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008310 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8311 /* exponentially overallocate to minimize reallocations */
8312 if (requiredsize < 2*outsize)
8313 requiredsize = 2*outsize;
8314 if (_PyBytes_Resize(outobj, requiredsize))
8315 return -1;
8316 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008317}
8318
Benjamin Peterson14339b62009-01-31 16:36:08 +00008319typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008321} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008323 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324 space is available. Return a new reference to the object that
8325 was put in the output buffer, or Py_None, if the mapping was undefined
8326 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008327 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008328static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008329charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008330 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008332 PyObject *rep;
8333 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008334 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335
Christian Heimes90aa7642007-12-19 02:45:37 +00008336 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008337 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008338 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008339 if (res == -1)
8340 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008341 if (outsize<requiredsize)
8342 if (charmapencode_resize(outobj, outpos, requiredsize))
8343 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008344 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 outstart[(*outpos)++] = (char)res;
8346 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008347 }
8348
8349 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008351 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008352 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 Py_DECREF(rep);
8354 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008355 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 if (PyLong_Check(rep)) {
8357 Py_ssize_t requiredsize = *outpos+1;
8358 if (outsize<requiredsize)
8359 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8360 Py_DECREF(rep);
8361 return enc_EXCEPTION;
8362 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008363 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008365 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 else {
8367 const char *repchars = PyBytes_AS_STRING(rep);
8368 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8369 Py_ssize_t requiredsize = *outpos+repsize;
8370 if (outsize<requiredsize)
8371 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8372 Py_DECREF(rep);
8373 return enc_EXCEPTION;
8374 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008375 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 memcpy(outstart + *outpos, repchars, repsize);
8377 *outpos += repsize;
8378 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008379 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008380 Py_DECREF(rep);
8381 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382}
8383
8384/* handle an error in PyUnicode_EncodeCharmap
8385 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008386static int
8387charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008388 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008390 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008391 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392{
8393 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008394 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008395 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008396 enum PyUnicode_Kind kind;
8397 void *data;
8398 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008400 Py_ssize_t collstartpos = *inpos;
8401 Py_ssize_t collendpos = *inpos+1;
8402 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 char *encoding = "charmap";
8404 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008405 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008406 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008407 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408
Benjamin Petersonbac79492012-01-14 13:34:47 -05008409 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008410 return -1;
8411 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412 /* find all unencodable characters */
8413 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008414 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008415 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008416 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008417 val = encoding_map_lookup(ch, mapping);
8418 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008419 break;
8420 ++collendpos;
8421 continue;
8422 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008423
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008424 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8425 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 if (rep==NULL)
8427 return -1;
8428 else if (rep!=Py_None) {
8429 Py_DECREF(rep);
8430 break;
8431 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008432 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008433 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008434 }
8435 /* cache callback name lookup
8436 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008437 if (*error_handler == _Py_ERROR_UNKNOWN)
8438 *error_handler = get_error_handler(errors);
8439
8440 switch (*error_handler) {
8441 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008442 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008443 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008444
8445 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008446 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 x = charmapencode_output('?', mapping, res, respos);
8448 if (x==enc_EXCEPTION) {
8449 return -1;
8450 }
8451 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008452 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 return -1;
8454 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008455 }
8456 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008457 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008458 *inpos = collendpos;
8459 break;
Victor Stinner50149202015-09-22 00:26:54 +02008460
8461 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008462 /* generate replacement (temporarily (mis)uses p) */
8463 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 char buffer[2+29+1+1];
8465 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008466 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008467 for (cp = buffer; *cp; ++cp) {
8468 x = charmapencode_output(*cp, mapping, res, respos);
8469 if (x==enc_EXCEPTION)
8470 return -1;
8471 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008472 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 return -1;
8474 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008475 }
8476 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008477 *inpos = collendpos;
8478 break;
Victor Stinner50149202015-09-22 00:26:54 +02008479
Benjamin Peterson14339b62009-01-31 16:36:08 +00008480 default:
Victor Stinner50149202015-09-22 00:26:54 +02008481 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008482 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008484 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008486 if (PyBytes_Check(repunicode)) {
8487 /* Directly copy bytes result to output. */
8488 Py_ssize_t outsize = PyBytes_Size(*res);
8489 Py_ssize_t requiredsize;
8490 repsize = PyBytes_Size(repunicode);
8491 requiredsize = *respos + repsize;
8492 if (requiredsize > outsize)
8493 /* Make room for all additional bytes. */
8494 if (charmapencode_resize(res, respos, requiredsize)) {
8495 Py_DECREF(repunicode);
8496 return -1;
8497 }
8498 memcpy(PyBytes_AsString(*res) + *respos,
8499 PyBytes_AsString(repunicode), repsize);
8500 *respos += repsize;
8501 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008502 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008503 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008504 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008505 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008506 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008507 Py_DECREF(repunicode);
8508 return -1;
8509 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008510 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008511 data = PyUnicode_DATA(repunicode);
8512 kind = PyUnicode_KIND(repunicode);
8513 for (index = 0; index < repsize; index++) {
8514 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8515 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008517 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 return -1;
8519 }
8520 else if (x==enc_FAILED) {
8521 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008522 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 return -1;
8524 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008525 }
8526 *inpos = newpos;
8527 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008528 }
8529 return 0;
8530}
8531
Alexander Belopolsky40018472011-02-26 01:02:56 +00008532PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008533_PyUnicode_EncodeCharmap(PyObject *unicode,
8534 PyObject *mapping,
8535 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008536{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 /* output object */
8538 PyObject *res = NULL;
8539 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008540 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008541 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008542 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008543 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008544 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008545 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008546 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008547 void *data;
8548 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008549
Benjamin Petersonbac79492012-01-14 13:34:47 -05008550 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008551 return NULL;
8552 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008553 data = PyUnicode_DATA(unicode);
8554 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008555
Guido van Rossumd57fd912000-03-10 22:53:23 +00008556 /* Default to Latin-1 */
8557 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008558 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008559
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008560 /* allocate enough for a simple encoding without
8561 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008562 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008563 if (res == NULL)
8564 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008565 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008566 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008567
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008569 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008571 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 if (x==enc_EXCEPTION) /* error */
8573 goto onError;
8574 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008575 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008576 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008577 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 &res, &respos)) {
8579 goto onError;
8580 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008581 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 else
8583 /* done with this character => adjust input position */
8584 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008585 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008586
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008588 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008589 if (_PyBytes_Resize(&res, respos) < 0)
8590 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008591
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008592 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008593 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008594 return res;
8595
Benjamin Peterson29060642009-01-31 22:14:21 +00008596 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008597 Py_XDECREF(res);
8598 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008599 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600 return NULL;
8601}
8602
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008603/* Deprecated */
8604PyObject *
8605PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8606 Py_ssize_t size,
8607 PyObject *mapping,
8608 const char *errors)
8609{
8610 PyObject *result;
8611 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8612 if (unicode == NULL)
8613 return NULL;
8614 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8615 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008616 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008617}
8618
Alexander Belopolsky40018472011-02-26 01:02:56 +00008619PyObject *
8620PyUnicode_AsCharmapString(PyObject *unicode,
8621 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008622{
8623 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008624 PyErr_BadArgument();
8625 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008626 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008627 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008628}
8629
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008630/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008631static void
8632make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008634 Py_ssize_t startpos, Py_ssize_t endpos,
8635 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008636{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008637 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638 *exceptionObject = _PyUnicodeTranslateError_Create(
8639 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008640 }
8641 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8643 goto onError;
8644 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8645 goto onError;
8646 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8647 goto onError;
8648 return;
8649 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008650 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008651 }
8652}
8653
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008654/* error handling callback helper:
8655 build arguments, call the callback and check the arguments,
8656 put the result into newpos and return the replacement string, which
8657 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008658static PyObject *
8659unicode_translate_call_errorhandler(const char *errors,
8660 PyObject **errorHandler,
8661 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008662 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008663 Py_ssize_t startpos, Py_ssize_t endpos,
8664 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008666 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008667
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008668 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669 PyObject *restuple;
8670 PyObject *resunicode;
8671
8672 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008673 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008674 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008675 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008676 }
8677
8678 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008680 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008681 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008682
8683 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008685 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008688 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008689 Py_DECREF(restuple);
8690 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691 }
8692 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008693 &resunicode, &i_newpos)) {
8694 Py_DECREF(restuple);
8695 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008697 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008699 else
8700 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008701 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008702 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008703 Py_DECREF(restuple);
8704 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008705 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008706 Py_INCREF(resunicode);
8707 Py_DECREF(restuple);
8708 return resunicode;
8709}
8710
8711/* Lookup the character ch in the mapping and put the result in result,
8712 which must be decrefed by the caller.
8713 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008714static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008715charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008716{
Christian Heimes217cfd12007-12-02 14:31:20 +00008717 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008718 PyObject *x;
8719
8720 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008722 x = PyObject_GetItem(mapping, w);
8723 Py_DECREF(w);
8724 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008725 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8726 /* No mapping found means: use 1:1 mapping. */
8727 PyErr_Clear();
8728 *result = NULL;
8729 return 0;
8730 } else
8731 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008732 }
8733 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008734 *result = x;
8735 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008736 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008737 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008738 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008739 if (value < 0 || value > MAX_UNICODE) {
8740 PyErr_Format(PyExc_ValueError,
8741 "character mapping must be in range(0x%x)",
8742 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008743 Py_DECREF(x);
8744 return -1;
8745 }
8746 *result = x;
8747 return 0;
8748 }
8749 else if (PyUnicode_Check(x)) {
8750 *result = x;
8751 return 0;
8752 }
8753 else {
8754 /* wrong return value */
8755 PyErr_SetString(PyExc_TypeError,
8756 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008757 Py_DECREF(x);
8758 return -1;
8759 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008760}
Victor Stinner1194ea02014-04-04 19:37:40 +02008761
8762/* lookup the character, write the result into the writer.
8763 Return 1 if the result was written into the writer, return 0 if the mapping
8764 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008765static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008766charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8767 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008768{
Victor Stinner1194ea02014-04-04 19:37:40 +02008769 PyObject *item;
8770
8771 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008772 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008773
8774 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008775 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008776 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008777 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008778 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008779 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008780 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008781
8782 if (item == Py_None) {
8783 Py_DECREF(item);
8784 return 0;
8785 }
8786
8787 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008788 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8789 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8790 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008791 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8792 Py_DECREF(item);
8793 return -1;
8794 }
8795 Py_DECREF(item);
8796 return 1;
8797 }
8798
8799 if (!PyUnicode_Check(item)) {
8800 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008801 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008802 }
8803
8804 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8805 Py_DECREF(item);
8806 return -1;
8807 }
8808
8809 Py_DECREF(item);
8810 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008811}
8812
Victor Stinner89a76ab2014-04-05 11:44:04 +02008813static int
8814unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8815 Py_UCS1 *translate)
8816{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008817 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008818 int ret = 0;
8819
Victor Stinner89a76ab2014-04-05 11:44:04 +02008820 if (charmaptranslate_lookup(ch, mapping, &item)) {
8821 return -1;
8822 }
8823
8824 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008825 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008826 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008827 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008828 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008829 /* not found => default to 1:1 mapping */
8830 translate[ch] = ch;
8831 return 1;
8832 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008833 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008834 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008835 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8836 used it */
8837 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008838 /* invalid character or character outside ASCII:
8839 skip the fast translate */
8840 goto exit;
8841 }
8842 translate[ch] = (Py_UCS1)replace;
8843 }
8844 else if (PyUnicode_Check(item)) {
8845 Py_UCS4 replace;
8846
8847 if (PyUnicode_READY(item) == -1) {
8848 Py_DECREF(item);
8849 return -1;
8850 }
8851 if (PyUnicode_GET_LENGTH(item) != 1)
8852 goto exit;
8853
8854 replace = PyUnicode_READ_CHAR(item, 0);
8855 if (replace > 127)
8856 goto exit;
8857 translate[ch] = (Py_UCS1)replace;
8858 }
8859 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008860 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008861 goto exit;
8862 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008863 ret = 1;
8864
Benjamin Peterson1365de72014-04-07 20:15:41 -04008865 exit:
8866 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008867 return ret;
8868}
8869
8870/* Fast path for ascii => ascii translation. Return 1 if the whole string
8871 was translated into writer, return 0 if the input string was partially
8872 translated into writer, raise an exception and return -1 on error. */
8873static int
8874unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008875 _PyUnicodeWriter *writer, int ignore,
8876 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008877{
Victor Stinner872b2912014-04-05 14:27:07 +02008878 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008879 Py_ssize_t len;
8880 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008881 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008882
Victor Stinner89a76ab2014-04-05 11:44:04 +02008883 len = PyUnicode_GET_LENGTH(input);
8884
Victor Stinner872b2912014-04-05 14:27:07 +02008885 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008886
8887 in = PyUnicode_1BYTE_DATA(input);
8888 end = in + len;
8889
8890 assert(PyUnicode_IS_ASCII(writer->buffer));
8891 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8892 out = PyUnicode_1BYTE_DATA(writer->buffer);
8893
Victor Stinner872b2912014-04-05 14:27:07 +02008894 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008895 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008896 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008897 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008898 int translate = unicode_fast_translate_lookup(mapping, ch,
8899 ascii_table);
8900 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008901 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008902 if (translate == 0)
8903 goto exit;
8904 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008905 }
Victor Stinner872b2912014-04-05 14:27:07 +02008906 if (ch2 == 0xfe) {
8907 if (ignore)
8908 continue;
8909 goto exit;
8910 }
8911 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008912 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008913 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008914 }
Victor Stinner872b2912014-04-05 14:27:07 +02008915 res = 1;
8916
8917exit:
8918 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008919 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008920 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008921}
8922
Victor Stinner3222da22015-10-01 22:07:32 +02008923static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008924_PyUnicode_TranslateCharmap(PyObject *input,
8925 PyObject *mapping,
8926 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008927{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008928 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008929 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008930 Py_ssize_t size, i;
8931 int kind;
8932 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008933 _PyUnicodeWriter writer;
8934 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008935 char *reason = "character maps to <undefined>";
8936 PyObject *errorHandler = NULL;
8937 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008938 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008939 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008940
Guido van Rossumd57fd912000-03-10 22:53:23 +00008941 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008942 PyErr_BadArgument();
8943 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008944 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008946 if (PyUnicode_READY(input) == -1)
8947 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008948 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008949 kind = PyUnicode_KIND(input);
8950 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008951
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008952 if (size == 0)
8953 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008954
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008955 /* allocate enough for a simple 1:1 translation without
8956 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008957 _PyUnicodeWriter_Init(&writer);
8958 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008959 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008960
Victor Stinner872b2912014-04-05 14:27:07 +02008961 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8962
Victor Stinner33798672016-03-01 21:59:58 +01008963 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008964 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008965 if (PyUnicode_IS_ASCII(input)) {
8966 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8967 if (res < 0) {
8968 _PyUnicodeWriter_Dealloc(&writer);
8969 return NULL;
8970 }
8971 if (res == 1)
8972 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008973 }
Victor Stinner33798672016-03-01 21:59:58 +01008974 else {
8975 i = 0;
8976 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008978 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008979 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008980 int translate;
8981 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8982 Py_ssize_t newpos;
8983 /* startpos for collecting untranslatable chars */
8984 Py_ssize_t collstart;
8985 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008986 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008987
Victor Stinner1194ea02014-04-04 19:37:40 +02008988 ch = PyUnicode_READ(kind, data, i);
8989 translate = charmaptranslate_output(ch, mapping, &writer);
8990 if (translate < 0)
8991 goto onError;
8992
8993 if (translate != 0) {
8994 /* it worked => adjust input pointer */
8995 ++i;
8996 continue;
8997 }
8998
8999 /* untranslatable character */
9000 collstart = i;
9001 collend = i+1;
9002
9003 /* find all untranslatable characters */
9004 while (collend < size) {
9005 PyObject *x;
9006 ch = PyUnicode_READ(kind, data, collend);
9007 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009008 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009009 Py_XDECREF(x);
9010 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009011 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009012 ++collend;
9013 }
9014
9015 if (ignore) {
9016 i = collend;
9017 }
9018 else {
9019 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9020 reason, input, &exc,
9021 collstart, collend, &newpos);
9022 if (repunicode == NULL)
9023 goto onError;
9024 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009025 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009026 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009027 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009028 Py_DECREF(repunicode);
9029 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009030 }
9031 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009032 Py_XDECREF(exc);
9033 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009034 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009035
Benjamin Peterson29060642009-01-31 22:14:21 +00009036 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009037 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009038 Py_XDECREF(exc);
9039 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009040 return NULL;
9041}
9042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009043/* Deprecated. Use PyUnicode_Translate instead. */
9044PyObject *
9045PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9046 Py_ssize_t size,
9047 PyObject *mapping,
9048 const char *errors)
9049{
Christian Heimes5f520f42012-09-11 14:03:25 +02009050 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009051 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9052 if (!unicode)
9053 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009054 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9055 Py_DECREF(unicode);
9056 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009057}
9058
Alexander Belopolsky40018472011-02-26 01:02:56 +00009059PyObject *
9060PyUnicode_Translate(PyObject *str,
9061 PyObject *mapping,
9062 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009063{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009064 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009065 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009066 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009067}
Tim Petersced69f82003-09-16 20:30:58 +00009068
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009069static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009070fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009071{
9072 /* No need to call PyUnicode_READY(self) because this function is only
9073 called as a callback from fixup() which does it already. */
9074 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9075 const int kind = PyUnicode_KIND(self);
9076 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009077 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009078 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009079 Py_ssize_t i;
9080
9081 for (i = 0; i < len; ++i) {
9082 ch = PyUnicode_READ(kind, data, i);
9083 fixed = 0;
9084 if (ch > 127) {
9085 if (Py_UNICODE_ISSPACE(ch))
9086 fixed = ' ';
9087 else {
9088 const int decimal = Py_UNICODE_TODECIMAL(ch);
9089 if (decimal >= 0)
9090 fixed = '0' + decimal;
9091 }
9092 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009093 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009094 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009095 PyUnicode_WRITE(kind, data, i, fixed);
9096 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009097 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009098 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009099 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009100 }
9101
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009102 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009103}
9104
9105PyObject *
9106_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9107{
9108 if (!PyUnicode_Check(unicode)) {
9109 PyErr_BadInternalCall();
9110 return NULL;
9111 }
9112 if (PyUnicode_READY(unicode) == -1)
9113 return NULL;
9114 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9115 /* If the string is already ASCII, just return the same string */
9116 Py_INCREF(unicode);
9117 return unicode;
9118 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009119 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120}
9121
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009122PyObject *
9123PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9124 Py_ssize_t length)
9125{
Victor Stinnerf0124502011-11-21 23:12:56 +01009126 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009127 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009128 Py_UCS4 maxchar;
9129 enum PyUnicode_Kind kind;
9130 void *data;
9131
Victor Stinner99d7ad02012-02-22 13:37:39 +01009132 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009133 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009134 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009135 if (ch > 127) {
9136 int decimal = Py_UNICODE_TODECIMAL(ch);
9137 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009138 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009139 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009140 }
9141 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009142
9143 /* Copy to a new string */
9144 decimal = PyUnicode_New(length, maxchar);
9145 if (decimal == NULL)
9146 return decimal;
9147 kind = PyUnicode_KIND(decimal);
9148 data = PyUnicode_DATA(decimal);
9149 /* Iterate over code points */
9150 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009151 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009152 if (ch > 127) {
9153 int decimal = Py_UNICODE_TODECIMAL(ch);
9154 if (decimal >= 0)
9155 ch = '0' + decimal;
9156 }
9157 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009158 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009159 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009160}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009161/* --- Decimal Encoder ---------------------------------------------------- */
9162
Alexander Belopolsky40018472011-02-26 01:02:56 +00009163int
9164PyUnicode_EncodeDecimal(Py_UNICODE *s,
9165 Py_ssize_t length,
9166 char *output,
9167 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009168{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009169 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009170 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009171 enum PyUnicode_Kind kind;
9172 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009173
9174 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009175 PyErr_BadArgument();
9176 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009177 }
9178
Victor Stinner42bf7752011-11-21 22:52:58 +01009179 unicode = PyUnicode_FromUnicode(s, length);
9180 if (unicode == NULL)
9181 return -1;
9182
Benjamin Petersonbac79492012-01-14 13:34:47 -05009183 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009184 Py_DECREF(unicode);
9185 return -1;
9186 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009187 kind = PyUnicode_KIND(unicode);
9188 data = PyUnicode_DATA(unicode);
9189
Victor Stinnerb84d7232011-11-22 01:50:07 +01009190 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009191 PyObject *exc;
9192 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009193 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009194 Py_ssize_t startpos;
9195
9196 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009197
Benjamin Peterson29060642009-01-31 22:14:21 +00009198 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009199 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009200 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009201 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009202 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009203 decimal = Py_UNICODE_TODECIMAL(ch);
9204 if (decimal >= 0) {
9205 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009206 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009207 continue;
9208 }
9209 if (0 < ch && ch < 256) {
9210 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009211 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009212 continue;
9213 }
Victor Stinner6345be92011-11-25 20:09:01 +01009214
Victor Stinner42bf7752011-11-21 22:52:58 +01009215 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009216 exc = NULL;
9217 raise_encode_exception(&exc, "decimal", unicode,
9218 startpos, startpos+1,
9219 "invalid decimal Unicode string");
9220 Py_XDECREF(exc);
9221 Py_DECREF(unicode);
9222 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009223 }
9224 /* 0-terminate the output string */
9225 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009226 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009227 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009228}
9229
Guido van Rossumd57fd912000-03-10 22:53:23 +00009230/* --- Helpers ------------------------------------------------------------ */
9231
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009232/* helper macro to fixup start/end slice values */
9233#define ADJUST_INDICES(start, end, len) \
9234 if (end > len) \
9235 end = len; \
9236 else if (end < 0) { \
9237 end += len; \
9238 if (end < 0) \
9239 end = 0; \
9240 } \
9241 if (start < 0) { \
9242 start += len; \
9243 if (start < 0) \
9244 start = 0; \
9245 }
9246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009247static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009248any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009249 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009250 Py_ssize_t end,
9251 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009252{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009253 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 void *buf1, *buf2;
9255 Py_ssize_t len1, len2, result;
9256
9257 kind1 = PyUnicode_KIND(s1);
9258 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009259 if (kind1 < kind2)
9260 return -1;
9261
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009262 len1 = PyUnicode_GET_LENGTH(s1);
9263 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009264 ADJUST_INDICES(start, end, len1);
9265 if (end - start < len2)
9266 return -1;
9267
9268 buf1 = PyUnicode_DATA(s1);
9269 buf2 = PyUnicode_DATA(s2);
9270 if (len2 == 1) {
9271 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9272 result = findchar((const char *)buf1 + kind1*start,
9273 kind1, end - start, ch, direction);
9274 if (result == -1)
9275 return -1;
9276 else
9277 return start + result;
9278 }
9279
9280 if (kind2 != kind1) {
9281 buf2 = _PyUnicode_AsKind(s2, kind1);
9282 if (!buf2)
9283 return -2;
9284 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009285
Victor Stinner794d5672011-10-10 03:21:36 +02009286 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009287 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009288 case PyUnicode_1BYTE_KIND:
9289 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9290 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9291 else
9292 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9293 break;
9294 case PyUnicode_2BYTE_KIND:
9295 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9296 break;
9297 case PyUnicode_4BYTE_KIND:
9298 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9299 break;
9300 default:
9301 assert(0); result = -2;
9302 }
9303 }
9304 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009305 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009306 case PyUnicode_1BYTE_KIND:
9307 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9308 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9309 else
9310 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9311 break;
9312 case PyUnicode_2BYTE_KIND:
9313 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9314 break;
9315 case PyUnicode_4BYTE_KIND:
9316 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9317 break;
9318 default:
9319 assert(0); result = -2;
9320 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009321 }
9322
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009323 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009324 PyMem_Free(buf2);
9325
9326 return result;
9327}
9328
9329Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009330_PyUnicode_InsertThousandsGrouping(
9331 PyObject *unicode, Py_ssize_t index,
9332 Py_ssize_t n_buffer,
9333 void *digits, Py_ssize_t n_digits,
9334 Py_ssize_t min_width,
9335 const char *grouping, PyObject *thousands_sep,
9336 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009337{
Victor Stinner41a863c2012-02-24 00:37:51 +01009338 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009339 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009340 Py_ssize_t thousands_sep_len;
9341 Py_ssize_t len;
9342
9343 if (unicode != NULL) {
9344 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009345 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009346 }
9347 else {
9348 kind = PyUnicode_1BYTE_KIND;
9349 data = NULL;
9350 }
9351 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9352 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9353 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9354 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009355 if (thousands_sep_kind < kind) {
9356 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9357 if (!thousands_sep_data)
9358 return -1;
9359 }
9360 else {
9361 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9362 if (!data)
9363 return -1;
9364 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009365 }
9366
Benjamin Petersonead6b532011-12-20 17:23:42 -06009367 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009369 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009370 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009371 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009372 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009373 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009374 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009375 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009376 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009377 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009378 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009379 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009380 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009381 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009382 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009383 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009384 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009385 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009387 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009388 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009389 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009390 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009391 break;
9392 default:
9393 assert(0);
9394 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009396 if (unicode != NULL && thousands_sep_kind != kind) {
9397 if (thousands_sep_kind < kind)
9398 PyMem_Free(thousands_sep_data);
9399 else
9400 PyMem_Free(data);
9401 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009402 if (unicode == NULL) {
9403 *maxchar = 127;
9404 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009405 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009406 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009407 }
9408 }
9409 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009410}
9411
9412
Alexander Belopolsky40018472011-02-26 01:02:56 +00009413Py_ssize_t
9414PyUnicode_Count(PyObject *str,
9415 PyObject *substr,
9416 Py_ssize_t start,
9417 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009418{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009419 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009420 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421 void *buf1 = NULL, *buf2 = NULL;
9422 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009423
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009424 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009425 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009426
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009427 kind1 = PyUnicode_KIND(str);
9428 kind2 = PyUnicode_KIND(substr);
9429 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009430 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009431
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009432 len1 = PyUnicode_GET_LENGTH(str);
9433 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009435 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009436 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009437
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009438 buf1 = PyUnicode_DATA(str);
9439 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009440 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009441 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009442 if (!buf2)
9443 goto onError;
9444 }
9445
9446 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009448 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009449 result = asciilib_count(
9450 ((Py_UCS1*)buf1) + start, end - start,
9451 buf2, len2, PY_SSIZE_T_MAX
9452 );
9453 else
9454 result = ucs1lib_count(
9455 ((Py_UCS1*)buf1) + start, end - start,
9456 buf2, len2, PY_SSIZE_T_MAX
9457 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458 break;
9459 case PyUnicode_2BYTE_KIND:
9460 result = ucs2lib_count(
9461 ((Py_UCS2*)buf1) + start, end - start,
9462 buf2, len2, PY_SSIZE_T_MAX
9463 );
9464 break;
9465 case PyUnicode_4BYTE_KIND:
9466 result = ucs4lib_count(
9467 ((Py_UCS4*)buf1) + start, end - start,
9468 buf2, len2, PY_SSIZE_T_MAX
9469 );
9470 break;
9471 default:
9472 assert(0); result = 0;
9473 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009474
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009475 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 PyMem_Free(buf2);
9477
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009480 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481 PyMem_Free(buf2);
9482 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483}
9484
Alexander Belopolsky40018472011-02-26 01:02:56 +00009485Py_ssize_t
9486PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009487 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009488 Py_ssize_t start,
9489 Py_ssize_t end,
9490 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009492 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009493 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009494
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009495 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009496}
9497
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498Py_ssize_t
9499PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9500 Py_ssize_t start, Py_ssize_t end,
9501 int direction)
9502{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009504 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009505 if (PyUnicode_READY(str) == -1)
9506 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009507 if (start < 0 || end < 0) {
9508 PyErr_SetString(PyExc_IndexError, "string index out of range");
9509 return -2;
9510 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009511 if (end > PyUnicode_GET_LENGTH(str))
9512 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009513 if (start >= end)
9514 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009515 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009516 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9517 kind, end-start, ch, direction);
9518 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009520 else
9521 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522}
9523
Alexander Belopolsky40018472011-02-26 01:02:56 +00009524static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009525tailmatch(PyObject *self,
9526 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009527 Py_ssize_t start,
9528 Py_ssize_t end,
9529 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 int kind_self;
9532 int kind_sub;
9533 void *data_self;
9534 void *data_sub;
9535 Py_ssize_t offset;
9536 Py_ssize_t i;
9537 Py_ssize_t end_sub;
9538
9539 if (PyUnicode_READY(self) == -1 ||
9540 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009541 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009543 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9544 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009545 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009546 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009547
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009548 if (PyUnicode_GET_LENGTH(substring) == 0)
9549 return 1;
9550
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009551 kind_self = PyUnicode_KIND(self);
9552 data_self = PyUnicode_DATA(self);
9553 kind_sub = PyUnicode_KIND(substring);
9554 data_sub = PyUnicode_DATA(substring);
9555 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9556
9557 if (direction > 0)
9558 offset = end;
9559 else
9560 offset = start;
9561
9562 if (PyUnicode_READ(kind_self, data_self, offset) ==
9563 PyUnicode_READ(kind_sub, data_sub, 0) &&
9564 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9565 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9566 /* If both are of the same kind, memcmp is sufficient */
9567 if (kind_self == kind_sub) {
9568 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009569 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009570 data_sub,
9571 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009572 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009573 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009574 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009575 else {
9576 /* We do not need to compare 0 and len(substring)-1 because
9577 the if statement above ensured already that they are equal
9578 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009579 for (i = 1; i < end_sub; ++i) {
9580 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9581 PyUnicode_READ(kind_sub, data_sub, i))
9582 return 0;
9583 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009584 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009586 }
9587
9588 return 0;
9589}
9590
Alexander Belopolsky40018472011-02-26 01:02:56 +00009591Py_ssize_t
9592PyUnicode_Tailmatch(PyObject *str,
9593 PyObject *substr,
9594 Py_ssize_t start,
9595 Py_ssize_t end,
9596 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009597{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009598 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009599 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009600
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009601 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009602}
9603
Guido van Rossumd57fd912000-03-10 22:53:23 +00009604/* Apply fixfct filter to the Unicode object self and return a
9605 reference to the modified object */
9606
Alexander Belopolsky40018472011-02-26 01:02:56 +00009607static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009608fixup(PyObject *self,
9609 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009610{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009611 PyObject *u;
9612 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009613 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009614
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009615 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009616 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009617 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009618 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009620 /* fix functions return the new maximum character in a string,
9621 if the kind of the resulting unicode object does not change,
9622 everything is fine. Otherwise we need to change the string kind
9623 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009624 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009625
9626 if (maxchar_new == 0) {
9627 /* no changes */;
9628 if (PyUnicode_CheckExact(self)) {
9629 Py_DECREF(u);
9630 Py_INCREF(self);
9631 return self;
9632 }
9633 else
9634 return u;
9635 }
9636
Victor Stinnere6abb482012-05-02 01:15:40 +02009637 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638
Victor Stinnereaab6042011-12-11 22:22:39 +01009639 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009640 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009641
9642 /* In case the maximum character changed, we need to
9643 convert the string to the new category. */
9644 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9645 if (v == NULL) {
9646 Py_DECREF(u);
9647 return NULL;
9648 }
9649 if (maxchar_new > maxchar_old) {
9650 /* If the maxchar increased so that the kind changed, not all
9651 characters are representable anymore and we need to fix the
9652 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009653 _PyUnicode_FastCopyCharacters(v, 0,
9654 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009655 maxchar_old = fixfct(v);
9656 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009657 }
9658 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009659 _PyUnicode_FastCopyCharacters(v, 0,
9660 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009661 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009662 Py_DECREF(u);
9663 assert(_PyUnicode_CheckConsistency(v, 1));
9664 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009665}
9666
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009667static PyObject *
9668ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9671 char *resdata, *data = PyUnicode_DATA(self);
9672 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009673
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009674 res = PyUnicode_New(len, 127);
9675 if (res == NULL)
9676 return NULL;
9677 resdata = PyUnicode_DATA(res);
9678 if (lower)
9679 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009680 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009681 _Py_bytes_upper(resdata, data, len);
9682 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009683}
9684
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009685static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009686handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009687{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009688 Py_ssize_t j;
9689 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009690 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009691 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009692
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009693 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9694
9695 where ! is a negation and \p{xxx} is a character with property xxx.
9696 */
9697 for (j = i - 1; j >= 0; j--) {
9698 c = PyUnicode_READ(kind, data, j);
9699 if (!_PyUnicode_IsCaseIgnorable(c))
9700 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009701 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009702 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9703 if (final_sigma) {
9704 for (j = i + 1; j < length; j++) {
9705 c = PyUnicode_READ(kind, data, j);
9706 if (!_PyUnicode_IsCaseIgnorable(c))
9707 break;
9708 }
9709 final_sigma = j == length || !_PyUnicode_IsCased(c);
9710 }
9711 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009712}
9713
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009714static int
9715lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9716 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009717{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009718 /* Obscure special case. */
9719 if (c == 0x3A3) {
9720 mapped[0] = handle_capital_sigma(kind, data, length, i);
9721 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009722 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009723 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009724}
9725
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009726static Py_ssize_t
9727do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009728{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009729 Py_ssize_t i, k = 0;
9730 int n_res, j;
9731 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009732
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009733 c = PyUnicode_READ(kind, data, 0);
9734 n_res = _PyUnicode_ToUpperFull(c, mapped);
9735 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009736 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009737 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009738 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009739 for (i = 1; i < length; i++) {
9740 c = PyUnicode_READ(kind, data, i);
9741 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9742 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009743 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009744 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009745 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009746 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009747 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009748}
9749
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009750static Py_ssize_t
9751do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9752 Py_ssize_t i, k = 0;
9753
9754 for (i = 0; i < length; i++) {
9755 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9756 int n_res, j;
9757 if (Py_UNICODE_ISUPPER(c)) {
9758 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9759 }
9760 else if (Py_UNICODE_ISLOWER(c)) {
9761 n_res = _PyUnicode_ToUpperFull(c, mapped);
9762 }
9763 else {
9764 n_res = 1;
9765 mapped[0] = c;
9766 }
9767 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009768 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009769 res[k++] = mapped[j];
9770 }
9771 }
9772 return k;
9773}
9774
9775static Py_ssize_t
9776do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9777 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009778{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009779 Py_ssize_t i, k = 0;
9780
9781 for (i = 0; i < length; i++) {
9782 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9783 int n_res, j;
9784 if (lower)
9785 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9786 else
9787 n_res = _PyUnicode_ToUpperFull(c, mapped);
9788 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009789 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009790 res[k++] = mapped[j];
9791 }
9792 }
9793 return k;
9794}
9795
9796static Py_ssize_t
9797do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9798{
9799 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9800}
9801
9802static Py_ssize_t
9803do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9804{
9805 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9806}
9807
Benjamin Petersone51757f2012-01-12 21:10:29 -05009808static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009809do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9810{
9811 Py_ssize_t i, k = 0;
9812
9813 for (i = 0; i < length; i++) {
9814 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9815 Py_UCS4 mapped[3];
9816 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9817 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009818 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009819 res[k++] = mapped[j];
9820 }
9821 }
9822 return k;
9823}
9824
9825static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009826do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9827{
9828 Py_ssize_t i, k = 0;
9829 int previous_is_cased;
9830
9831 previous_is_cased = 0;
9832 for (i = 0; i < length; i++) {
9833 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9834 Py_UCS4 mapped[3];
9835 int n_res, j;
9836
9837 if (previous_is_cased)
9838 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9839 else
9840 n_res = _PyUnicode_ToTitleFull(c, mapped);
9841
9842 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009843 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009844 res[k++] = mapped[j];
9845 }
9846
9847 previous_is_cased = _PyUnicode_IsCased(c);
9848 }
9849 return k;
9850}
9851
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009852static PyObject *
9853case_operation(PyObject *self,
9854 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9855{
9856 PyObject *res = NULL;
9857 Py_ssize_t length, newlength = 0;
9858 int kind, outkind;
9859 void *data, *outdata;
9860 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9861
Benjamin Petersoneea48462012-01-16 14:28:50 -05009862 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009863
9864 kind = PyUnicode_KIND(self);
9865 data = PyUnicode_DATA(self);
9866 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009867 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009868 PyErr_SetString(PyExc_OverflowError, "string is too long");
9869 return NULL;
9870 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009871 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009872 if (tmp == NULL)
9873 return PyErr_NoMemory();
9874 newlength = perform(kind, data, length, tmp, &maxchar);
9875 res = PyUnicode_New(newlength, maxchar);
9876 if (res == NULL)
9877 goto leave;
9878 tmpend = tmp + newlength;
9879 outdata = PyUnicode_DATA(res);
9880 outkind = PyUnicode_KIND(res);
9881 switch (outkind) {
9882 case PyUnicode_1BYTE_KIND:
9883 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9884 break;
9885 case PyUnicode_2BYTE_KIND:
9886 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9887 break;
9888 case PyUnicode_4BYTE_KIND:
9889 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9890 break;
9891 default:
9892 assert(0);
9893 break;
9894 }
9895 leave:
9896 PyMem_FREE(tmp);
9897 return res;
9898}
9899
Tim Peters8ce9f162004-08-27 01:49:32 +00009900PyObject *
9901PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009902{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009903 PyObject *res;
9904 PyObject *fseq;
9905 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009906 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009907
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009908 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009909 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009910 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009911 }
9912
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009913 /* NOTE: the following code can't call back into Python code,
9914 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009915 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009916
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009917 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009918 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009919 res = _PyUnicode_JoinArray(separator, items, seqlen);
9920 Py_DECREF(fseq);
9921 return res;
9922}
9923
9924PyObject *
9925_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9926{
9927 PyObject *res = NULL; /* the result */
9928 PyObject *sep = NULL;
9929 Py_ssize_t seplen;
9930 PyObject *item;
9931 Py_ssize_t sz, i, res_offset;
9932 Py_UCS4 maxchar;
9933 Py_UCS4 item_maxchar;
9934 int use_memcpy;
9935 unsigned char *res_data = NULL, *sep_data = NULL;
9936 PyObject *last_obj;
9937 unsigned int kind = 0;
9938
Tim Peters05eba1f2004-08-27 21:32:02 +00009939 /* If empty sequence, return u"". */
9940 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009941 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009942 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009943
Tim Peters05eba1f2004-08-27 21:32:02 +00009944 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009945 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009946 if (seqlen == 1) {
9947 if (PyUnicode_CheckExact(items[0])) {
9948 res = items[0];
9949 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009950 return res;
9951 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009952 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009953 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009954 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009955 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009956 /* Set up sep and seplen */
9957 if (separator == NULL) {
9958 /* fall back to a blank space separator */
9959 sep = PyUnicode_FromOrdinal(' ');
9960 if (!sep)
9961 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009962 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009963 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009964 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009965 else {
9966 if (!PyUnicode_Check(separator)) {
9967 PyErr_Format(PyExc_TypeError,
9968 "separator: expected str instance,"
9969 " %.80s found",
9970 Py_TYPE(separator)->tp_name);
9971 goto onError;
9972 }
9973 if (PyUnicode_READY(separator))
9974 goto onError;
9975 sep = separator;
9976 seplen = PyUnicode_GET_LENGTH(separator);
9977 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9978 /* inc refcount to keep this code path symmetric with the
9979 above case of a blank separator */
9980 Py_INCREF(sep);
9981 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009982 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009983 }
9984
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009985 /* There are at least two things to join, or else we have a subclass
9986 * of str in the sequence.
9987 * Do a pre-pass to figure out the total amount of space we'll
9988 * need (sz), and see whether all argument are strings.
9989 */
9990 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009991#ifdef Py_DEBUG
9992 use_memcpy = 0;
9993#else
9994 use_memcpy = 1;
9995#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009996 for (i = 0; i < seqlen; i++) {
9997 const Py_ssize_t old_sz = sz;
9998 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009999 if (!PyUnicode_Check(item)) {
10000 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +020010001 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +000010002 " %.80s found",
10003 i, Py_TYPE(item)->tp_name);
10004 goto onError;
10005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 if (PyUnicode_READY(item) == -1)
10007 goto onError;
10008 sz += PyUnicode_GET_LENGTH(item);
10009 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010010 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010011 if (i != 0)
10012 sz += seplen;
10013 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
10014 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010015 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010016 goto onError;
10017 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010018 if (use_memcpy && last_obj != NULL) {
10019 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10020 use_memcpy = 0;
10021 }
10022 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010023 }
Tim Petersced69f82003-09-16 20:30:58 +000010024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010026 if (res == NULL)
10027 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010028
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010029 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010030#ifdef Py_DEBUG
10031 use_memcpy = 0;
10032#else
10033 if (use_memcpy) {
10034 res_data = PyUnicode_1BYTE_DATA(res);
10035 kind = PyUnicode_KIND(res);
10036 if (seplen != 0)
10037 sep_data = PyUnicode_1BYTE_DATA(sep);
10038 }
10039#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010040 if (use_memcpy) {
10041 for (i = 0; i < seqlen; ++i) {
10042 Py_ssize_t itemlen;
10043 item = items[i];
10044
10045 /* Copy item, and maybe the separator. */
10046 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010047 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010048 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010049 kind * seplen);
10050 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010051 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010052
10053 itemlen = PyUnicode_GET_LENGTH(item);
10054 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010055 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010056 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010057 kind * itemlen);
10058 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010059 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010060 }
10061 assert(res_data == PyUnicode_1BYTE_DATA(res)
10062 + kind * PyUnicode_GET_LENGTH(res));
10063 }
10064 else {
10065 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10066 Py_ssize_t itemlen;
10067 item = items[i];
10068
10069 /* Copy item, and maybe the separator. */
10070 if (i && seplen != 0) {
10071 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10072 res_offset += seplen;
10073 }
10074
10075 itemlen = PyUnicode_GET_LENGTH(item);
10076 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010077 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010078 res_offset += itemlen;
10079 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010080 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010081 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010082 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010083
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010085 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010087
Benjamin Peterson29060642009-01-31 22:14:21 +000010088 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010090 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010091 return NULL;
10092}
10093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094#define FILL(kind, data, value, start, length) \
10095 do { \
10096 Py_ssize_t i_ = 0; \
10097 assert(kind != PyUnicode_WCHAR_KIND); \
10098 switch ((kind)) { \
10099 case PyUnicode_1BYTE_KIND: { \
10100 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010101 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 break; \
10103 } \
10104 case PyUnicode_2BYTE_KIND: { \
10105 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10106 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10107 break; \
10108 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010109 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010110 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10111 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10112 break; \
10113 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010114 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010115 } \
10116 } while (0)
10117
Victor Stinnerd3f08822012-05-29 12:57:52 +020010118void
10119_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10120 Py_UCS4 fill_char)
10121{
10122 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10123 const void *data = PyUnicode_DATA(unicode);
10124 assert(PyUnicode_IS_READY(unicode));
10125 assert(unicode_modifiable(unicode));
10126 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10127 assert(start >= 0);
10128 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10129 FILL(kind, data, fill_char, start, length);
10130}
10131
Victor Stinner3fe55312012-01-04 00:33:50 +010010132Py_ssize_t
10133PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10134 Py_UCS4 fill_char)
10135{
10136 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010137
10138 if (!PyUnicode_Check(unicode)) {
10139 PyErr_BadInternalCall();
10140 return -1;
10141 }
10142 if (PyUnicode_READY(unicode) == -1)
10143 return -1;
10144 if (unicode_check_modifiable(unicode))
10145 return -1;
10146
Victor Stinnerd3f08822012-05-29 12:57:52 +020010147 if (start < 0) {
10148 PyErr_SetString(PyExc_IndexError, "string index out of range");
10149 return -1;
10150 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010151 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10152 PyErr_SetString(PyExc_ValueError,
10153 "fill character is bigger than "
10154 "the string maximum character");
10155 return -1;
10156 }
10157
10158 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10159 length = Py_MIN(maxlen, length);
10160 if (length <= 0)
10161 return 0;
10162
Victor Stinnerd3f08822012-05-29 12:57:52 +020010163 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010164 return length;
10165}
10166
Victor Stinner9310abb2011-10-05 00:59:23 +020010167static PyObject *
10168pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010169 Py_ssize_t left,
10170 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010172{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010173 PyObject *u;
10174 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010175 int kind;
10176 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010177
10178 if (left < 0)
10179 left = 0;
10180 if (right < 0)
10181 right = 0;
10182
Victor Stinnerc4b49542011-12-11 22:44:26 +010010183 if (left == 0 && right == 0)
10184 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010185
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10187 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010188 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10189 return NULL;
10190 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010192 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010194 if (!u)
10195 return NULL;
10196
10197 kind = PyUnicode_KIND(u);
10198 data = PyUnicode_DATA(u);
10199 if (left)
10200 FILL(kind, data, fill, 0, left);
10201 if (right)
10202 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010203 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010204 assert(_PyUnicode_CheckConsistency(u, 1));
10205 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010206}
10207
Alexander Belopolsky40018472011-02-26 01:02:56 +000010208PyObject *
10209PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010210{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010211 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010212
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010213 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010214 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010215
Benjamin Petersonead6b532011-12-20 17:23:42 -060010216 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010218 if (PyUnicode_IS_ASCII(string))
10219 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010220 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010221 PyUnicode_GET_LENGTH(string), keepends);
10222 else
10223 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010224 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010225 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 break;
10227 case PyUnicode_2BYTE_KIND:
10228 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010229 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 PyUnicode_GET_LENGTH(string), keepends);
10231 break;
10232 case PyUnicode_4BYTE_KIND:
10233 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010234 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 PyUnicode_GET_LENGTH(string), keepends);
10236 break;
10237 default:
10238 assert(0);
10239 list = 0;
10240 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010241 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010242}
10243
Alexander Belopolsky40018472011-02-26 01:02:56 +000010244static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010245split(PyObject *self,
10246 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010247 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010248{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010249 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 void *buf1, *buf2;
10251 Py_ssize_t len1, len2;
10252 PyObject* out;
10253
Guido van Rossumd57fd912000-03-10 22:53:23 +000010254 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010255 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 if (PyUnicode_READY(self) == -1)
10258 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010259
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010261 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010263 if (PyUnicode_IS_ASCII(self))
10264 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010265 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010266 PyUnicode_GET_LENGTH(self), maxcount
10267 );
10268 else
10269 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010270 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010271 PyUnicode_GET_LENGTH(self), maxcount
10272 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 case PyUnicode_2BYTE_KIND:
10274 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010275 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 PyUnicode_GET_LENGTH(self), maxcount
10277 );
10278 case PyUnicode_4BYTE_KIND:
10279 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010280 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 PyUnicode_GET_LENGTH(self), maxcount
10282 );
10283 default:
10284 assert(0);
10285 return NULL;
10286 }
10287
10288 if (PyUnicode_READY(substring) == -1)
10289 return NULL;
10290
10291 kind1 = PyUnicode_KIND(self);
10292 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 len1 = PyUnicode_GET_LENGTH(self);
10294 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010295 if (kind1 < kind2 || len1 < len2) {
10296 out = PyList_New(1);
10297 if (out == NULL)
10298 return NULL;
10299 Py_INCREF(self);
10300 PyList_SET_ITEM(out, 0, self);
10301 return out;
10302 }
10303 buf1 = PyUnicode_DATA(self);
10304 buf2 = PyUnicode_DATA(substring);
10305 if (kind2 != kind1) {
10306 buf2 = _PyUnicode_AsKind(substring, kind1);
10307 if (!buf2)
10308 return NULL;
10309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010311 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010313 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10314 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010315 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010316 else
10317 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010318 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 break;
10320 case PyUnicode_2BYTE_KIND:
10321 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010322 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 break;
10324 case PyUnicode_4BYTE_KIND:
10325 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010326 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 break;
10328 default:
10329 out = NULL;
10330 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010331 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 PyMem_Free(buf2);
10333 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010334}
10335
Alexander Belopolsky40018472011-02-26 01:02:56 +000010336static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010337rsplit(PyObject *self,
10338 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010339 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010340{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010341 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 void *buf1, *buf2;
10343 Py_ssize_t len1, len2;
10344 PyObject* out;
10345
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010346 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010347 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 if (PyUnicode_READY(self) == -1)
10350 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010351
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010353 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010355 if (PyUnicode_IS_ASCII(self))
10356 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010357 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010358 PyUnicode_GET_LENGTH(self), maxcount
10359 );
10360 else
10361 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010362 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010363 PyUnicode_GET_LENGTH(self), maxcount
10364 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 case PyUnicode_2BYTE_KIND:
10366 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010367 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 PyUnicode_GET_LENGTH(self), maxcount
10369 );
10370 case PyUnicode_4BYTE_KIND:
10371 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010372 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 PyUnicode_GET_LENGTH(self), maxcount
10374 );
10375 default:
10376 assert(0);
10377 return NULL;
10378 }
10379
10380 if (PyUnicode_READY(substring) == -1)
10381 return NULL;
10382
10383 kind1 = PyUnicode_KIND(self);
10384 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 len1 = PyUnicode_GET_LENGTH(self);
10386 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010387 if (kind1 < kind2 || len1 < len2) {
10388 out = PyList_New(1);
10389 if (out == NULL)
10390 return NULL;
10391 Py_INCREF(self);
10392 PyList_SET_ITEM(out, 0, self);
10393 return out;
10394 }
10395 buf1 = PyUnicode_DATA(self);
10396 buf2 = PyUnicode_DATA(substring);
10397 if (kind2 != kind1) {
10398 buf2 = _PyUnicode_AsKind(substring, kind1);
10399 if (!buf2)
10400 return NULL;
10401 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010403 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010405 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10406 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010407 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010408 else
10409 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010410 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 break;
10412 case PyUnicode_2BYTE_KIND:
10413 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010414 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 break;
10416 case PyUnicode_4BYTE_KIND:
10417 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010418 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 break;
10420 default:
10421 out = NULL;
10422 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010423 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 PyMem_Free(buf2);
10425 return out;
10426}
10427
10428static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010429anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10430 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010432 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010434 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10435 return asciilib_find(buf1, len1, buf2, len2, offset);
10436 else
10437 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438 case PyUnicode_2BYTE_KIND:
10439 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10440 case PyUnicode_4BYTE_KIND:
10441 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10442 }
10443 assert(0);
10444 return -1;
10445}
10446
10447static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010448anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10449 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010451 switch (kind) {
10452 case PyUnicode_1BYTE_KIND:
10453 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10454 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10455 else
10456 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10457 case PyUnicode_2BYTE_KIND:
10458 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10459 case PyUnicode_4BYTE_KIND:
10460 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10461 }
10462 assert(0);
10463 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010464}
10465
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010466static void
10467replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10468 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10469{
10470 int kind = PyUnicode_KIND(u);
10471 void *data = PyUnicode_DATA(u);
10472 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10473 if (kind == PyUnicode_1BYTE_KIND) {
10474 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10475 (Py_UCS1 *)data + len,
10476 u1, u2, maxcount);
10477 }
10478 else if (kind == PyUnicode_2BYTE_KIND) {
10479 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10480 (Py_UCS2 *)data + len,
10481 u1, u2, maxcount);
10482 }
10483 else {
10484 assert(kind == PyUnicode_4BYTE_KIND);
10485 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10486 (Py_UCS4 *)data + len,
10487 u1, u2, maxcount);
10488 }
10489}
10490
Alexander Belopolsky40018472011-02-26 01:02:56 +000010491static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492replace(PyObject *self, PyObject *str1,
10493 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010494{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 PyObject *u;
10496 char *sbuf = PyUnicode_DATA(self);
10497 char *buf1 = PyUnicode_DATA(str1);
10498 char *buf2 = PyUnicode_DATA(str2);
10499 int srelease = 0, release1 = 0, release2 = 0;
10500 int skind = PyUnicode_KIND(self);
10501 int kind1 = PyUnicode_KIND(str1);
10502 int kind2 = PyUnicode_KIND(str2);
10503 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10504 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10505 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010506 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010507 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010508
10509 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010510 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010512 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010513
Victor Stinner59de0ee2011-10-07 10:01:28 +020010514 if (str1 == str2)
10515 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010516
Victor Stinner49a0a212011-10-12 23:46:10 +020010517 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010518 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10519 if (maxchar < maxchar_str1)
10520 /* substring too wide to be present */
10521 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010522 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10523 /* Replacing str1 with str2 may cause a maxchar reduction in the
10524 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010525 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010526 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010527
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010528 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010529 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010531 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010533 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010534 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010535 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010536
Victor Stinner69ed0f42013-04-09 21:48:24 +020010537 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010538 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010539 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010540 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010541 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010542 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010543 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010545
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010546 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10547 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010548 }
10549 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 int rkind = skind;
10551 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010552 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010553
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010554 if (kind1 < rkind) {
10555 /* widen substring */
10556 buf1 = _PyUnicode_AsKind(str1, rkind);
10557 if (!buf1) goto error;
10558 release1 = 1;
10559 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010560 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010561 if (i < 0)
10562 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 if (rkind > kind2) {
10564 /* widen replacement */
10565 buf2 = _PyUnicode_AsKind(str2, rkind);
10566 if (!buf2) goto error;
10567 release2 = 1;
10568 }
10569 else if (rkind < kind2) {
10570 /* widen self and buf1 */
10571 rkind = kind2;
10572 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010573 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 sbuf = _PyUnicode_AsKind(self, rkind);
10575 if (!sbuf) goto error;
10576 srelease = 1;
10577 buf1 = _PyUnicode_AsKind(str1, rkind);
10578 if (!buf1) goto error;
10579 release1 = 1;
10580 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010581 u = PyUnicode_New(slen, maxchar);
10582 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010584 assert(PyUnicode_KIND(u) == rkind);
10585 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010586
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010587 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010588 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010589 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010591 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010593
10594 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010595 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010596 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010597 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010598 if (i == -1)
10599 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010600 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010602 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010604 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010605 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010606 }
10607 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010609 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 int rkind = skind;
10611 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010612
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010613 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010614 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 buf1 = _PyUnicode_AsKind(str1, rkind);
10616 if (!buf1) goto error;
10617 release1 = 1;
10618 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010619 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010620 if (n == 0)
10621 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010623 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 buf2 = _PyUnicode_AsKind(str2, rkind);
10625 if (!buf2) goto error;
10626 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010628 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010629 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630 rkind = kind2;
10631 sbuf = _PyUnicode_AsKind(self, rkind);
10632 if (!sbuf) goto error;
10633 srelease = 1;
10634 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010635 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 buf1 = _PyUnicode_AsKind(str1, rkind);
10637 if (!buf1) goto error;
10638 release1 = 1;
10639 }
10640 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10641 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010642 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010643 PyErr_SetString(PyExc_OverflowError,
10644 "replace string is too long");
10645 goto error;
10646 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010647 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010648 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010649 _Py_INCREF_UNICODE_EMPTY();
10650 if (!unicode_empty)
10651 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010652 u = unicode_empty;
10653 goto done;
10654 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010655 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 PyErr_SetString(PyExc_OverflowError,
10657 "replace string is too long");
10658 goto error;
10659 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010660 u = PyUnicode_New(new_size, maxchar);
10661 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010662 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010663 assert(PyUnicode_KIND(u) == rkind);
10664 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010665 ires = i = 0;
10666 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010667 while (n-- > 0) {
10668 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010669 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010670 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010671 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010672 if (j == -1)
10673 break;
10674 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010675 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010676 memcpy(res + rkind * ires,
10677 sbuf + rkind * i,
10678 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010680 }
10681 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010682 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010683 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010684 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010685 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010686 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010687 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010688 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010689 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010690 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010691 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010692 memcpy(res + rkind * ires,
10693 sbuf + rkind * i,
10694 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010695 }
10696 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010697 /* interleave */
10698 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010699 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010701 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010702 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010703 if (--n <= 0)
10704 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010705 memcpy(res + rkind * ires,
10706 sbuf + rkind * i,
10707 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010708 ires++;
10709 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010710 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010711 memcpy(res + rkind * ires,
10712 sbuf + rkind * i,
10713 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010714 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010715 }
10716
10717 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010718 unicode_adjust_maxchar(&u);
10719 if (u == NULL)
10720 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010721 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010722
10723 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010724 if (srelease)
10725 PyMem_FREE(sbuf);
10726 if (release1)
10727 PyMem_FREE(buf1);
10728 if (release2)
10729 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010730 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010731 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010732
Benjamin Peterson29060642009-01-31 22:14:21 +000010733 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010734 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 if (srelease)
10736 PyMem_FREE(sbuf);
10737 if (release1)
10738 PyMem_FREE(buf1);
10739 if (release2)
10740 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010741 return unicode_result_unchanged(self);
10742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010743 error:
10744 if (srelease && sbuf)
10745 PyMem_FREE(sbuf);
10746 if (release1 && buf1)
10747 PyMem_FREE(buf1);
10748 if (release2 && buf2)
10749 PyMem_FREE(buf2);
10750 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010751}
10752
10753/* --- Unicode Object Methods --------------------------------------------- */
10754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010755PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010756 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010757\n\
10758Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010759characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760
10761static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010762unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010764 if (PyUnicode_READY(self) == -1)
10765 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010766 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767}
10768
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010769PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010770 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010771\n\
10772Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010773have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774
10775static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010776unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010777{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010778 if (PyUnicode_READY(self) == -1)
10779 return NULL;
10780 if (PyUnicode_GET_LENGTH(self) == 0)
10781 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010782 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010783}
10784
Benjamin Petersond5890c82012-01-14 13:23:30 -050010785PyDoc_STRVAR(casefold__doc__,
10786 "S.casefold() -> str\n\
10787\n\
10788Return a version of S suitable for caseless comparisons.");
10789
10790static PyObject *
10791unicode_casefold(PyObject *self)
10792{
10793 if (PyUnicode_READY(self) == -1)
10794 return NULL;
10795 if (PyUnicode_IS_ASCII(self))
10796 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010797 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010798}
10799
10800
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010801/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010802
10803static int
10804convert_uc(PyObject *obj, void *addr)
10805{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010807
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010808 if (!PyUnicode_Check(obj)) {
10809 PyErr_Format(PyExc_TypeError,
10810 "The fill character must be a unicode character, "
10811 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010812 return 0;
10813 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010814 if (PyUnicode_READY(obj) < 0)
10815 return 0;
10816 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010817 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010818 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010819 return 0;
10820 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010821 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010822 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010823}
10824
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010825PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010826 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010827\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010828Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010829done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830
10831static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010832unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010833{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010834 Py_ssize_t marg, left;
10835 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010836 Py_UCS4 fillchar = ' ';
10837
Victor Stinnere9a29352011-10-01 02:14:59 +020010838 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010839 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010840
Benjamin Petersonbac79492012-01-14 13:34:47 -050010841 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010842 return NULL;
10843
Victor Stinnerc4b49542011-12-11 22:44:26 +010010844 if (PyUnicode_GET_LENGTH(self) >= width)
10845 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010846
Victor Stinnerc4b49542011-12-11 22:44:26 +010010847 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010848 left = marg / 2 + (marg & width & 1);
10849
Victor Stinner9310abb2011-10-05 00:59:23 +020010850 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010851}
10852
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010853/* This function assumes that str1 and str2 are readied by the caller. */
10854
Marc-André Lemburge5034372000-08-08 08:04:29 +000010855static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010856unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010857{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010858#define COMPARE(TYPE1, TYPE2) \
10859 do { \
10860 TYPE1* p1 = (TYPE1 *)data1; \
10861 TYPE2* p2 = (TYPE2 *)data2; \
10862 TYPE1* end = p1 + len; \
10863 Py_UCS4 c1, c2; \
10864 for (; p1 != end; p1++, p2++) { \
10865 c1 = *p1; \
10866 c2 = *p2; \
10867 if (c1 != c2) \
10868 return (c1 < c2) ? -1 : 1; \
10869 } \
10870 } \
10871 while (0)
10872
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010873 int kind1, kind2;
10874 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010875 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010876
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010877 kind1 = PyUnicode_KIND(str1);
10878 kind2 = PyUnicode_KIND(str2);
10879 data1 = PyUnicode_DATA(str1);
10880 data2 = PyUnicode_DATA(str2);
10881 len1 = PyUnicode_GET_LENGTH(str1);
10882 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010883 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010884
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010885 switch(kind1) {
10886 case PyUnicode_1BYTE_KIND:
10887 {
10888 switch(kind2) {
10889 case PyUnicode_1BYTE_KIND:
10890 {
10891 int cmp = memcmp(data1, data2, len);
10892 /* normalize result of memcmp() into the range [-1; 1] */
10893 if (cmp < 0)
10894 return -1;
10895 if (cmp > 0)
10896 return 1;
10897 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010898 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010899 case PyUnicode_2BYTE_KIND:
10900 COMPARE(Py_UCS1, Py_UCS2);
10901 break;
10902 case PyUnicode_4BYTE_KIND:
10903 COMPARE(Py_UCS1, Py_UCS4);
10904 break;
10905 default:
10906 assert(0);
10907 }
10908 break;
10909 }
10910 case PyUnicode_2BYTE_KIND:
10911 {
10912 switch(kind2) {
10913 case PyUnicode_1BYTE_KIND:
10914 COMPARE(Py_UCS2, Py_UCS1);
10915 break;
10916 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010917 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010918 COMPARE(Py_UCS2, Py_UCS2);
10919 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010920 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010921 case PyUnicode_4BYTE_KIND:
10922 COMPARE(Py_UCS2, Py_UCS4);
10923 break;
10924 default:
10925 assert(0);
10926 }
10927 break;
10928 }
10929 case PyUnicode_4BYTE_KIND:
10930 {
10931 switch(kind2) {
10932 case PyUnicode_1BYTE_KIND:
10933 COMPARE(Py_UCS4, Py_UCS1);
10934 break;
10935 case PyUnicode_2BYTE_KIND:
10936 COMPARE(Py_UCS4, Py_UCS2);
10937 break;
10938 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010939 {
10940#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10941 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10942 /* normalize result of wmemcmp() into the range [-1; 1] */
10943 if (cmp < 0)
10944 return -1;
10945 if (cmp > 0)
10946 return 1;
10947#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010948 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010949#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010950 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010951 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010952 default:
10953 assert(0);
10954 }
10955 break;
10956 }
10957 default:
10958 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010959 }
10960
Victor Stinner770e19e2012-10-04 22:59:45 +020010961 if (len1 == len2)
10962 return 0;
10963 if (len1 < len2)
10964 return -1;
10965 else
10966 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010967
10968#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010969}
10970
Benjamin Peterson621b4302016-09-09 13:54:34 -070010971static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010972unicode_compare_eq(PyObject *str1, PyObject *str2)
10973{
10974 int kind;
10975 void *data1, *data2;
10976 Py_ssize_t len;
10977 int cmp;
10978
Victor Stinnere5567ad2012-10-23 02:48:49 +020010979 len = PyUnicode_GET_LENGTH(str1);
10980 if (PyUnicode_GET_LENGTH(str2) != len)
10981 return 0;
10982 kind = PyUnicode_KIND(str1);
10983 if (PyUnicode_KIND(str2) != kind)
10984 return 0;
10985 data1 = PyUnicode_DATA(str1);
10986 data2 = PyUnicode_DATA(str2);
10987
10988 cmp = memcmp(data1, data2, len * kind);
10989 return (cmp == 0);
10990}
10991
10992
Alexander Belopolsky40018472011-02-26 01:02:56 +000010993int
10994PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10997 if (PyUnicode_READY(left) == -1 ||
10998 PyUnicode_READY(right) == -1)
10999 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011000
11001 /* a string is equal to itself */
11002 if (left == right)
11003 return 0;
11004
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011005 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011006 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011007 PyErr_Format(PyExc_TypeError,
11008 "Can't compare %.100s and %.100s",
11009 left->ob_type->tp_name,
11010 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011011 return -1;
11012}
11013
Martin v. Löwis5b222132007-06-10 09:51:05 +000011014int
11015PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11016{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011017 Py_ssize_t i;
11018 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011019 Py_UCS4 chr;
11020
Victor Stinner910337b2011-10-03 03:20:16 +020011021 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011022 if (PyUnicode_READY(uni) == -1)
11023 return -1;
11024 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011025 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011026 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011027 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011028 size_t len, len2 = strlen(str);
11029 int cmp;
11030
11031 len = Py_MIN(len1, len2);
11032 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011033 if (cmp != 0) {
11034 if (cmp < 0)
11035 return -1;
11036 else
11037 return 1;
11038 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011039 if (len1 > len2)
11040 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011041 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011042 return -1; /* str is longer */
11043 return 0;
11044 }
11045 else {
11046 void *data = PyUnicode_DATA(uni);
11047 /* Compare Unicode string and source character set string */
11048 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011049 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011050 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11051 /* This check keeps Python strings that end in '\0' from comparing equal
11052 to C strings identical up to that point. */
11053 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11054 return 1; /* uni is longer */
11055 if (str[i])
11056 return -1; /* str is longer */
11057 return 0;
11058 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011059}
11060
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011061static int
11062non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11063{
11064 size_t i, len;
11065 const wchar_t *p;
11066 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11067 if (strlen(str) != len)
11068 return 0;
11069 p = _PyUnicode_WSTR(unicode);
11070 assert(p);
11071 for (i = 0; i < len; i++) {
11072 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011073 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011074 return 0;
11075 }
11076 return 1;
11077}
11078
11079int
11080_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11081{
11082 size_t len;
11083 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011084 assert(str);
11085#ifndef NDEBUG
11086 for (const char *p = str; *p; p++) {
11087 assert((unsigned char)*p < 128);
11088 }
11089#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011090 if (PyUnicode_READY(unicode) == -1) {
11091 /* Memory error or bad data */
11092 PyErr_Clear();
11093 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11094 }
11095 if (!PyUnicode_IS_ASCII(unicode))
11096 return 0;
11097 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11098 return strlen(str) == len &&
11099 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11100}
11101
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011102int
11103_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11104{
11105 PyObject *right_uni;
11106 Py_hash_t hash;
11107
11108 assert(_PyUnicode_CHECK(left));
11109 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011110#ifndef NDEBUG
11111 for (const char *p = right->string; *p; p++) {
11112 assert((unsigned char)*p < 128);
11113 }
11114#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011115
11116 if (PyUnicode_READY(left) == -1) {
11117 /* memory error or bad data */
11118 PyErr_Clear();
11119 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11120 }
11121
11122 if (!PyUnicode_IS_ASCII(left))
11123 return 0;
11124
11125 right_uni = _PyUnicode_FromId(right); /* borrowed */
11126 if (right_uni == NULL) {
11127 /* memory error or bad data */
11128 PyErr_Clear();
11129 return _PyUnicode_EqualToASCIIString(left, right->string);
11130 }
11131
11132 if (left == right_uni)
11133 return 1;
11134
11135 if (PyUnicode_CHECK_INTERNED(left))
11136 return 0;
11137
11138 assert(_PyUnicode_HASH(right_uni) != 1);
11139 hash = _PyUnicode_HASH(left);
11140 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11141 return 0;
11142
11143 return unicode_compare_eq(left, right_uni);
11144}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011145
Benjamin Peterson29060642009-01-31 22:14:21 +000011146#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011147 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011148
Alexander Belopolsky40018472011-02-26 01:02:56 +000011149PyObject *
11150PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011151{
11152 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011153 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011154
Victor Stinnere5567ad2012-10-23 02:48:49 +020011155 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11156 Py_RETURN_NOTIMPLEMENTED;
11157
11158 if (PyUnicode_READY(left) == -1 ||
11159 PyUnicode_READY(right) == -1)
11160 return NULL;
11161
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011162 if (left == right) {
11163 switch (op) {
11164 case Py_EQ:
11165 case Py_LE:
11166 case Py_GE:
11167 /* a string is equal to itself */
11168 v = Py_True;
11169 break;
11170 case Py_NE:
11171 case Py_LT:
11172 case Py_GT:
11173 v = Py_False;
11174 break;
11175 default:
11176 PyErr_BadArgument();
11177 return NULL;
11178 }
11179 }
11180 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011181 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011182 result ^= (op == Py_NE);
11183 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011184 }
11185 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011186 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011187
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011188 /* Convert the return value to a Boolean */
11189 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011190 case Py_LE:
11191 v = TEST_COND(result <= 0);
11192 break;
11193 case Py_GE:
11194 v = TEST_COND(result >= 0);
11195 break;
11196 case Py_LT:
11197 v = TEST_COND(result == -1);
11198 break;
11199 case Py_GT:
11200 v = TEST_COND(result == 1);
11201 break;
11202 default:
11203 PyErr_BadArgument();
11204 return NULL;
11205 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011206 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011207 Py_INCREF(v);
11208 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011209}
11210
Alexander Belopolsky40018472011-02-26 01:02:56 +000011211int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011212_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11213{
11214 return unicode_eq(aa, bb);
11215}
11216
11217int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011218PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011219{
Victor Stinner77282cb2013-04-14 19:22:47 +020011220 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011221 void *buf1, *buf2;
11222 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011223 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011224
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011225 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011226 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011227 "'in <string>' requires string as left operand, not %.100s",
11228 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011229 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011230 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011231 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011232 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011233 if (ensure_unicode(str) < 0)
11234 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011235
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011236 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011237 kind2 = PyUnicode_KIND(substr);
11238 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011239 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011240 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011241 len2 = PyUnicode_GET_LENGTH(substr);
11242 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011243 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011244 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011245 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011246 if (len2 == 1) {
11247 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11248 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011249 return result;
11250 }
11251 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011252 buf2 = _PyUnicode_AsKind(substr, kind1);
11253 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011254 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011256
Victor Stinner77282cb2013-04-14 19:22:47 +020011257 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011258 case PyUnicode_1BYTE_KIND:
11259 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11260 break;
11261 case PyUnicode_2BYTE_KIND:
11262 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11263 break;
11264 case PyUnicode_4BYTE_KIND:
11265 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11266 break;
11267 default:
11268 result = -1;
11269 assert(0);
11270 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011271
Victor Stinner77282cb2013-04-14 19:22:47 +020011272 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011273 PyMem_Free(buf2);
11274
Guido van Rossum403d68b2000-03-13 15:55:09 +000011275 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011276}
11277
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278/* Concat to string or Unicode object giving a new Unicode object. */
11279
Alexander Belopolsky40018472011-02-26 01:02:56 +000011280PyObject *
11281PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011283 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011284 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011285 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011287 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11288 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289
11290 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011291 if (left == unicode_empty)
11292 return PyUnicode_FromObject(right);
11293 if (right == unicode_empty)
11294 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011296 left_len = PyUnicode_GET_LENGTH(left);
11297 right_len = PyUnicode_GET_LENGTH(right);
11298 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011299 PyErr_SetString(PyExc_OverflowError,
11300 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011301 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011302 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011303 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011304
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011305 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11306 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011307 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011308
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011310 result = PyUnicode_New(new_len, maxchar);
11311 if (result == NULL)
11312 return NULL;
11313 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11314 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11315 assert(_PyUnicode_CheckConsistency(result, 1));
11316 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011317}
11318
Walter Dörwald1ab83302007-05-18 17:15:44 +000011319void
Victor Stinner23e56682011-10-03 03:54:37 +020011320PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011321{
Victor Stinner23e56682011-10-03 03:54:37 +020011322 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011323 Py_UCS4 maxchar, maxchar2;
11324 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011325
11326 if (p_left == NULL) {
11327 if (!PyErr_Occurred())
11328 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011329 return;
11330 }
Victor Stinner23e56682011-10-03 03:54:37 +020011331 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011332 if (right == NULL || left == NULL
11333 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011334 if (!PyErr_Occurred())
11335 PyErr_BadInternalCall();
11336 goto error;
11337 }
11338
Benjamin Petersonbac79492012-01-14 13:34:47 -050011339 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011340 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011341 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011342 goto error;
11343
Victor Stinner488fa492011-12-12 00:01:39 +010011344 /* Shortcuts */
11345 if (left == unicode_empty) {
11346 Py_DECREF(left);
11347 Py_INCREF(right);
11348 *p_left = right;
11349 return;
11350 }
11351 if (right == unicode_empty)
11352 return;
11353
11354 left_len = PyUnicode_GET_LENGTH(left);
11355 right_len = PyUnicode_GET_LENGTH(right);
11356 if (left_len > PY_SSIZE_T_MAX - right_len) {
11357 PyErr_SetString(PyExc_OverflowError,
11358 "strings are too large to concat");
11359 goto error;
11360 }
11361 new_len = left_len + right_len;
11362
11363 if (unicode_modifiable(left)
11364 && PyUnicode_CheckExact(right)
11365 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011366 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11367 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011368 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011369 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011370 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11371 {
11372 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011373 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011374 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011375
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011376 /* copy 'right' into the newly allocated area of 'left' */
11377 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011378 }
Victor Stinner488fa492011-12-12 00:01:39 +010011379 else {
11380 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11381 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011382 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011383
Victor Stinner488fa492011-12-12 00:01:39 +010011384 /* Concat the two Unicode strings */
11385 res = PyUnicode_New(new_len, maxchar);
11386 if (res == NULL)
11387 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011388 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11389 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011390 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011391 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011392 }
11393 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011394 return;
11395
11396error:
Victor Stinner488fa492011-12-12 00:01:39 +010011397 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011398}
11399
11400void
11401PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11402{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011403 PyUnicode_Append(pleft, right);
11404 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011405}
11406
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011407/*
11408Wraps stringlib_parse_args_finds() and additionally ensures that the
11409first argument is a unicode object.
11410*/
11411
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011412static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011413parse_args_finds_unicode(const char * function_name, PyObject *args,
11414 PyObject **substring,
11415 Py_ssize_t *start, Py_ssize_t *end)
11416{
11417 if(stringlib_parse_args_finds(function_name, args, substring,
11418 start, end)) {
11419 if (ensure_unicode(*substring) < 0)
11420 return 0;
11421 return 1;
11422 }
11423 return 0;
11424}
11425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011426PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011427 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011429Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011430string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011431interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432
11433static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011434unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011436 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011437 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011438 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011440 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 void *buf1, *buf2;
11442 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011444 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011445 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 kind1 = PyUnicode_KIND(self);
11448 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011449 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011450 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 len1 = PyUnicode_GET_LENGTH(self);
11453 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011455 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011456 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011457
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011458 buf1 = PyUnicode_DATA(self);
11459 buf2 = PyUnicode_DATA(substring);
11460 if (kind2 != kind1) {
11461 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011462 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011463 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011464 }
11465 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 case PyUnicode_1BYTE_KIND:
11467 iresult = ucs1lib_count(
11468 ((Py_UCS1*)buf1) + start, end - start,
11469 buf2, len2, PY_SSIZE_T_MAX
11470 );
11471 break;
11472 case PyUnicode_2BYTE_KIND:
11473 iresult = ucs2lib_count(
11474 ((Py_UCS2*)buf1) + start, end - start,
11475 buf2, len2, PY_SSIZE_T_MAX
11476 );
11477 break;
11478 case PyUnicode_4BYTE_KIND:
11479 iresult = ucs4lib_count(
11480 ((Py_UCS4*)buf1) + start, end - start,
11481 buf2, len2, PY_SSIZE_T_MAX
11482 );
11483 break;
11484 default:
11485 assert(0); iresult = 0;
11486 }
11487
11488 result = PyLong_FromSsize_t(iresult);
11489
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011490 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011491 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493 return result;
11494}
11495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011496PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011497 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011499Encode S using the codec registered for encoding. Default encoding\n\
11500is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011501handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011502a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11503'xmlcharrefreplace' as well as any other name registered with\n\
11504codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505
11506static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011507unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011509 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510 char *encoding = NULL;
11511 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011512
Benjamin Peterson308d6372009-09-18 21:42:35 +000011513 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11514 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011516 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011517}
11518
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011519PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011520 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521\n\
11522Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011523If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524
11525static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011526unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011528 Py_ssize_t i, j, line_pos, src_len, incr;
11529 Py_UCS4 ch;
11530 PyObject *u;
11531 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011532 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011534 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011535 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536
Ezio Melotti745d54d2013-11-16 19:10:57 +020011537 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11538 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011539 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540
Antoine Pitrou22425222011-10-04 19:10:51 +020011541 if (PyUnicode_READY(self) == -1)
11542 return NULL;
11543
Thomas Wouters7e474022000-07-16 12:04:32 +000011544 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011545 src_len = PyUnicode_GET_LENGTH(self);
11546 i = j = line_pos = 0;
11547 kind = PyUnicode_KIND(self);
11548 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011549 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011550 for (; i < src_len; i++) {
11551 ch = PyUnicode_READ(kind, src_data, i);
11552 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011553 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011554 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011555 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011556 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011557 goto overflow;
11558 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011559 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011560 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011561 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011563 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011564 goto overflow;
11565 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011567 if (ch == '\n' || ch == '\r')
11568 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011570 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011571 if (!found)
11572 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011573
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011575 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576 if (!u)
11577 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011578 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579
Antoine Pitroue71d5742011-10-04 15:55:09 +020011580 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581
Antoine Pitroue71d5742011-10-04 15:55:09 +020011582 for (; i < src_len; i++) {
11583 ch = PyUnicode_READ(kind, src_data, i);
11584 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011585 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011586 incr = tabsize - (line_pos % tabsize);
11587 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011588 FILL(kind, dest_data, ' ', j, incr);
11589 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011590 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011591 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011592 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011593 line_pos++;
11594 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011595 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011596 if (ch == '\n' || ch == '\r')
11597 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011599 }
11600 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011601 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011602
Antoine Pitroue71d5742011-10-04 15:55:09 +020011603 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011604 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11605 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606}
11607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011608PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011609 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610\n\
11611Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011612such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613arguments start and end are interpreted as in slice notation.\n\
11614\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011615Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616
11617static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011618unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011620 /* initialize variables to prevent gcc warning */
11621 PyObject *substring = NULL;
11622 Py_ssize_t start = 0;
11623 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011624 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011626 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011629 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011632 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011634 if (result == -2)
11635 return NULL;
11636
Christian Heimes217cfd12007-12-02 14:31:20 +000011637 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011638}
11639
11640static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011641unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011643 void *data;
11644 enum PyUnicode_Kind kind;
11645 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011646
11647 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11648 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011650 }
11651 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11652 PyErr_SetString(PyExc_IndexError, "string index out of range");
11653 return NULL;
11654 }
11655 kind = PyUnicode_KIND(self);
11656 data = PyUnicode_DATA(self);
11657 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011658 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659}
11660
Guido van Rossumc2504932007-09-18 19:42:40 +000011661/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011662 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011663static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011664unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665{
Guido van Rossumc2504932007-09-18 19:42:40 +000011666 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011667 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011668
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011669#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011670 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011671#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 if (_PyUnicode_HASH(self) != -1)
11673 return _PyUnicode_HASH(self);
11674 if (PyUnicode_READY(self) == -1)
11675 return -1;
11676 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011677 /*
11678 We make the hash of the empty string be 0, rather than using
11679 (prefix ^ suffix), since this slightly obfuscates the hash secret
11680 */
11681 if (len == 0) {
11682 _PyUnicode_HASH(self) = 0;
11683 return 0;
11684 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011685 x = _Py_HashBytes(PyUnicode_DATA(self),
11686 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011687 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011688 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689}
11690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011691PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011692 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011694Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695
11696static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011699 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011700 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011701 PyObject *substring = NULL;
11702 Py_ssize_t start = 0;
11703 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011705 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011708 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011709 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011711 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 if (result == -2)
11714 return NULL;
11715
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716 if (result < 0) {
11717 PyErr_SetString(PyExc_ValueError, "substring not found");
11718 return NULL;
11719 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011720
Christian Heimes217cfd12007-12-02 14:31:20 +000011721 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722}
11723
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011724PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011725 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011726\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011727Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011728at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729
11730static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011731unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011733 Py_ssize_t i, length;
11734 int kind;
11735 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736 int cased;
11737
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011738 if (PyUnicode_READY(self) == -1)
11739 return NULL;
11740 length = PyUnicode_GET_LENGTH(self);
11741 kind = PyUnicode_KIND(self);
11742 data = PyUnicode_DATA(self);
11743
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011745 if (length == 1)
11746 return PyBool_FromLong(
11747 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011748
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011749 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011750 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011751 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011752
Guido van Rossumd57fd912000-03-10 22:53:23 +000011753 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754 for (i = 0; i < length; i++) {
11755 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011756
Benjamin Peterson29060642009-01-31 22:14:21 +000011757 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11758 return PyBool_FromLong(0);
11759 else if (!cased && Py_UNICODE_ISLOWER(ch))
11760 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011762 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763}
11764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011765PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011766 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011767\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011768Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011769at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770
11771static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011772unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011774 Py_ssize_t i, length;
11775 int kind;
11776 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777 int cased;
11778
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 if (PyUnicode_READY(self) == -1)
11780 return NULL;
11781 length = PyUnicode_GET_LENGTH(self);
11782 kind = PyUnicode_KIND(self);
11783 data = PyUnicode_DATA(self);
11784
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011786 if (length == 1)
11787 return PyBool_FromLong(
11788 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011790 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011791 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011792 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011793
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011795 for (i = 0; i < length; i++) {
11796 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011797
Benjamin Peterson29060642009-01-31 22:14:21 +000011798 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11799 return PyBool_FromLong(0);
11800 else if (!cased && Py_UNICODE_ISUPPER(ch))
11801 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011802 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011803 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804}
11805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011806PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011807 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011808\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011809Return True if S is a titlecased string and there is at least one\n\
11810character in S, i.e. upper- and titlecase characters may only\n\
11811follow uncased characters and lowercase characters only cased ones.\n\
11812Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011813
11814static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011815unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011817 Py_ssize_t i, length;
11818 int kind;
11819 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820 int cased, previous_is_cased;
11821
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011822 if (PyUnicode_READY(self) == -1)
11823 return NULL;
11824 length = PyUnicode_GET_LENGTH(self);
11825 kind = PyUnicode_KIND(self);
11826 data = PyUnicode_DATA(self);
11827
Guido van Rossumd57fd912000-03-10 22:53:23 +000011828 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011829 if (length == 1) {
11830 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11831 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11832 (Py_UNICODE_ISUPPER(ch) != 0));
11833 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011835 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011836 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011837 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011838
Guido van Rossumd57fd912000-03-10 22:53:23 +000011839 cased = 0;
11840 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011841 for (i = 0; i < length; i++) {
11842 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011843
Benjamin Peterson29060642009-01-31 22:14:21 +000011844 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11845 if (previous_is_cased)
11846 return PyBool_FromLong(0);
11847 previous_is_cased = 1;
11848 cased = 1;
11849 }
11850 else if (Py_UNICODE_ISLOWER(ch)) {
11851 if (!previous_is_cased)
11852 return PyBool_FromLong(0);
11853 previous_is_cased = 1;
11854 cased = 1;
11855 }
11856 else
11857 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011859 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860}
11861
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011862PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011863 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011864\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011865Return True if all characters in S are whitespace\n\
11866and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011867
11868static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011869unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011871 Py_ssize_t i, length;
11872 int kind;
11873 void *data;
11874
11875 if (PyUnicode_READY(self) == -1)
11876 return NULL;
11877 length = PyUnicode_GET_LENGTH(self);
11878 kind = PyUnicode_KIND(self);
11879 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880
Guido van Rossumd57fd912000-03-10 22:53:23 +000011881 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 if (length == 1)
11883 return PyBool_FromLong(
11884 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011886 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011887 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011888 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011889
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 for (i = 0; i < length; i++) {
11891 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011892 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011893 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011895 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896}
11897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011898PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011899 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011900\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011901Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011902and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011903
11904static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011905unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011906{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 Py_ssize_t i, length;
11908 int kind;
11909 void *data;
11910
11911 if (PyUnicode_READY(self) == -1)
11912 return NULL;
11913 length = PyUnicode_GET_LENGTH(self);
11914 kind = PyUnicode_KIND(self);
11915 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011916
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011917 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 if (length == 1)
11919 return PyBool_FromLong(
11920 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011921
11922 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011923 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011924 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926 for (i = 0; i < length; i++) {
11927 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011928 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011929 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011930 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011931}
11932
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011933PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011934 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011935\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011936Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011937and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011938
11939static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011940unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011941{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011942 int kind;
11943 void *data;
11944 Py_ssize_t len, i;
11945
11946 if (PyUnicode_READY(self) == -1)
11947 return NULL;
11948
11949 kind = PyUnicode_KIND(self);
11950 data = PyUnicode_DATA(self);
11951 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011952
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011953 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 if (len == 1) {
11955 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11956 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11957 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011958
11959 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011961 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011962
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011963 for (i = 0; i < len; i++) {
11964 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011965 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011966 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011967 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011968 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011969}
11970
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011971PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011972 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011973\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011974Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011975False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011976
11977static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011978unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 Py_ssize_t i, length;
11981 int kind;
11982 void *data;
11983
11984 if (PyUnicode_READY(self) == -1)
11985 return NULL;
11986 length = PyUnicode_GET_LENGTH(self);
11987 kind = PyUnicode_KIND(self);
11988 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011989
Guido van Rossumd57fd912000-03-10 22:53:23 +000011990 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011991 if (length == 1)
11992 return PyBool_FromLong(
11993 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011994
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011995 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011997 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011998
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999 for (i = 0; i < length; i++) {
12000 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012001 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012002 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012003 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012004}
12005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012006PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012007 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012008\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000012009Return True if all characters in S are digits\n\
12010and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012011
12012static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012013unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012014{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 Py_ssize_t i, length;
12016 int kind;
12017 void *data;
12018
12019 if (PyUnicode_READY(self) == -1)
12020 return NULL;
12021 length = PyUnicode_GET_LENGTH(self);
12022 kind = PyUnicode_KIND(self);
12023 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024
Guido van Rossumd57fd912000-03-10 22:53:23 +000012025 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012026 if (length == 1) {
12027 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12028 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12029 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012030
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012031 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012032 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012033 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012034
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012035 for (i = 0; i < length; i++) {
12036 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012037 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012038 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012039 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040}
12041
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012042PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012043 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012044\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000012045Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012046False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012047
12048static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012049unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012051 Py_ssize_t i, length;
12052 int kind;
12053 void *data;
12054
12055 if (PyUnicode_READY(self) == -1)
12056 return NULL;
12057 length = PyUnicode_GET_LENGTH(self);
12058 kind = PyUnicode_KIND(self);
12059 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012060
Guido van Rossumd57fd912000-03-10 22:53:23 +000012061 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062 if (length == 1)
12063 return PyBool_FromLong(
12064 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012065
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012066 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012067 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012068 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012069
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012070 for (i = 0; i < length; i++) {
12071 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012072 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012073 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012074 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012075}
12076
Martin v. Löwis47383402007-08-15 07:32:56 +000012077int
12078PyUnicode_IsIdentifier(PyObject *self)
12079{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080 int kind;
12081 void *data;
12082 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012083 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012084
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085 if (PyUnicode_READY(self) == -1) {
12086 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012087 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 }
12089
12090 /* Special case for empty strings */
12091 if (PyUnicode_GET_LENGTH(self) == 0)
12092 return 0;
12093 kind = PyUnicode_KIND(self);
12094 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012095
12096 /* PEP 3131 says that the first character must be in
12097 XID_Start and subsequent characters in XID_Continue,
12098 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012099 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012100 letters, digits, underscore). However, given the current
12101 definition of XID_Start and XID_Continue, it is sufficient
12102 to check just for these, except that _ must be allowed
12103 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012104 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012105 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012106 return 0;
12107
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012108 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012109 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012110 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012111 return 1;
12112}
12113
12114PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012115 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012116\n\
12117Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012118to the language definition.\n\
12119\n\
12120Use keyword.iskeyword() to test for reserved identifiers\n\
12121such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012122
12123static PyObject*
12124unicode_isidentifier(PyObject *self)
12125{
12126 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12127}
12128
Georg Brandl559e5d72008-06-11 18:37:52 +000012129PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012130 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012131\n\
12132Return True if all characters in S are considered\n\
12133printable in repr() or S is empty, False otherwise.");
12134
12135static PyObject*
12136unicode_isprintable(PyObject *self)
12137{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012138 Py_ssize_t i, length;
12139 int kind;
12140 void *data;
12141
12142 if (PyUnicode_READY(self) == -1)
12143 return NULL;
12144 length = PyUnicode_GET_LENGTH(self);
12145 kind = PyUnicode_KIND(self);
12146 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012147
12148 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012149 if (length == 1)
12150 return PyBool_FromLong(
12151 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012153 for (i = 0; i < length; i++) {
12154 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012155 Py_RETURN_FALSE;
12156 }
12157 }
12158 Py_RETURN_TRUE;
12159}
12160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012161PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012162 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163\n\
12164Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012165iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166
12167static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012168unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012170 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171}
12172
Martin v. Löwis18e16552006-02-15 17:27:45 +000012173static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012174unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012176 if (PyUnicode_READY(self) == -1)
12177 return -1;
12178 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179}
12180
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012181PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012182 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012184Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012185done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186
12187static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012188unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012189{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012190 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012191 Py_UCS4 fillchar = ' ';
12192
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012193 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194 return NULL;
12195
Benjamin Petersonbac79492012-01-14 13:34:47 -050012196 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012197 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198
Victor Stinnerc4b49542011-12-11 22:44:26 +010012199 if (PyUnicode_GET_LENGTH(self) >= width)
12200 return unicode_result_unchanged(self);
12201
12202 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203}
12204
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012205PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012206 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012207\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012208Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209
12210static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012211unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012213 if (PyUnicode_READY(self) == -1)
12214 return NULL;
12215 if (PyUnicode_IS_ASCII(self))
12216 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012217 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218}
12219
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012220#define LEFTSTRIP 0
12221#define RIGHTSTRIP 1
12222#define BOTHSTRIP 2
12223
12224/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012225static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012226
12227#define STRIPNAME(i) (stripformat[i]+3)
12228
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012229/* externally visible for str.strip(unicode) */
12230PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012231_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012232{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012233 void *data;
12234 int kind;
12235 Py_ssize_t i, j, len;
12236 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012237 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012239 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12240 return NULL;
12241
12242 kind = PyUnicode_KIND(self);
12243 data = PyUnicode_DATA(self);
12244 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012245 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012246 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12247 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012248 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012249
Benjamin Peterson14339b62009-01-31 16:36:08 +000012250 i = 0;
12251 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012252 while (i < len) {
12253 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12254 if (!BLOOM(sepmask, ch))
12255 break;
12256 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12257 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012258 i++;
12259 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012260 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012261
Benjamin Peterson14339b62009-01-31 16:36:08 +000012262 j = len;
12263 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012264 j--;
12265 while (j >= i) {
12266 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12267 if (!BLOOM(sepmask, ch))
12268 break;
12269 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12270 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012271 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012272 }
12273
Benjamin Peterson29060642009-01-31 22:14:21 +000012274 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012275 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012276
Victor Stinner7931d9a2011-11-04 00:22:48 +010012277 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012278}
12279
12280PyObject*
12281PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12282{
12283 unsigned char *data;
12284 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012285 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012286
Victor Stinnerde636f32011-10-01 03:55:54 +020012287 if (PyUnicode_READY(self) == -1)
12288 return NULL;
12289
Victor Stinner684d5fd2012-05-03 02:32:34 +020012290 length = PyUnicode_GET_LENGTH(self);
12291 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012292
Victor Stinner684d5fd2012-05-03 02:32:34 +020012293 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012294 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012295
Victor Stinnerde636f32011-10-01 03:55:54 +020012296 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012297 PyErr_SetString(PyExc_IndexError, "string index out of range");
12298 return NULL;
12299 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012300 if (start >= length || end < start)
12301 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012302
Victor Stinner684d5fd2012-05-03 02:32:34 +020012303 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012304 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012305 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012306 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012307 }
12308 else {
12309 kind = PyUnicode_KIND(self);
12310 data = PyUnicode_1BYTE_DATA(self);
12311 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012312 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012313 length);
12314 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012315}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012316
12317static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012318do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012319{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320 Py_ssize_t len, i, j;
12321
12322 if (PyUnicode_READY(self) == -1)
12323 return NULL;
12324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012326
Victor Stinnercc7af722013-04-09 22:39:24 +020012327 if (PyUnicode_IS_ASCII(self)) {
12328 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12329
12330 i = 0;
12331 if (striptype != RIGHTSTRIP) {
12332 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012333 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012334 if (!_Py_ascii_whitespace[ch])
12335 break;
12336 i++;
12337 }
12338 }
12339
12340 j = len;
12341 if (striptype != LEFTSTRIP) {
12342 j--;
12343 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012344 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012345 if (!_Py_ascii_whitespace[ch])
12346 break;
12347 j--;
12348 }
12349 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012350 }
12351 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012352 else {
12353 int kind = PyUnicode_KIND(self);
12354 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012355
Victor Stinnercc7af722013-04-09 22:39:24 +020012356 i = 0;
12357 if (striptype != RIGHTSTRIP) {
12358 while (i < len) {
12359 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12360 if (!Py_UNICODE_ISSPACE(ch))
12361 break;
12362 i++;
12363 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012364 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012365
12366 j = len;
12367 if (striptype != LEFTSTRIP) {
12368 j--;
12369 while (j >= i) {
12370 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12371 if (!Py_UNICODE_ISSPACE(ch))
12372 break;
12373 j--;
12374 }
12375 j++;
12376 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012377 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012378
Victor Stinner7931d9a2011-11-04 00:22:48 +010012379 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012380}
12381
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012382
12383static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012384do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012385{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012386 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012387
Serhiy Storchakac6792272013-10-19 21:03:34 +030012388 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012389 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012390
Benjamin Peterson14339b62009-01-31 16:36:08 +000012391 if (sep != NULL && sep != Py_None) {
12392 if (PyUnicode_Check(sep))
12393 return _PyUnicode_XStrip(self, striptype, sep);
12394 else {
12395 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012396 "%s arg must be None or str",
12397 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012398 return NULL;
12399 }
12400 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012401
Benjamin Peterson14339b62009-01-31 16:36:08 +000012402 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012403}
12404
12405
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012406PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012407 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012408\n\
12409Return a copy of the string S with leading and trailing\n\
12410whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012411If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012412
12413static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012414unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012415{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012416 if (PyTuple_GET_SIZE(args) == 0)
12417 return do_strip(self, BOTHSTRIP); /* Common case */
12418 else
12419 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012420}
12421
12422
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012423PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012424 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012425\n\
12426Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012427If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012428
12429static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012430unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012431{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012432 if (PyTuple_GET_SIZE(args) == 0)
12433 return do_strip(self, LEFTSTRIP); /* Common case */
12434 else
12435 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012436}
12437
12438
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012439PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012440 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012441\n\
12442Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012443If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012444
12445static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012446unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012447{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012448 if (PyTuple_GET_SIZE(args) == 0)
12449 return do_strip(self, RIGHTSTRIP); /* Common case */
12450 else
12451 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012452}
12453
12454
Guido van Rossumd57fd912000-03-10 22:53:23 +000012455static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012456unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012457{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012458 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012459 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460
Serhiy Storchaka05997252013-01-26 12:14:02 +020012461 if (len < 1)
12462 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012463
Victor Stinnerc4b49542011-12-11 22:44:26 +010012464 /* no repeat, return original string */
12465 if (len == 1)
12466 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012467
Benjamin Petersonbac79492012-01-14 13:34:47 -050012468 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012469 return NULL;
12470
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012471 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012472 PyErr_SetString(PyExc_OverflowError,
12473 "repeated string is too long");
12474 return NULL;
12475 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012477
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012478 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479 if (!u)
12480 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012481 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012483 if (PyUnicode_GET_LENGTH(str) == 1) {
12484 const int kind = PyUnicode_KIND(str);
12485 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012486 if (kind == PyUnicode_1BYTE_KIND) {
12487 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012488 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012489 }
12490 else if (kind == PyUnicode_2BYTE_KIND) {
12491 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012492 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012493 ucs2[n] = fill_char;
12494 } else {
12495 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12496 assert(kind == PyUnicode_4BYTE_KIND);
12497 for (n = 0; n < len; ++n)
12498 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012499 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012500 }
12501 else {
12502 /* number of characters copied this far */
12503 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012504 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012505 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012506 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012507 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012508 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012509 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012510 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012511 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012512 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012513 }
12514
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012515 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012516 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012517}
12518
Alexander Belopolsky40018472011-02-26 01:02:56 +000012519PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012520PyUnicode_Replace(PyObject *str,
12521 PyObject *substr,
12522 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012523 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012525 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12526 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012527 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012528 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529}
12530
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012531PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012532 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533\n\
12534Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012535old replaced by new. If the optional argument count is\n\
12536given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012537
12538static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012539unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012540{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 PyObject *str1;
12542 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012543 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012544
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012545 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012547 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012548 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012549 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012550}
12551
Alexander Belopolsky40018472011-02-26 01:02:56 +000012552static PyObject *
12553unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012555 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012556 Py_ssize_t isize;
12557 Py_ssize_t osize, squote, dquote, i, o;
12558 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012559 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012561
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012562 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012563 return NULL;
12564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 isize = PyUnicode_GET_LENGTH(unicode);
12566 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012567
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 /* Compute length of output, quote characters, and
12569 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012570 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 max = 127;
12572 squote = dquote = 0;
12573 ikind = PyUnicode_KIND(unicode);
12574 for (i = 0; i < isize; i++) {
12575 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012576 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012577 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012578 case '\'': squote++; break;
12579 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012580 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012581 incr = 2;
12582 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012583 default:
12584 /* Fast-path ASCII */
12585 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012586 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012588 ;
12589 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012590 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012591 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012592 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012594 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012595 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012596 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012597 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012598 if (osize > PY_SSIZE_T_MAX - incr) {
12599 PyErr_SetString(PyExc_OverflowError,
12600 "string is too long to generate repr");
12601 return NULL;
12602 }
12603 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012604 }
12605
12606 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012607 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012608 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012609 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012610 if (dquote)
12611 /* Both squote and dquote present. Use squote,
12612 and escape them */
12613 osize += squote;
12614 else
12615 quote = '"';
12616 }
Victor Stinner55c08782013-04-14 18:45:39 +020012617 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012618
12619 repr = PyUnicode_New(osize, max);
12620 if (repr == NULL)
12621 return NULL;
12622 okind = PyUnicode_KIND(repr);
12623 odata = PyUnicode_DATA(repr);
12624
12625 PyUnicode_WRITE(okind, odata, 0, quote);
12626 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012627 if (unchanged) {
12628 _PyUnicode_FastCopyCharacters(repr, 1,
12629 unicode, 0,
12630 isize);
12631 }
12632 else {
12633 for (i = 0, o = 1; i < isize; i++) {
12634 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012635
Victor Stinner55c08782013-04-14 18:45:39 +020012636 /* Escape quotes and backslashes */
12637 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012638 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012639 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012640 continue;
12641 }
12642
12643 /* Map special whitespace to '\t', \n', '\r' */
12644 if (ch == '\t') {
12645 PyUnicode_WRITE(okind, odata, o++, '\\');
12646 PyUnicode_WRITE(okind, odata, o++, 't');
12647 }
12648 else if (ch == '\n') {
12649 PyUnicode_WRITE(okind, odata, o++, '\\');
12650 PyUnicode_WRITE(okind, odata, o++, 'n');
12651 }
12652 else if (ch == '\r') {
12653 PyUnicode_WRITE(okind, odata, o++, '\\');
12654 PyUnicode_WRITE(okind, odata, o++, 'r');
12655 }
12656
12657 /* Map non-printable US ASCII to '\xhh' */
12658 else if (ch < ' ' || ch == 0x7F) {
12659 PyUnicode_WRITE(okind, odata, o++, '\\');
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
12665 /* Copy ASCII characters as-is */
12666 else if (ch < 0x7F) {
12667 PyUnicode_WRITE(okind, odata, o++, ch);
12668 }
12669
12670 /* Non-ASCII characters */
12671 else {
12672 /* Map Unicode whitespace and control characters
12673 (categories Z* and C* except ASCII space)
12674 */
12675 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12676 PyUnicode_WRITE(okind, odata, o++, '\\');
12677 /* Map 8-bit characters to '\xhh' */
12678 if (ch <= 0xff) {
12679 PyUnicode_WRITE(okind, odata, o++, 'x');
12680 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12681 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12682 }
12683 /* Map 16-bit characters to '\uxxxx' */
12684 else if (ch <= 0xffff) {
12685 PyUnicode_WRITE(okind, odata, o++, 'u');
12686 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12687 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12688 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12689 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12690 }
12691 /* Map 21-bit characters to '\U00xxxxxx' */
12692 else {
12693 PyUnicode_WRITE(okind, odata, o++, 'U');
12694 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12695 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12696 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12697 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12698 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12699 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12700 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12701 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12702 }
12703 }
12704 /* Copy characters as-is */
12705 else {
12706 PyUnicode_WRITE(okind, odata, o++, ch);
12707 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012708 }
12709 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012710 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012712 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012713 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714}
12715
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012716PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012717 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718\n\
12719Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012720such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012721arguments start and end are interpreted as in slice notation.\n\
12722\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012723Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724
12725static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012727{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012728 /* initialize variables to prevent gcc warning */
12729 PyObject *substring = NULL;
12730 Py_ssize_t start = 0;
12731 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012732 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012733
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012734 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012735 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012737 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012739
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012740 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012742 if (result == -2)
12743 return NULL;
12744
Christian Heimes217cfd12007-12-02 14:31:20 +000012745 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012746}
12747
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012748PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012749 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012750\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012751Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012752
12753static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012754unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012756 /* initialize variables to prevent gcc warning */
12757 PyObject *substring = NULL;
12758 Py_ssize_t start = 0;
12759 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012760 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012762 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012763 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012765 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012766 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012767
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012768 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012770 if (result == -2)
12771 return NULL;
12772
Guido van Rossumd57fd912000-03-10 22:53:23 +000012773 if (result < 0) {
12774 PyErr_SetString(PyExc_ValueError, "substring not found");
12775 return NULL;
12776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012777
Christian Heimes217cfd12007-12-02 14:31:20 +000012778 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012779}
12780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012781PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012782 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012784Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012785done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786
12787static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012788unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012789{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012790 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012791 Py_UCS4 fillchar = ' ';
12792
Victor Stinnere9a29352011-10-01 02:14:59 +020012793 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012794 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012795
Benjamin Petersonbac79492012-01-14 13:34:47 -050012796 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797 return NULL;
12798
Victor Stinnerc4b49542011-12-11 22:44:26 +010012799 if (PyUnicode_GET_LENGTH(self) >= width)
12800 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801
Victor Stinnerc4b49542011-12-11 22:44:26 +010012802 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803}
12804
Alexander Belopolsky40018472011-02-26 01:02:56 +000012805PyObject *
12806PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012807{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012808 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012809 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012811 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012812}
12813
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012814PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012815 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816\n\
12817Return a list of the words in S, using sep as the\n\
12818delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012819splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012820whitespace string is a separator and empty strings are\n\
12821removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012822
12823static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012824unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012826 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012828 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012829
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012830 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12831 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012832 return NULL;
12833
12834 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012835 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012836
12837 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012838 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012839
12840 PyErr_Format(PyExc_TypeError,
12841 "must be str or None, not %.100s",
12842 Py_TYPE(substring)->tp_name);
12843 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012844}
12845
Thomas Wouters477c8d52006-05-27 19:21:47 +000012846PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012847PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012848{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012849 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012850 int kind1, kind2;
12851 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012852 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012853
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012854 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012855 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012856
Victor Stinner14f8f022011-10-05 20:58:25 +020012857 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012858 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012859 len1 = PyUnicode_GET_LENGTH(str_obj);
12860 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012861 if (kind1 < kind2 || len1 < len2) {
12862 _Py_INCREF_UNICODE_EMPTY();
12863 if (!unicode_empty)
12864 out = NULL;
12865 else {
12866 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12867 Py_DECREF(unicode_empty);
12868 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012869 return out;
12870 }
12871 buf1 = PyUnicode_DATA(str_obj);
12872 buf2 = PyUnicode_DATA(sep_obj);
12873 if (kind2 != kind1) {
12874 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12875 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012876 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012877 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012879 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012880 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012881 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12882 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12883 else
12884 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012885 break;
12886 case PyUnicode_2BYTE_KIND:
12887 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12888 break;
12889 case PyUnicode_4BYTE_KIND:
12890 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12891 break;
12892 default:
12893 assert(0);
12894 out = 0;
12895 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012896
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012897 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012898 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012899
12900 return out;
12901}
12902
12903
12904PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012905PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012906{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012907 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012908 int kind1, kind2;
12909 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012910 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012911
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012912 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012913 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012914
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012915 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012916 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012917 len1 = PyUnicode_GET_LENGTH(str_obj);
12918 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012919 if (kind1 < kind2 || len1 < len2) {
12920 _Py_INCREF_UNICODE_EMPTY();
12921 if (!unicode_empty)
12922 out = NULL;
12923 else {
12924 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12925 Py_DECREF(unicode_empty);
12926 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012927 return out;
12928 }
12929 buf1 = PyUnicode_DATA(str_obj);
12930 buf2 = PyUnicode_DATA(sep_obj);
12931 if (kind2 != kind1) {
12932 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12933 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012934 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012935 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012936
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012937 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012938 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012939 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12940 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12941 else
12942 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012943 break;
12944 case PyUnicode_2BYTE_KIND:
12945 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12946 break;
12947 case PyUnicode_4BYTE_KIND:
12948 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12949 break;
12950 default:
12951 assert(0);
12952 out = 0;
12953 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012954
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012955 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012956 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012957
12958 return out;
12959}
12960
12961PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012962 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012963\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012964Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012965the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012966found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012967
12968static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012969unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012970{
Victor Stinner9310abb2011-10-05 00:59:23 +020012971 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012972}
12973
12974PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012975 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012976\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012977Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012978the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012979separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012980
12981static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012982unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012983{
Victor Stinner9310abb2011-10-05 00:59:23 +020012984 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012985}
12986
Alexander Belopolsky40018472011-02-26 01:02:56 +000012987PyObject *
12988PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012989{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012990 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012991 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012992
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012993 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012994}
12995
12996PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012997 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012998\n\
12999Return a list of the words in S, using sep as the\n\
13000delimiter string, starting at the end of the string and\n\
13001working to the front. If maxsplit is given, at most maxsplit\n\
13002splits are done. If sep is not specified, any whitespace string\n\
13003is a separator.");
13004
13005static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013006unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013007{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013008 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013009 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013010 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013011
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013012 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
13013 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013014 return NULL;
13015
13016 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000013017 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013018
13019 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020013020 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013021
13022 PyErr_Format(PyExc_TypeError,
13023 "must be str or None, not %.100s",
13024 Py_TYPE(substring)->tp_name);
13025 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013026}
13027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013028PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013029 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013030\n\
13031Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000013032Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013033is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013034
13035static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013036unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013037{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013038 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000013039 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013040
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013041 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
13042 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013043 return NULL;
13044
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013045 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013046}
13047
13048static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013049PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013050{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013051 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013052}
13053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013054PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013055 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013056\n\
13057Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013058and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013059
13060static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013061unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013062{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013063 if (PyUnicode_READY(self) == -1)
13064 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013065 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013066}
13067
Larry Hastings61272b72014-01-07 12:41:53 -080013068/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013069
Larry Hastings31826802013-10-19 00:09:25 -070013070@staticmethod
13071str.maketrans as unicode_maketrans
13072
13073 x: object
13074
13075 y: unicode=NULL
13076
13077 z: unicode=NULL
13078
13079 /
13080
13081Return a translation table usable for str.translate().
13082
13083If there is only one argument, it must be a dictionary mapping Unicode
13084ordinals (integers) or characters to Unicode ordinals, strings or None.
13085Character keys will be then converted to ordinals.
13086If there are two arguments, they must be strings of equal length, and
13087in the resulting dictionary, each character in x will be mapped to the
13088character at the same position in y. If there is a third argument, it
13089must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013090[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013091
Larry Hastings31826802013-10-19 00:09:25 -070013092static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013093unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013094/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013095{
Georg Brandlceee0772007-11-27 23:48:05 +000013096 PyObject *new = NULL, *key, *value;
13097 Py_ssize_t i = 0;
13098 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013099
Georg Brandlceee0772007-11-27 23:48:05 +000013100 new = PyDict_New();
13101 if (!new)
13102 return NULL;
13103 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 int x_kind, y_kind, z_kind;
13105 void *x_data, *y_data, *z_data;
13106
Georg Brandlceee0772007-11-27 23:48:05 +000013107 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013108 if (!PyUnicode_Check(x)) {
13109 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13110 "be a string if there is a second argument");
13111 goto err;
13112 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013113 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013114 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13115 "arguments must have equal length");
13116 goto err;
13117 }
13118 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 x_kind = PyUnicode_KIND(x);
13120 y_kind = PyUnicode_KIND(y);
13121 x_data = PyUnicode_DATA(x);
13122 y_data = PyUnicode_DATA(y);
13123 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13124 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013125 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013126 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013127 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013128 if (!value) {
13129 Py_DECREF(key);
13130 goto err;
13131 }
Georg Brandlceee0772007-11-27 23:48:05 +000013132 res = PyDict_SetItem(new, key, value);
13133 Py_DECREF(key);
13134 Py_DECREF(value);
13135 if (res < 0)
13136 goto err;
13137 }
13138 /* create entries for deleting chars in z */
13139 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013140 z_kind = PyUnicode_KIND(z);
13141 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013142 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013143 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013144 if (!key)
13145 goto err;
13146 res = PyDict_SetItem(new, key, Py_None);
13147 Py_DECREF(key);
13148 if (res < 0)
13149 goto err;
13150 }
13151 }
13152 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013153 int kind;
13154 void *data;
13155
Georg Brandlceee0772007-11-27 23:48:05 +000013156 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013157 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013158 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13159 "to maketrans it must be a dict");
13160 goto err;
13161 }
13162 /* copy entries into the new dict, converting string keys to int keys */
13163 while (PyDict_Next(x, &i, &key, &value)) {
13164 if (PyUnicode_Check(key)) {
13165 /* convert string keys to integer keys */
13166 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013167 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013168 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13169 "table must be of length 1");
13170 goto err;
13171 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013172 kind = PyUnicode_KIND(key);
13173 data = PyUnicode_DATA(key);
13174 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013175 if (!newkey)
13176 goto err;
13177 res = PyDict_SetItem(new, newkey, value);
13178 Py_DECREF(newkey);
13179 if (res < 0)
13180 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013181 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013182 /* just keep integer keys */
13183 if (PyDict_SetItem(new, key, value) < 0)
13184 goto err;
13185 } else {
13186 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13187 "be strings or integers");
13188 goto err;
13189 }
13190 }
13191 }
13192 return new;
13193 err:
13194 Py_DECREF(new);
13195 return NULL;
13196}
13197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013198PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013199 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013200\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013201Return a copy of the string S in which each character has been mapped\n\
13202through the given translation table. The table must implement\n\
13203lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13204mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13205this operation raises LookupError, the character is left untouched.\n\
13206Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207
13208static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013209unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013211 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212}
13213
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013214PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013215 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013217Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218
13219static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013220unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013222 if (PyUnicode_READY(self) == -1)
13223 return NULL;
13224 if (PyUnicode_IS_ASCII(self))
13225 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013226 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227}
13228
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013229PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013230 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013232Pad a numeric string S with zeros on the left, to fill a field\n\
13233of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013234
13235static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013236unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013238 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013239 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013240 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013241 int kind;
13242 void *data;
13243 Py_UCS4 chr;
13244
Martin v. Löwis18e16552006-02-15 17:27:45 +000013245 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013246 return NULL;
13247
Benjamin Petersonbac79492012-01-14 13:34:47 -050013248 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013249 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013250
Victor Stinnerc4b49542011-12-11 22:44:26 +010013251 if (PyUnicode_GET_LENGTH(self) >= width)
13252 return unicode_result_unchanged(self);
13253
13254 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013255
13256 u = pad(self, fill, 0, '0');
13257
Walter Dörwald068325e2002-04-15 13:36:47 +000013258 if (u == NULL)
13259 return NULL;
13260
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013261 kind = PyUnicode_KIND(u);
13262 data = PyUnicode_DATA(u);
13263 chr = PyUnicode_READ(kind, data, fill);
13264
13265 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013266 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013267 PyUnicode_WRITE(kind, data, 0, chr);
13268 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013269 }
13270
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013271 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013272 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013273}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013274
13275#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013276static PyObject *
13277unicode__decimal2ascii(PyObject *self)
13278{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013279 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013280}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013281#endif
13282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013283PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013284 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013285\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013286Return True if S starts with the specified prefix, False otherwise.\n\
13287With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013288With optional end, stop comparing S at that position.\n\
13289prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013290
13291static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013292unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013293 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013294{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013295 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013296 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013297 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013298 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013299 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013300
Jesus Ceaac451502011-04-20 17:09:23 +020013301 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013302 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013303 if (PyTuple_Check(subobj)) {
13304 Py_ssize_t i;
13305 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013306 substring = PyTuple_GET_ITEM(subobj, i);
13307 if (!PyUnicode_Check(substring)) {
13308 PyErr_Format(PyExc_TypeError,
13309 "tuple for startswith must only contain str, "
13310 "not %.100s",
13311 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013312 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013313 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013314 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013315 if (result == -1)
13316 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013317 if (result) {
13318 Py_RETURN_TRUE;
13319 }
13320 }
13321 /* nothing matched */
13322 Py_RETURN_FALSE;
13323 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013324 if (!PyUnicode_Check(subobj)) {
13325 PyErr_Format(PyExc_TypeError,
13326 "startswith first arg must be str or "
13327 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013328 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013329 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013330 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013331 if (result == -1)
13332 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013333 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013334}
13335
13336
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013337PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013338 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013339\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013340Return True if S ends with the specified suffix, False otherwise.\n\
13341With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013342With optional end, stop comparing S at that position.\n\
13343suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013344
13345static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013346unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013347 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013348{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013349 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013350 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013351 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013352 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013353 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013354
Jesus Ceaac451502011-04-20 17:09:23 +020013355 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013356 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013357 if (PyTuple_Check(subobj)) {
13358 Py_ssize_t i;
13359 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013360 substring = PyTuple_GET_ITEM(subobj, i);
13361 if (!PyUnicode_Check(substring)) {
13362 PyErr_Format(PyExc_TypeError,
13363 "tuple for endswith must only contain str, "
13364 "not %.100s",
13365 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013366 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013367 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013368 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013369 if (result == -1)
13370 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013371 if (result) {
13372 Py_RETURN_TRUE;
13373 }
13374 }
13375 Py_RETURN_FALSE;
13376 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013377 if (!PyUnicode_Check(subobj)) {
13378 PyErr_Format(PyExc_TypeError,
13379 "endswith first arg must be str or "
13380 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013382 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013383 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013384 if (result == -1)
13385 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013386 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013387}
13388
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013389static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013390_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013391{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013392 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13393 writer->data = PyUnicode_DATA(writer->buffer);
13394
13395 if (!writer->readonly) {
13396 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013397 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013398 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013399 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013400 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13401 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13402 writer->kind = PyUnicode_WCHAR_KIND;
13403 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13404
Victor Stinner8f674cc2013-04-17 23:02:17 +020013405 /* Copy-on-write mode: set buffer size to 0 so
13406 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13407 * next write. */
13408 writer->size = 0;
13409 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013410}
13411
Victor Stinnerd3f08822012-05-29 12:57:52 +020013412void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013413_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013414{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013415 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013416
13417 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013418 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013419
13420 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13421 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13422 writer->kind = PyUnicode_WCHAR_KIND;
13423 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013424}
13425
Victor Stinnerd3f08822012-05-29 12:57:52 +020013426int
13427_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13428 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013429{
13430 Py_ssize_t newlen;
13431 PyObject *newbuffer;
13432
Victor Stinner2740e462016-09-06 16:58:36 -070013433 assert(maxchar <= MAX_UNICODE);
13434
Victor Stinnerca9381e2015-09-22 00:58:32 +020013435 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013436 assert((maxchar > writer->maxchar && length >= 0)
13437 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013438
Victor Stinner202fdca2012-05-07 12:47:02 +020013439 if (length > PY_SSIZE_T_MAX - writer->pos) {
13440 PyErr_NoMemory();
13441 return -1;
13442 }
13443 newlen = writer->pos + length;
13444
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013445 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013446
Victor Stinnerd3f08822012-05-29 12:57:52 +020013447 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013448 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013449 if (writer->overallocate
13450 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13451 /* overallocate to limit the number of realloc() */
13452 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013453 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013454 if (newlen < writer->min_length)
13455 newlen = writer->min_length;
13456
Victor Stinnerd3f08822012-05-29 12:57:52 +020013457 writer->buffer = PyUnicode_New(newlen, maxchar);
13458 if (writer->buffer == NULL)
13459 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013460 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013461 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013462 if (writer->overallocate
13463 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13464 /* overallocate to limit the number of realloc() */
13465 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013466 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013467 if (newlen < writer->min_length)
13468 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013469
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013470 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013471 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013472 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013473 newbuffer = PyUnicode_New(newlen, maxchar);
13474 if (newbuffer == NULL)
13475 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013476 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13477 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013478 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013479 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013480 }
13481 else {
13482 newbuffer = resize_compact(writer->buffer, newlen);
13483 if (newbuffer == NULL)
13484 return -1;
13485 }
13486 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013487 }
13488 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013489 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013490 newbuffer = PyUnicode_New(writer->size, maxchar);
13491 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013492 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013493 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13494 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013495 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013496 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013497 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013498 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013499
13500#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013501}
13502
Victor Stinnerca9381e2015-09-22 00:58:32 +020013503int
13504_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13505 enum PyUnicode_Kind kind)
13506{
13507 Py_UCS4 maxchar;
13508
13509 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13510 assert(writer->kind < kind);
13511
13512 switch (kind)
13513 {
13514 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13515 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13516 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13517 default:
13518 assert(0 && "invalid kind");
13519 return -1;
13520 }
13521
13522 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13523}
13524
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013525static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013526_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013527{
Victor Stinner2740e462016-09-06 16:58:36 -070013528 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013529 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13530 return -1;
13531 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13532 writer->pos++;
13533 return 0;
13534}
13535
13536int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013537_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13538{
13539 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13540}
13541
13542int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013543_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13544{
13545 Py_UCS4 maxchar;
13546 Py_ssize_t len;
13547
13548 if (PyUnicode_READY(str) == -1)
13549 return -1;
13550 len = PyUnicode_GET_LENGTH(str);
13551 if (len == 0)
13552 return 0;
13553 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13554 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013555 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013556 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013557 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013558 Py_INCREF(str);
13559 writer->buffer = str;
13560 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013561 writer->pos += len;
13562 return 0;
13563 }
13564 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13565 return -1;
13566 }
13567 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13568 str, 0, len);
13569 writer->pos += len;
13570 return 0;
13571}
13572
Victor Stinnere215d962012-10-06 23:03:36 +020013573int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013574_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13575 Py_ssize_t start, Py_ssize_t end)
13576{
13577 Py_UCS4 maxchar;
13578 Py_ssize_t len;
13579
13580 if (PyUnicode_READY(str) == -1)
13581 return -1;
13582
13583 assert(0 <= start);
13584 assert(end <= PyUnicode_GET_LENGTH(str));
13585 assert(start <= end);
13586
13587 if (end == 0)
13588 return 0;
13589
13590 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13591 return _PyUnicodeWriter_WriteStr(writer, str);
13592
13593 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13594 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13595 else
13596 maxchar = writer->maxchar;
13597 len = end - start;
13598
13599 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13600 return -1;
13601
13602 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13603 str, start, len);
13604 writer->pos += len;
13605 return 0;
13606}
13607
13608int
Victor Stinner4a587072013-11-19 12:54:53 +010013609_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13610 const char *ascii, Py_ssize_t len)
13611{
13612 if (len == -1)
13613 len = strlen(ascii);
13614
13615 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13616
13617 if (writer->buffer == NULL && !writer->overallocate) {
13618 PyObject *str;
13619
13620 str = _PyUnicode_FromASCII(ascii, len);
13621 if (str == NULL)
13622 return -1;
13623
13624 writer->readonly = 1;
13625 writer->buffer = str;
13626 _PyUnicodeWriter_Update(writer);
13627 writer->pos += len;
13628 return 0;
13629 }
13630
13631 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13632 return -1;
13633
13634 switch (writer->kind)
13635 {
13636 case PyUnicode_1BYTE_KIND:
13637 {
13638 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13639 Py_UCS1 *data = writer->data;
13640
Christian Heimesf051e432016-09-13 20:22:02 +020013641 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013642 break;
13643 }
13644 case PyUnicode_2BYTE_KIND:
13645 {
13646 _PyUnicode_CONVERT_BYTES(
13647 Py_UCS1, Py_UCS2,
13648 ascii, ascii + len,
13649 (Py_UCS2 *)writer->data + writer->pos);
13650 break;
13651 }
13652 case PyUnicode_4BYTE_KIND:
13653 {
13654 _PyUnicode_CONVERT_BYTES(
13655 Py_UCS1, Py_UCS4,
13656 ascii, ascii + len,
13657 (Py_UCS4 *)writer->data + writer->pos);
13658 break;
13659 }
13660 default:
13661 assert(0);
13662 }
13663
13664 writer->pos += len;
13665 return 0;
13666}
13667
13668int
13669_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13670 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013671{
13672 Py_UCS4 maxchar;
13673
13674 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13675 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13676 return -1;
13677 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13678 writer->pos += len;
13679 return 0;
13680}
13681
Victor Stinnerd3f08822012-05-29 12:57:52 +020013682PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013683_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013684{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013685 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013686
Victor Stinnerd3f08822012-05-29 12:57:52 +020013687 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013688 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013689 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013690 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013691
13692 str = writer->buffer;
13693 writer->buffer = NULL;
13694
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013695 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013696 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13697 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013698 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013699
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013700 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13701 PyObject *str2;
13702 str2 = resize_compact(str, writer->pos);
13703 if (str2 == NULL) {
13704 Py_DECREF(str);
13705 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013706 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013707 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013708 }
13709
Victor Stinner15a0bd32013-07-08 22:29:55 +020013710 assert(_PyUnicode_CheckConsistency(str, 1));
13711 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013712}
13713
Victor Stinnerd3f08822012-05-29 12:57:52 +020013714void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013715_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013716{
13717 Py_CLEAR(writer->buffer);
13718}
13719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013720#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013721
13722PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013723 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013724\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013725Return a formatted version of S, using substitutions from args and kwargs.\n\
13726The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013727
Eric Smith27bbca62010-11-04 17:06:58 +000013728PyDoc_STRVAR(format_map__doc__,
13729 "S.format_map(mapping) -> str\n\
13730\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013731Return a formatted version of S, using substitutions from mapping.\n\
13732The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013733
Eric Smith4a7d76d2008-05-30 18:10:19 +000013734static PyObject *
13735unicode__format__(PyObject* self, PyObject* args)
13736{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013737 PyObject *format_spec;
13738 _PyUnicodeWriter writer;
13739 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013740
13741 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13742 return NULL;
13743
Victor Stinnerd3f08822012-05-29 12:57:52 +020013744 if (PyUnicode_READY(self) == -1)
13745 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013746 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013747 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13748 self, format_spec, 0,
13749 PyUnicode_GET_LENGTH(format_spec));
13750 if (ret == -1) {
13751 _PyUnicodeWriter_Dealloc(&writer);
13752 return NULL;
13753 }
13754 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013755}
13756
Eric Smith8c663262007-08-25 02:26:07 +000013757PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013758 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013759\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013760Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013761
13762static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013763unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013764{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013765 Py_ssize_t size;
13766
13767 /* If it's a compact object, account for base structure +
13768 character data. */
13769 if (PyUnicode_IS_COMPACT_ASCII(v))
13770 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13771 else if (PyUnicode_IS_COMPACT(v))
13772 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013773 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013774 else {
13775 /* If it is a two-block object, account for base object, and
13776 for character block if present. */
13777 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013778 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013779 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013780 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013781 }
13782 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013783 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013784 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013785 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013786 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013787 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013788
13789 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013790}
13791
13792PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013793 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013794
13795static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013796unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013797{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013798 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013799 if (!copy)
13800 return NULL;
13801 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013802}
13803
Guido van Rossumd57fd912000-03-10 22:53:23 +000013804static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013805 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013806 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013807 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13808 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013809 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13810 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013811 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013812 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13813 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13814 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013815 {"expandtabs", (PyCFunction) unicode_expandtabs,
13816 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013817 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013818 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013819 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13820 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13821 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013822 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013823 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13824 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13825 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013826 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013827 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013828 {"splitlines", (PyCFunction) unicode_splitlines,
13829 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013830 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013831 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13832 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13833 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13834 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13835 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13836 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13837 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13838 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13839 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13840 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13841 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13842 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13843 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13844 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013845 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013846 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013847 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013848 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013849 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013850 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013851 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013852 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013853#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013854 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013855 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013856#endif
13857
Benjamin Peterson14339b62009-01-31 16:36:08 +000013858 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013859 {NULL, NULL}
13860};
13861
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013862static PyObject *
13863unicode_mod(PyObject *v, PyObject *w)
13864{
Brian Curtindfc80e32011-08-10 20:28:54 -050013865 if (!PyUnicode_Check(v))
13866 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013867 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013868}
13869
13870static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013871 0, /*nb_add*/
13872 0, /*nb_subtract*/
13873 0, /*nb_multiply*/
13874 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013875};
13876
Guido van Rossumd57fd912000-03-10 22:53:23 +000013877static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013878 (lenfunc) unicode_length, /* sq_length */
13879 PyUnicode_Concat, /* sq_concat */
13880 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13881 (ssizeargfunc) unicode_getitem, /* sq_item */
13882 0, /* sq_slice */
13883 0, /* sq_ass_item */
13884 0, /* sq_ass_slice */
13885 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013886};
13887
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013888static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013889unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013890{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013891 if (PyUnicode_READY(self) == -1)
13892 return NULL;
13893
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013894 if (PyIndex_Check(item)) {
13895 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013896 if (i == -1 && PyErr_Occurred())
13897 return NULL;
13898 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013899 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013900 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013901 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013902 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013903 PyObject *result;
13904 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013905 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013906 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013907
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013908 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013909 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013910 return NULL;
13911 }
13912
13913 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013914 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013915 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013916 slicelength == PyUnicode_GET_LENGTH(self)) {
13917 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013918 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013919 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013920 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013921 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013922 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013923 src_kind = PyUnicode_KIND(self);
13924 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013925 if (!PyUnicode_IS_ASCII(self)) {
13926 kind_limit = kind_maxchar_limit(src_kind);
13927 max_char = 0;
13928 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13929 ch = PyUnicode_READ(src_kind, src_data, cur);
13930 if (ch > max_char) {
13931 max_char = ch;
13932 if (max_char >= kind_limit)
13933 break;
13934 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013935 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013936 }
Victor Stinner55c99112011-10-13 01:17:06 +020013937 else
13938 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013939 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013940 if (result == NULL)
13941 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013942 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013943 dest_data = PyUnicode_DATA(result);
13944
13945 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013946 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13947 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013948 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013949 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013950 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013951 } else {
13952 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13953 return NULL;
13954 }
13955}
13956
13957static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013958 (lenfunc)unicode_length, /* mp_length */
13959 (binaryfunc)unicode_subscript, /* mp_subscript */
13960 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013961};
13962
Guido van Rossumd57fd912000-03-10 22:53:23 +000013963
Guido van Rossumd57fd912000-03-10 22:53:23 +000013964/* Helpers for PyUnicode_Format() */
13965
Victor Stinnera47082312012-10-04 02:19:54 +020013966struct unicode_formatter_t {
13967 PyObject *args;
13968 int args_owned;
13969 Py_ssize_t arglen, argidx;
13970 PyObject *dict;
13971
13972 enum PyUnicode_Kind fmtkind;
13973 Py_ssize_t fmtcnt, fmtpos;
13974 void *fmtdata;
13975 PyObject *fmtstr;
13976
13977 _PyUnicodeWriter writer;
13978};
13979
13980struct unicode_format_arg_t {
13981 Py_UCS4 ch;
13982 int flags;
13983 Py_ssize_t width;
13984 int prec;
13985 int sign;
13986};
13987
Guido van Rossumd57fd912000-03-10 22:53:23 +000013988static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013989unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013990{
Victor Stinnera47082312012-10-04 02:19:54 +020013991 Py_ssize_t argidx = ctx->argidx;
13992
13993 if (argidx < ctx->arglen) {
13994 ctx->argidx++;
13995 if (ctx->arglen < 0)
13996 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013997 else
Victor Stinnera47082312012-10-04 02:19:54 +020013998 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013999 }
14000 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014001 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014002 return NULL;
14003}
14004
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014005/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014006
Victor Stinnera47082312012-10-04 02:19:54 +020014007/* Format a float into the writer if the writer is not NULL, or into *p_output
14008 otherwise.
14009
14010 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014011static int
Victor Stinnera47082312012-10-04 02:19:54 +020014012formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14013 PyObject **p_output,
14014 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014015{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014016 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014017 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014018 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014019 int prec;
14020 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014021
Guido van Rossumd57fd912000-03-10 22:53:23 +000014022 x = PyFloat_AsDouble(v);
14023 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014024 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014025
Victor Stinnera47082312012-10-04 02:19:54 +020014026 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014027 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014028 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014029
Victor Stinnera47082312012-10-04 02:19:54 +020014030 if (arg->flags & F_ALT)
14031 dtoa_flags = Py_DTSF_ALT;
14032 else
14033 dtoa_flags = 0;
14034 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014035 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014036 return -1;
14037 len = strlen(p);
14038 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014039 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014040 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014041 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014042 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014043 }
14044 else
14045 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014046 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014047 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014048}
14049
Victor Stinnerd0880d52012-04-27 23:40:13 +020014050/* formatlong() emulates the format codes d, u, o, x and X, and
14051 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14052 * Python's regular ints.
14053 * Return value: a new PyUnicodeObject*, or NULL if error.
14054 * The output string is of the form
14055 * "-"? ("0x" | "0X")? digit+
14056 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14057 * set in flags. The case of hex digits will be correct,
14058 * There will be at least prec digits, zero-filled on the left if
14059 * necessary to get that many.
14060 * val object to be converted
14061 * flags bitmask of format flags; only F_ALT is looked at
14062 * prec minimum number of digits; 0-fill on left if needed
14063 * type a character in [duoxX]; u acts the same as d
14064 *
14065 * CAUTION: o, x and X conversions on regular ints can never
14066 * produce a '-' sign, but can for Python's unbounded ints.
14067 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014068PyObject *
14069_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014070{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014071 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014072 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014073 Py_ssize_t i;
14074 int sign; /* 1 if '-', else 0 */
14075 int len; /* number of characters */
14076 Py_ssize_t llen;
14077 int numdigits; /* len == numnondigits + numdigits */
14078 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014079
Victor Stinnerd0880d52012-04-27 23:40:13 +020014080 /* Avoid exceeding SSIZE_T_MAX */
14081 if (prec > INT_MAX-3) {
14082 PyErr_SetString(PyExc_OverflowError,
14083 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014084 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014085 }
14086
14087 assert(PyLong_Check(val));
14088
14089 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014090 default:
14091 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014092 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014093 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014094 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014095 /* int and int subclasses should print numerically when a numeric */
14096 /* format code is used (see issue18780) */
14097 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014098 break;
14099 case 'o':
14100 numnondigits = 2;
14101 result = PyNumber_ToBase(val, 8);
14102 break;
14103 case 'x':
14104 case 'X':
14105 numnondigits = 2;
14106 result = PyNumber_ToBase(val, 16);
14107 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014108 }
14109 if (!result)
14110 return NULL;
14111
14112 assert(unicode_modifiable(result));
14113 assert(PyUnicode_IS_READY(result));
14114 assert(PyUnicode_IS_ASCII(result));
14115
14116 /* To modify the string in-place, there can only be one reference. */
14117 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014118 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014119 PyErr_BadInternalCall();
14120 return NULL;
14121 }
14122 buf = PyUnicode_DATA(result);
14123 llen = PyUnicode_GET_LENGTH(result);
14124 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014125 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014126 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014127 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014128 return NULL;
14129 }
14130 len = (int)llen;
14131 sign = buf[0] == '-';
14132 numnondigits += sign;
14133 numdigits = len - numnondigits;
14134 assert(numdigits > 0);
14135
14136 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014137 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014138 (type == 'o' || type == 'x' || type == 'X'))) {
14139 assert(buf[sign] == '0');
14140 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14141 buf[sign+1] == 'o');
14142 numnondigits -= 2;
14143 buf += 2;
14144 len -= 2;
14145 if (sign)
14146 buf[0] = '-';
14147 assert(len == numnondigits + numdigits);
14148 assert(numdigits > 0);
14149 }
14150
14151 /* Fill with leading zeroes to meet minimum width. */
14152 if (prec > numdigits) {
14153 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14154 numnondigits + prec);
14155 char *b1;
14156 if (!r1) {
14157 Py_DECREF(result);
14158 return NULL;
14159 }
14160 b1 = PyBytes_AS_STRING(r1);
14161 for (i = 0; i < numnondigits; ++i)
14162 *b1++ = *buf++;
14163 for (i = 0; i < prec - numdigits; i++)
14164 *b1++ = '0';
14165 for (i = 0; i < numdigits; i++)
14166 *b1++ = *buf++;
14167 *b1 = '\0';
14168 Py_DECREF(result);
14169 result = r1;
14170 buf = PyBytes_AS_STRING(result);
14171 len = numnondigits + prec;
14172 }
14173
14174 /* Fix up case for hex conversions. */
14175 if (type == 'X') {
14176 /* Need to convert all lower case letters to upper case.
14177 and need to convert 0x to 0X (and -0x to -0X). */
14178 for (i = 0; i < len; i++)
14179 if (buf[i] >= 'a' && buf[i] <= 'x')
14180 buf[i] -= 'a'-'A';
14181 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014182 if (!PyUnicode_Check(result)
14183 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014184 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014185 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014186 Py_DECREF(result);
14187 result = unicode;
14188 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014189 else if (len != PyUnicode_GET_LENGTH(result)) {
14190 if (PyUnicode_Resize(&result, len) < 0)
14191 Py_CLEAR(result);
14192 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014193 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014194}
14195
Ethan Furmandf3ed242014-01-05 06:50:30 -080014196/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014197 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014198 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014199 * -1 and raise an exception on error */
14200static int
Victor Stinnera47082312012-10-04 02:19:54 +020014201mainformatlong(PyObject *v,
14202 struct unicode_format_arg_t *arg,
14203 PyObject **p_output,
14204 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014205{
14206 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014207 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014208
14209 if (!PyNumber_Check(v))
14210 goto wrongtype;
14211
Ethan Furman9ab74802014-03-21 06:38:46 -070014212 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014213 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014214 if (type == 'o' || type == 'x' || type == 'X') {
14215 iobj = PyNumber_Index(v);
14216 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014217 if (PyErr_ExceptionMatches(PyExc_TypeError))
14218 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014219 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014220 }
14221 }
14222 else {
14223 iobj = PyNumber_Long(v);
14224 if (iobj == NULL ) {
14225 if (PyErr_ExceptionMatches(PyExc_TypeError))
14226 goto wrongtype;
14227 return -1;
14228 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014229 }
14230 assert(PyLong_Check(iobj));
14231 }
14232 else {
14233 iobj = v;
14234 Py_INCREF(iobj);
14235 }
14236
14237 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014238 && arg->width == -1 && arg->prec == -1
14239 && !(arg->flags & (F_SIGN | F_BLANK))
14240 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014241 {
14242 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014243 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014244 int base;
14245
Victor Stinnera47082312012-10-04 02:19:54 +020014246 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014247 {
14248 default:
14249 assert(0 && "'type' not in [diuoxX]");
14250 case 'd':
14251 case 'i':
14252 case 'u':
14253 base = 10;
14254 break;
14255 case 'o':
14256 base = 8;
14257 break;
14258 case 'x':
14259 case 'X':
14260 base = 16;
14261 break;
14262 }
14263
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014264 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14265 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014266 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014267 }
14268 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014269 return 1;
14270 }
14271
Ethan Furmanb95b5612015-01-23 20:05:18 -080014272 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014273 Py_DECREF(iobj);
14274 if (res == NULL)
14275 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014276 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014277 return 0;
14278
14279wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014280 switch(type)
14281 {
14282 case 'o':
14283 case 'x':
14284 case 'X':
14285 PyErr_Format(PyExc_TypeError,
14286 "%%%c format: an integer is required, "
14287 "not %.200s",
14288 type, Py_TYPE(v)->tp_name);
14289 break;
14290 default:
14291 PyErr_Format(PyExc_TypeError,
14292 "%%%c format: a number is required, "
14293 "not %.200s",
14294 type, Py_TYPE(v)->tp_name);
14295 break;
14296 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014297 return -1;
14298}
14299
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014300static Py_UCS4
14301formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014302{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014303 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014304 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014305 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014306 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014307 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014308 goto onError;
14309 }
14310 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014311 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014312 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014313 /* make sure number is a type of integer */
14314 if (!PyLong_Check(v)) {
14315 iobj = PyNumber_Index(v);
14316 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014317 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014318 }
14319 v = iobj;
14320 Py_DECREF(iobj);
14321 }
14322 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014323 x = PyLong_AsLong(v);
14324 if (x == -1 && PyErr_Occurred())
14325 goto onError;
14326
Victor Stinner8faf8212011-12-08 22:14:11 +010014327 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014328 PyErr_SetString(PyExc_OverflowError,
14329 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014330 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014331 }
14332
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014333 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014334 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014335
Benjamin Peterson29060642009-01-31 22:14:21 +000014336 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014337 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014338 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014339 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014340}
14341
Victor Stinnera47082312012-10-04 02:19:54 +020014342/* Parse options of an argument: flags, width, precision.
14343 Handle also "%(name)" syntax.
14344
14345 Return 0 if the argument has been formatted into arg->str.
14346 Return 1 if the argument has been written into ctx->writer,
14347 Raise an exception and return -1 on error. */
14348static int
14349unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14350 struct unicode_format_arg_t *arg)
14351{
14352#define FORMAT_READ(ctx) \
14353 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14354
14355 PyObject *v;
14356
Victor Stinnera47082312012-10-04 02:19:54 +020014357 if (arg->ch == '(') {
14358 /* Get argument value from a dictionary. Example: "%(name)s". */
14359 Py_ssize_t keystart;
14360 Py_ssize_t keylen;
14361 PyObject *key;
14362 int pcount = 1;
14363
14364 if (ctx->dict == NULL) {
14365 PyErr_SetString(PyExc_TypeError,
14366 "format requires a mapping");
14367 return -1;
14368 }
14369 ++ctx->fmtpos;
14370 --ctx->fmtcnt;
14371 keystart = ctx->fmtpos;
14372 /* Skip over balanced parentheses */
14373 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14374 arg->ch = FORMAT_READ(ctx);
14375 if (arg->ch == ')')
14376 --pcount;
14377 else if (arg->ch == '(')
14378 ++pcount;
14379 ctx->fmtpos++;
14380 }
14381 keylen = ctx->fmtpos - keystart - 1;
14382 if (ctx->fmtcnt < 0 || pcount > 0) {
14383 PyErr_SetString(PyExc_ValueError,
14384 "incomplete format key");
14385 return -1;
14386 }
14387 key = PyUnicode_Substring(ctx->fmtstr,
14388 keystart, keystart + keylen);
14389 if (key == NULL)
14390 return -1;
14391 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014392 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014393 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014394 }
14395 ctx->args = PyObject_GetItem(ctx->dict, key);
14396 Py_DECREF(key);
14397 if (ctx->args == NULL)
14398 return -1;
14399 ctx->args_owned = 1;
14400 ctx->arglen = -1;
14401 ctx->argidx = -2;
14402 }
14403
14404 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014405 while (--ctx->fmtcnt >= 0) {
14406 arg->ch = FORMAT_READ(ctx);
14407 ctx->fmtpos++;
14408 switch (arg->ch) {
14409 case '-': arg->flags |= F_LJUST; continue;
14410 case '+': arg->flags |= F_SIGN; continue;
14411 case ' ': arg->flags |= F_BLANK; continue;
14412 case '#': arg->flags |= F_ALT; continue;
14413 case '0': arg->flags |= F_ZERO; continue;
14414 }
14415 break;
14416 }
14417
14418 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014419 if (arg->ch == '*') {
14420 v = unicode_format_getnextarg(ctx);
14421 if (v == NULL)
14422 return -1;
14423 if (!PyLong_Check(v)) {
14424 PyErr_SetString(PyExc_TypeError,
14425 "* wants int");
14426 return -1;
14427 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014428 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014429 if (arg->width == -1 && PyErr_Occurred())
14430 return -1;
14431 if (arg->width < 0) {
14432 arg->flags |= F_LJUST;
14433 arg->width = -arg->width;
14434 }
14435 if (--ctx->fmtcnt >= 0) {
14436 arg->ch = FORMAT_READ(ctx);
14437 ctx->fmtpos++;
14438 }
14439 }
14440 else if (arg->ch >= '0' && arg->ch <= '9') {
14441 arg->width = arg->ch - '0';
14442 while (--ctx->fmtcnt >= 0) {
14443 arg->ch = FORMAT_READ(ctx);
14444 ctx->fmtpos++;
14445 if (arg->ch < '0' || arg->ch > '9')
14446 break;
14447 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14448 mixing signed and unsigned comparison. Since arg->ch is between
14449 '0' and '9', casting to int is safe. */
14450 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14451 PyErr_SetString(PyExc_ValueError,
14452 "width too big");
14453 return -1;
14454 }
14455 arg->width = arg->width*10 + (arg->ch - '0');
14456 }
14457 }
14458
14459 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014460 if (arg->ch == '.') {
14461 arg->prec = 0;
14462 if (--ctx->fmtcnt >= 0) {
14463 arg->ch = FORMAT_READ(ctx);
14464 ctx->fmtpos++;
14465 }
14466 if (arg->ch == '*') {
14467 v = unicode_format_getnextarg(ctx);
14468 if (v == NULL)
14469 return -1;
14470 if (!PyLong_Check(v)) {
14471 PyErr_SetString(PyExc_TypeError,
14472 "* wants int");
14473 return -1;
14474 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014475 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014476 if (arg->prec == -1 && PyErr_Occurred())
14477 return -1;
14478 if (arg->prec < 0)
14479 arg->prec = 0;
14480 if (--ctx->fmtcnt >= 0) {
14481 arg->ch = FORMAT_READ(ctx);
14482 ctx->fmtpos++;
14483 }
14484 }
14485 else if (arg->ch >= '0' && arg->ch <= '9') {
14486 arg->prec = arg->ch - '0';
14487 while (--ctx->fmtcnt >= 0) {
14488 arg->ch = FORMAT_READ(ctx);
14489 ctx->fmtpos++;
14490 if (arg->ch < '0' || arg->ch > '9')
14491 break;
14492 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14493 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014494 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014495 return -1;
14496 }
14497 arg->prec = arg->prec*10 + (arg->ch - '0');
14498 }
14499 }
14500 }
14501
14502 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14503 if (ctx->fmtcnt >= 0) {
14504 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14505 if (--ctx->fmtcnt >= 0) {
14506 arg->ch = FORMAT_READ(ctx);
14507 ctx->fmtpos++;
14508 }
14509 }
14510 }
14511 if (ctx->fmtcnt < 0) {
14512 PyErr_SetString(PyExc_ValueError,
14513 "incomplete format");
14514 return -1;
14515 }
14516 return 0;
14517
14518#undef FORMAT_READ
14519}
14520
14521/* Format one argument. Supported conversion specifiers:
14522
14523 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014524 - "i", "d", "u": int or float
14525 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014526 - "e", "E", "f", "F", "g", "G": float
14527 - "c": int or str (1 character)
14528
Victor Stinner8dbd4212012-12-04 09:30:24 +010014529 When possible, the output is written directly into the Unicode writer
14530 (ctx->writer). A string is created when padding is required.
14531
Victor Stinnera47082312012-10-04 02:19:54 +020014532 Return 0 if the argument has been formatted into *p_str,
14533 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014534 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014535static int
14536unicode_format_arg_format(struct unicode_formatter_t *ctx,
14537 struct unicode_format_arg_t *arg,
14538 PyObject **p_str)
14539{
14540 PyObject *v;
14541 _PyUnicodeWriter *writer = &ctx->writer;
14542
14543 if (ctx->fmtcnt == 0)
14544 ctx->writer.overallocate = 0;
14545
14546 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014547 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014548 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014549 return 1;
14550 }
14551
14552 v = unicode_format_getnextarg(ctx);
14553 if (v == NULL)
14554 return -1;
14555
Victor Stinnera47082312012-10-04 02:19:54 +020014556
14557 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014558 case 's':
14559 case 'r':
14560 case 'a':
14561 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14562 /* Fast path */
14563 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14564 return -1;
14565 return 1;
14566 }
14567
14568 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14569 *p_str = v;
14570 Py_INCREF(*p_str);
14571 }
14572 else {
14573 if (arg->ch == 's')
14574 *p_str = PyObject_Str(v);
14575 else if (arg->ch == 'r')
14576 *p_str = PyObject_Repr(v);
14577 else
14578 *p_str = PyObject_ASCII(v);
14579 }
14580 break;
14581
14582 case 'i':
14583 case 'd':
14584 case 'u':
14585 case 'o':
14586 case 'x':
14587 case 'X':
14588 {
14589 int ret = mainformatlong(v, arg, p_str, writer);
14590 if (ret != 0)
14591 return ret;
14592 arg->sign = 1;
14593 break;
14594 }
14595
14596 case 'e':
14597 case 'E':
14598 case 'f':
14599 case 'F':
14600 case 'g':
14601 case 'G':
14602 if (arg->width == -1 && arg->prec == -1
14603 && !(arg->flags & (F_SIGN | F_BLANK)))
14604 {
14605 /* Fast path */
14606 if (formatfloat(v, arg, NULL, writer) == -1)
14607 return -1;
14608 return 1;
14609 }
14610
14611 arg->sign = 1;
14612 if (formatfloat(v, arg, p_str, NULL) == -1)
14613 return -1;
14614 break;
14615
14616 case 'c':
14617 {
14618 Py_UCS4 ch = formatchar(v);
14619 if (ch == (Py_UCS4) -1)
14620 return -1;
14621 if (arg->width == -1 && arg->prec == -1) {
14622 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014623 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014624 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014625 return 1;
14626 }
14627 *p_str = PyUnicode_FromOrdinal(ch);
14628 break;
14629 }
14630
14631 default:
14632 PyErr_Format(PyExc_ValueError,
14633 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014634 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014635 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14636 (int)arg->ch,
14637 ctx->fmtpos - 1);
14638 return -1;
14639 }
14640 if (*p_str == NULL)
14641 return -1;
14642 assert (PyUnicode_Check(*p_str));
14643 return 0;
14644}
14645
14646static int
14647unicode_format_arg_output(struct unicode_formatter_t *ctx,
14648 struct unicode_format_arg_t *arg,
14649 PyObject *str)
14650{
14651 Py_ssize_t len;
14652 enum PyUnicode_Kind kind;
14653 void *pbuf;
14654 Py_ssize_t pindex;
14655 Py_UCS4 signchar;
14656 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014657 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014658 Py_ssize_t sublen;
14659 _PyUnicodeWriter *writer = &ctx->writer;
14660 Py_UCS4 fill;
14661
14662 fill = ' ';
14663 if (arg->sign && arg->flags & F_ZERO)
14664 fill = '0';
14665
14666 if (PyUnicode_READY(str) == -1)
14667 return -1;
14668
14669 len = PyUnicode_GET_LENGTH(str);
14670 if ((arg->width == -1 || arg->width <= len)
14671 && (arg->prec == -1 || arg->prec >= len)
14672 && !(arg->flags & (F_SIGN | F_BLANK)))
14673 {
14674 /* Fast path */
14675 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14676 return -1;
14677 return 0;
14678 }
14679
14680 /* Truncate the string for "s", "r" and "a" formats
14681 if the precision is set */
14682 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14683 if (arg->prec >= 0 && len > arg->prec)
14684 len = arg->prec;
14685 }
14686
14687 /* Adjust sign and width */
14688 kind = PyUnicode_KIND(str);
14689 pbuf = PyUnicode_DATA(str);
14690 pindex = 0;
14691 signchar = '\0';
14692 if (arg->sign) {
14693 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14694 if (ch == '-' || ch == '+') {
14695 signchar = ch;
14696 len--;
14697 pindex++;
14698 }
14699 else if (arg->flags & F_SIGN)
14700 signchar = '+';
14701 else if (arg->flags & F_BLANK)
14702 signchar = ' ';
14703 else
14704 arg->sign = 0;
14705 }
14706 if (arg->width < len)
14707 arg->width = len;
14708
14709 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014710 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014711 if (!(arg->flags & F_LJUST)) {
14712 if (arg->sign) {
14713 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014714 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014715 }
14716 else {
14717 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014718 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014719 }
14720 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014721 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14722 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014723 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014724 }
14725
Victor Stinnera47082312012-10-04 02:19:54 +020014726 buflen = arg->width;
14727 if (arg->sign && len == arg->width)
14728 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014729 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014730 return -1;
14731
14732 /* Write the sign if needed */
14733 if (arg->sign) {
14734 if (fill != ' ') {
14735 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14736 writer->pos += 1;
14737 }
14738 if (arg->width > len)
14739 arg->width--;
14740 }
14741
14742 /* Write the numeric prefix for "x", "X" and "o" formats
14743 if the alternate form is used.
14744 For example, write "0x" for the "%#x" format. */
14745 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14746 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14747 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14748 if (fill != ' ') {
14749 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14750 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14751 writer->pos += 2;
14752 pindex += 2;
14753 }
14754 arg->width -= 2;
14755 if (arg->width < 0)
14756 arg->width = 0;
14757 len -= 2;
14758 }
14759
14760 /* Pad left with the fill character if needed */
14761 if (arg->width > len && !(arg->flags & F_LJUST)) {
14762 sublen = arg->width - len;
14763 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14764 writer->pos += sublen;
14765 arg->width = len;
14766 }
14767
14768 /* If padding with spaces: write sign if needed and/or numeric prefix if
14769 the alternate form is used */
14770 if (fill == ' ') {
14771 if (arg->sign) {
14772 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14773 writer->pos += 1;
14774 }
14775 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14776 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14777 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14778 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14779 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14780 writer->pos += 2;
14781 pindex += 2;
14782 }
14783 }
14784
14785 /* Write characters */
14786 if (len) {
14787 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14788 str, pindex, len);
14789 writer->pos += len;
14790 }
14791
14792 /* Pad right with the fill character if needed */
14793 if (arg->width > len) {
14794 sublen = arg->width - len;
14795 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14796 writer->pos += sublen;
14797 }
14798 return 0;
14799}
14800
14801/* Helper of PyUnicode_Format(): format one arg.
14802 Return 0 on success, raise an exception and return -1 on error. */
14803static int
14804unicode_format_arg(struct unicode_formatter_t *ctx)
14805{
14806 struct unicode_format_arg_t arg;
14807 PyObject *str;
14808 int ret;
14809
Victor Stinner8dbd4212012-12-04 09:30:24 +010014810 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14811 arg.flags = 0;
14812 arg.width = -1;
14813 arg.prec = -1;
14814 arg.sign = 0;
14815 str = NULL;
14816
Victor Stinnera47082312012-10-04 02:19:54 +020014817 ret = unicode_format_arg_parse(ctx, &arg);
14818 if (ret == -1)
14819 return -1;
14820
14821 ret = unicode_format_arg_format(ctx, &arg, &str);
14822 if (ret == -1)
14823 return -1;
14824
14825 if (ret != 1) {
14826 ret = unicode_format_arg_output(ctx, &arg, str);
14827 Py_DECREF(str);
14828 if (ret == -1)
14829 return -1;
14830 }
14831
14832 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14833 PyErr_SetString(PyExc_TypeError,
14834 "not all arguments converted during string formatting");
14835 return -1;
14836 }
14837 return 0;
14838}
14839
Alexander Belopolsky40018472011-02-26 01:02:56 +000014840PyObject *
14841PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014842{
Victor Stinnera47082312012-10-04 02:19:54 +020014843 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014844
Guido van Rossumd57fd912000-03-10 22:53:23 +000014845 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014846 PyErr_BadInternalCall();
14847 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014848 }
Victor Stinnera47082312012-10-04 02:19:54 +020014849
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014850 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014851 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014852
14853 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014854 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14855 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14856 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14857 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014858
Victor Stinner8f674cc2013-04-17 23:02:17 +020014859 _PyUnicodeWriter_Init(&ctx.writer);
14860 ctx.writer.min_length = ctx.fmtcnt + 100;
14861 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014862
Guido van Rossumd57fd912000-03-10 22:53:23 +000014863 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014864 ctx.arglen = PyTuple_Size(args);
14865 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014866 }
14867 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014868 ctx.arglen = -1;
14869 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014870 }
Victor Stinnera47082312012-10-04 02:19:54 +020014871 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014872 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014873 ctx.dict = args;
14874 else
14875 ctx.dict = NULL;
14876 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014877
Victor Stinnera47082312012-10-04 02:19:54 +020014878 while (--ctx.fmtcnt >= 0) {
14879 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014880 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014881
14882 nonfmtpos = ctx.fmtpos++;
14883 while (ctx.fmtcnt >= 0 &&
14884 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14885 ctx.fmtpos++;
14886 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014887 }
Victor Stinnera47082312012-10-04 02:19:54 +020014888 if (ctx.fmtcnt < 0) {
14889 ctx.fmtpos--;
14890 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014891 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014892
Victor Stinnercfc4c132013-04-03 01:48:39 +020014893 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14894 nonfmtpos, ctx.fmtpos) < 0)
14895 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014896 }
14897 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014898 ctx.fmtpos++;
14899 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014900 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014901 }
14902 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014903
Victor Stinnera47082312012-10-04 02:19:54 +020014904 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014905 PyErr_SetString(PyExc_TypeError,
14906 "not all arguments converted during string formatting");
14907 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014908 }
14909
Victor Stinnera47082312012-10-04 02:19:54 +020014910 if (ctx.args_owned) {
14911 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014912 }
Victor Stinnera47082312012-10-04 02:19:54 +020014913 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014914
Benjamin Peterson29060642009-01-31 22:14:21 +000014915 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014916 _PyUnicodeWriter_Dealloc(&ctx.writer);
14917 if (ctx.args_owned) {
14918 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014919 }
14920 return NULL;
14921}
14922
Jeremy Hylton938ace62002-07-17 16:30:39 +000014923static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014924unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14925
Tim Peters6d6c1a32001-08-02 04:15:00 +000014926static PyObject *
14927unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14928{
Benjamin Peterson29060642009-01-31 22:14:21 +000014929 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014930 static char *kwlist[] = {"object", "encoding", "errors", 0};
14931 char *encoding = NULL;
14932 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014933
Benjamin Peterson14339b62009-01-31 16:36:08 +000014934 if (type != &PyUnicode_Type)
14935 return unicode_subtype_new(type, args, kwds);
14936 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014937 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014938 return NULL;
14939 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014940 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014941 if (encoding == NULL && errors == NULL)
14942 return PyObject_Str(x);
14943 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014944 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014945}
14946
Guido van Rossume023fe02001-08-30 03:12:59 +000014947static PyObject *
14948unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14949{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014950 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014951 Py_ssize_t length, char_size;
14952 int share_wstr, share_utf8;
14953 unsigned int kind;
14954 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014955
Benjamin Peterson14339b62009-01-31 16:36:08 +000014956 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014957
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014958 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014959 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014960 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014961 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014962 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014963 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014964 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014965 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014966
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014967 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014968 if (self == NULL) {
14969 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014970 return NULL;
14971 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014972 kind = PyUnicode_KIND(unicode);
14973 length = PyUnicode_GET_LENGTH(unicode);
14974
14975 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014976#ifdef Py_DEBUG
14977 _PyUnicode_HASH(self) = -1;
14978#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014979 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014980#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014981 _PyUnicode_STATE(self).interned = 0;
14982 _PyUnicode_STATE(self).kind = kind;
14983 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014984 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014985 _PyUnicode_STATE(self).ready = 1;
14986 _PyUnicode_WSTR(self) = NULL;
14987 _PyUnicode_UTF8_LENGTH(self) = 0;
14988 _PyUnicode_UTF8(self) = NULL;
14989 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014990 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014991
14992 share_utf8 = 0;
14993 share_wstr = 0;
14994 if (kind == PyUnicode_1BYTE_KIND) {
14995 char_size = 1;
14996 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14997 share_utf8 = 1;
14998 }
14999 else if (kind == PyUnicode_2BYTE_KIND) {
15000 char_size = 2;
15001 if (sizeof(wchar_t) == 2)
15002 share_wstr = 1;
15003 }
15004 else {
15005 assert(kind == PyUnicode_4BYTE_KIND);
15006 char_size = 4;
15007 if (sizeof(wchar_t) == 4)
15008 share_wstr = 1;
15009 }
15010
15011 /* Ensure we won't overflow the length. */
15012 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15013 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015014 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015015 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015016 data = PyObject_MALLOC((length + 1) * char_size);
15017 if (data == NULL) {
15018 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015019 goto onError;
15020 }
15021
Victor Stinnerc3c74152011-10-02 20:39:55 +020015022 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015023 if (share_utf8) {
15024 _PyUnicode_UTF8_LENGTH(self) = length;
15025 _PyUnicode_UTF8(self) = data;
15026 }
15027 if (share_wstr) {
15028 _PyUnicode_WSTR_LENGTH(self) = length;
15029 _PyUnicode_WSTR(self) = (wchar_t *)data;
15030 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015031
Christian Heimesf051e432016-09-13 20:22:02 +020015032 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015033 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015034 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015035#ifdef Py_DEBUG
15036 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15037#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015038 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015039 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015040
15041onError:
15042 Py_DECREF(unicode);
15043 Py_DECREF(self);
15044 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015045}
15046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015047PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015048"str(object='') -> str\n\
15049str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015050\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015051Create a new string object from the given object. If encoding or\n\
15052errors is specified, then the object must expose a data buffer\n\
15053that will be decoded using the given encoding and error handler.\n\
15054Otherwise, returns the result of object.__str__() (if defined)\n\
15055or repr(object).\n\
15056encoding defaults to sys.getdefaultencoding().\n\
15057errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015058
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015059static PyObject *unicode_iter(PyObject *seq);
15060
Guido van Rossumd57fd912000-03-10 22:53:23 +000015061PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015062 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015063 "str", /* tp_name */
15064 sizeof(PyUnicodeObject), /* tp_size */
15065 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015066 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015067 (destructor)unicode_dealloc, /* tp_dealloc */
15068 0, /* tp_print */
15069 0, /* tp_getattr */
15070 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015071 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015072 unicode_repr, /* tp_repr */
15073 &unicode_as_number, /* tp_as_number */
15074 &unicode_as_sequence, /* tp_as_sequence */
15075 &unicode_as_mapping, /* tp_as_mapping */
15076 (hashfunc) unicode_hash, /* tp_hash*/
15077 0, /* tp_call*/
15078 (reprfunc) unicode_str, /* tp_str */
15079 PyObject_GenericGetAttr, /* tp_getattro */
15080 0, /* tp_setattro */
15081 0, /* tp_as_buffer */
15082 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015083 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015084 unicode_doc, /* tp_doc */
15085 0, /* tp_traverse */
15086 0, /* tp_clear */
15087 PyUnicode_RichCompare, /* tp_richcompare */
15088 0, /* tp_weaklistoffset */
15089 unicode_iter, /* tp_iter */
15090 0, /* tp_iternext */
15091 unicode_methods, /* tp_methods */
15092 0, /* tp_members */
15093 0, /* tp_getset */
15094 &PyBaseObject_Type, /* tp_base */
15095 0, /* tp_dict */
15096 0, /* tp_descr_get */
15097 0, /* tp_descr_set */
15098 0, /* tp_dictoffset */
15099 0, /* tp_init */
15100 0, /* tp_alloc */
15101 unicode_new, /* tp_new */
15102 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015103};
15104
15105/* Initialize the Unicode implementation */
15106
Victor Stinner3a50e702011-10-18 21:21:00 +020015107int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015108{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015109 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015110 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015111 0x000A, /* LINE FEED */
15112 0x000D, /* CARRIAGE RETURN */
15113 0x001C, /* FILE SEPARATOR */
15114 0x001D, /* GROUP SEPARATOR */
15115 0x001E, /* RECORD SEPARATOR */
15116 0x0085, /* NEXT LINE */
15117 0x2028, /* LINE SEPARATOR */
15118 0x2029, /* PARAGRAPH SEPARATOR */
15119 };
15120
Fred Drakee4315f52000-05-09 19:53:39 +000015121 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015122 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015123 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015124 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015125 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015126
Guido van Rossumcacfc072002-05-24 19:01:59 +000015127 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015128 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015129
15130 /* initialize the linebreak bloom filter */
15131 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015132 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015133 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015134
Christian Heimes26532f72013-07-20 14:57:16 +020015135 if (PyType_Ready(&EncodingMapType) < 0)
15136 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015137
Benjamin Petersonc4311282012-10-30 23:21:10 -040015138 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15139 Py_FatalError("Can't initialize field name iterator type");
15140
15141 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15142 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015143
Victor Stinner3a50e702011-10-18 21:21:00 +020015144 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015145}
15146
15147/* Finalize the Unicode implementation */
15148
Christian Heimesa156e092008-02-16 07:38:31 +000015149int
15150PyUnicode_ClearFreeList(void)
15151{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015152 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015153}
15154
Guido van Rossumd57fd912000-03-10 22:53:23 +000015155void
Thomas Wouters78890102000-07-22 19:25:51 +000015156_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015157{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015158 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015159
Serhiy Storchaka05997252013-01-26 12:14:02 +020015160 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015161
Serhiy Storchaka05997252013-01-26 12:14:02 +020015162 for (i = 0; i < 256; i++)
15163 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015164 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015165 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015166}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015167
Walter Dörwald16807132007-05-25 13:52:07 +000015168void
15169PyUnicode_InternInPlace(PyObject **p)
15170{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015171 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015172 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015173#ifdef Py_DEBUG
15174 assert(s != NULL);
15175 assert(_PyUnicode_CHECK(s));
15176#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015177 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015178 return;
15179#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015180 /* If it's a subclass, we don't really know what putting
15181 it in the interned dict might do. */
15182 if (!PyUnicode_CheckExact(s))
15183 return;
15184 if (PyUnicode_CHECK_INTERNED(s))
15185 return;
15186 if (interned == NULL) {
15187 interned = PyDict_New();
15188 if (interned == NULL) {
15189 PyErr_Clear(); /* Don't leave an exception */
15190 return;
15191 }
15192 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015193 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015194 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015195 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015196 if (t == NULL) {
15197 PyErr_Clear();
15198 return;
15199 }
15200 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015201 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015202 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015203 return;
15204 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015205 /* The two references in interned are not counted by refcnt.
15206 The deallocator will take care of this */
15207 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015208 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015209}
15210
15211void
15212PyUnicode_InternImmortal(PyObject **p)
15213{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015214 PyUnicode_InternInPlace(p);
15215 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015216 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015217 Py_INCREF(*p);
15218 }
Walter Dörwald16807132007-05-25 13:52:07 +000015219}
15220
15221PyObject *
15222PyUnicode_InternFromString(const char *cp)
15223{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015224 PyObject *s = PyUnicode_FromString(cp);
15225 if (s == NULL)
15226 return NULL;
15227 PyUnicode_InternInPlace(&s);
15228 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015229}
15230
Alexander Belopolsky40018472011-02-26 01:02:56 +000015231void
15232_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015233{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015234 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015235 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015236 Py_ssize_t i, n;
15237 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015238
Benjamin Peterson14339b62009-01-31 16:36:08 +000015239 if (interned == NULL || !PyDict_Check(interned))
15240 return;
15241 keys = PyDict_Keys(interned);
15242 if (keys == NULL || !PyList_Check(keys)) {
15243 PyErr_Clear();
15244 return;
15245 }
Walter Dörwald16807132007-05-25 13:52:07 +000015246
Benjamin Peterson14339b62009-01-31 16:36:08 +000015247 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15248 detector, interned unicode strings are not forcibly deallocated;
15249 rather, we give them their stolen references back, and then clear
15250 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015251
Benjamin Peterson14339b62009-01-31 16:36:08 +000015252 n = PyList_GET_SIZE(keys);
15253 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015254 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015255 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015256 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015257 if (PyUnicode_READY(s) == -1) {
15258 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015259 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015260 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015261 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015262 case SSTATE_NOT_INTERNED:
15263 /* XXX Shouldn't happen */
15264 break;
15265 case SSTATE_INTERNED_IMMORTAL:
15266 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015267 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015268 break;
15269 case SSTATE_INTERNED_MORTAL:
15270 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015271 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015272 break;
15273 default:
15274 Py_FatalError("Inconsistent interned string state.");
15275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015276 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015277 }
15278 fprintf(stderr, "total size of all interned strings: "
15279 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15280 "mortal/immortal\n", mortal_size, immortal_size);
15281 Py_DECREF(keys);
15282 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015283 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015284}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015285
15286
15287/********************* Unicode Iterator **************************/
15288
15289typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015290 PyObject_HEAD
15291 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015292 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015293} unicodeiterobject;
15294
15295static void
15296unicodeiter_dealloc(unicodeiterobject *it)
15297{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015298 _PyObject_GC_UNTRACK(it);
15299 Py_XDECREF(it->it_seq);
15300 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015301}
15302
15303static int
15304unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15305{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015306 Py_VISIT(it->it_seq);
15307 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015308}
15309
15310static PyObject *
15311unicodeiter_next(unicodeiterobject *it)
15312{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015313 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015314
Benjamin Peterson14339b62009-01-31 16:36:08 +000015315 assert(it != NULL);
15316 seq = it->it_seq;
15317 if (seq == NULL)
15318 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015319 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015320
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015321 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15322 int kind = PyUnicode_KIND(seq);
15323 void *data = PyUnicode_DATA(seq);
15324 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15325 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015326 if (item != NULL)
15327 ++it->it_index;
15328 return item;
15329 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015330
Benjamin Peterson14339b62009-01-31 16:36:08 +000015331 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015332 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015333 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015334}
15335
15336static PyObject *
15337unicodeiter_len(unicodeiterobject *it)
15338{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015339 Py_ssize_t len = 0;
15340 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015341 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015342 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015343}
15344
15345PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15346
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015347static PyObject *
15348unicodeiter_reduce(unicodeiterobject *it)
15349{
15350 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015351 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015352 it->it_seq, it->it_index);
15353 } else {
15354 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15355 if (u == NULL)
15356 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015357 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015358 }
15359}
15360
15361PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15362
15363static PyObject *
15364unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15365{
15366 Py_ssize_t index = PyLong_AsSsize_t(state);
15367 if (index == -1 && PyErr_Occurred())
15368 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015369 if (it->it_seq != NULL) {
15370 if (index < 0)
15371 index = 0;
15372 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15373 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15374 it->it_index = index;
15375 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015376 Py_RETURN_NONE;
15377}
15378
15379PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15380
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015381static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015382 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015383 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015384 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15385 reduce_doc},
15386 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15387 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015388 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015389};
15390
15391PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015392 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15393 "str_iterator", /* tp_name */
15394 sizeof(unicodeiterobject), /* tp_basicsize */
15395 0, /* tp_itemsize */
15396 /* methods */
15397 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15398 0, /* tp_print */
15399 0, /* tp_getattr */
15400 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015401 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015402 0, /* tp_repr */
15403 0, /* tp_as_number */
15404 0, /* tp_as_sequence */
15405 0, /* tp_as_mapping */
15406 0, /* tp_hash */
15407 0, /* tp_call */
15408 0, /* tp_str */
15409 PyObject_GenericGetAttr, /* tp_getattro */
15410 0, /* tp_setattro */
15411 0, /* tp_as_buffer */
15412 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15413 0, /* tp_doc */
15414 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15415 0, /* tp_clear */
15416 0, /* tp_richcompare */
15417 0, /* tp_weaklistoffset */
15418 PyObject_SelfIter, /* tp_iter */
15419 (iternextfunc)unicodeiter_next, /* tp_iternext */
15420 unicodeiter_methods, /* tp_methods */
15421 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015422};
15423
15424static PyObject *
15425unicode_iter(PyObject *seq)
15426{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015427 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015428
Benjamin Peterson14339b62009-01-31 16:36:08 +000015429 if (!PyUnicode_Check(seq)) {
15430 PyErr_BadInternalCall();
15431 return NULL;
15432 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015433 if (PyUnicode_READY(seq) == -1)
15434 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015435 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15436 if (it == NULL)
15437 return NULL;
15438 it->it_index = 0;
15439 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015440 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015441 _PyObject_GC_TRACK(it);
15442 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015443}
15444
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015445
15446size_t
15447Py_UNICODE_strlen(const Py_UNICODE *u)
15448{
15449 int res = 0;
15450 while(*u++)
15451 res++;
15452 return res;
15453}
15454
15455Py_UNICODE*
15456Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15457{
15458 Py_UNICODE *u = s1;
15459 while ((*u++ = *s2++));
15460 return s1;
15461}
15462
15463Py_UNICODE*
15464Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15465{
15466 Py_UNICODE *u = s1;
15467 while ((*u++ = *s2++))
15468 if (n-- == 0)
15469 break;
15470 return s1;
15471}
15472
15473Py_UNICODE*
15474Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15475{
15476 Py_UNICODE *u1 = s1;
15477 u1 += Py_UNICODE_strlen(u1);
15478 Py_UNICODE_strcpy(u1, s2);
15479 return s1;
15480}
15481
15482int
15483Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15484{
15485 while (*s1 && *s2 && *s1 == *s2)
15486 s1++, s2++;
15487 if (*s1 && *s2)
15488 return (*s1 < *s2) ? -1 : +1;
15489 if (*s1)
15490 return 1;
15491 if (*s2)
15492 return -1;
15493 return 0;
15494}
15495
15496int
15497Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15498{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015499 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015500 for (; n != 0; n--) {
15501 u1 = *s1;
15502 u2 = *s2;
15503 if (u1 != u2)
15504 return (u1 < u2) ? -1 : +1;
15505 if (u1 == '\0')
15506 return 0;
15507 s1++;
15508 s2++;
15509 }
15510 return 0;
15511}
15512
15513Py_UNICODE*
15514Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15515{
15516 const Py_UNICODE *p;
15517 for (p = s; *p; p++)
15518 if (*p == c)
15519 return (Py_UNICODE*)p;
15520 return NULL;
15521}
15522
15523Py_UNICODE*
15524Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15525{
15526 const Py_UNICODE *p;
15527 p = s + Py_UNICODE_strlen(s);
15528 while (p != s) {
15529 p--;
15530 if (*p == c)
15531 return (Py_UNICODE*)p;
15532 }
15533 return NULL;
15534}
Victor Stinner331ea922010-08-10 16:37:20 +000015535
Victor Stinner71133ff2010-09-01 23:43:53 +000015536Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015537PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015538{
Victor Stinner577db2c2011-10-11 22:12:48 +020015539 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015540 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015542 if (!PyUnicode_Check(unicode)) {
15543 PyErr_BadArgument();
15544 return NULL;
15545 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015546 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015547 if (u == NULL)
15548 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015549 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015550 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015551 PyErr_NoMemory();
15552 return NULL;
15553 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015554 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015555 size *= sizeof(Py_UNICODE);
15556 copy = PyMem_Malloc(size);
15557 if (copy == NULL) {
15558 PyErr_NoMemory();
15559 return NULL;
15560 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015561 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015562 return copy;
15563}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015564
Georg Brandl66c221e2010-10-14 07:04:07 +000015565/* A _string module, to export formatter_parser and formatter_field_name_split
15566 to the string.Formatter class implemented in Python. */
15567
15568static PyMethodDef _string_methods[] = {
15569 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15570 METH_O, PyDoc_STR("split the argument as a field name")},
15571 {"formatter_parser", (PyCFunction) formatter_parser,
15572 METH_O, PyDoc_STR("parse the argument as a format string")},
15573 {NULL, NULL}
15574};
15575
15576static struct PyModuleDef _string_module = {
15577 PyModuleDef_HEAD_INIT,
15578 "_string",
15579 PyDoc_STR("string helper module"),
15580 0,
15581 _string_methods,
15582 NULL,
15583 NULL,
15584 NULL,
15585 NULL
15586};
15587
15588PyMODINIT_FUNC
15589PyInit__string(void)
15590{
15591 return PyModule_Create(&_string_module);
15592}
15593
15594
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015595#ifdef __cplusplus
15596}
15597#endif