blob: 1f221aff67c0d780aae360d8cdaeffca651209a1 [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
Serhiy Storchaka0edffa32017-06-27 21:08:58 +03003020wchar_t*
3021_PyUnicode_AsWideCharString(PyObject *unicode)
3022{
3023 const wchar_t *wstr;
3024 wchar_t *buffer;
3025 Py_ssize_t buflen;
3026
3027 if (unicode == NULL) {
3028 PyErr_BadInternalCall();
3029 return NULL;
3030 }
3031
3032 wstr = PyUnicode_AsUnicodeAndSize(unicode, &buflen);
3033 if (wstr == NULL) {
3034 return NULL;
3035 }
3036 if (wcslen(wstr) != (size_t)buflen) {
3037 PyErr_SetString(PyExc_ValueError,
3038 "embedded null character");
3039 return NULL;
3040 }
3041
3042 buffer = PyMem_NEW(wchar_t, buflen + 1);
3043 if (buffer == NULL) {
3044 PyErr_NoMemory();
3045 return NULL;
3046 }
3047 memcpy(buffer, wstr, (buflen + 1) * sizeof(wchar_t));
3048 return buffer;
3049}
3050
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003051#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003052
Alexander Belopolsky40018472011-02-26 01:02:56 +00003053PyObject *
3054PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003055{
Victor Stinner8faf8212011-12-08 22:14:11 +01003056 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003057 PyErr_SetString(PyExc_ValueError,
3058 "chr() arg not in range(0x110000)");
3059 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003060 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003061
Victor Stinner985a82a2014-01-03 12:53:47 +01003062 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003063}
3064
Alexander Belopolsky40018472011-02-26 01:02:56 +00003065PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003066PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003067{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003068 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003069 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003070 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003071 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003072 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003073 Py_INCREF(obj);
3074 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003075 }
3076 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003077 /* For a Unicode subtype that's not a Unicode object,
3078 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003079 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003080 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003081 PyErr_Format(PyExc_TypeError,
3082 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003083 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003084 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003085}
3086
Alexander Belopolsky40018472011-02-26 01:02:56 +00003087PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003088PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003089 const char *encoding,
3090 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003091{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003092 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003093 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003094
Guido van Rossumd57fd912000-03-10 22:53:23 +00003095 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003096 PyErr_BadInternalCall();
3097 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003098 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003099
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003100 /* Decoding bytes objects is the most common case and should be fast */
3101 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003102 if (PyBytes_GET_SIZE(obj) == 0)
3103 _Py_RETURN_UNICODE_EMPTY();
3104 v = PyUnicode_Decode(
3105 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3106 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003107 return v;
3108 }
3109
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003110 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003111 PyErr_SetString(PyExc_TypeError,
3112 "decoding str is not supported");
3113 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003114 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003115
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003116 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3117 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3118 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003119 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003120 Py_TYPE(obj)->tp_name);
3121 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003122 }
Tim Petersced69f82003-09-16 20:30:58 +00003123
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003124 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003125 PyBuffer_Release(&buffer);
3126 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003127 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003128
Serhiy Storchaka05997252013-01-26 12:14:02 +02003129 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003130 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003131 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003132}
3133
Victor Stinnerebe17e02016-10-12 13:57:45 +02003134/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3135 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3136 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003137int
3138_Py_normalize_encoding(const char *encoding,
3139 char *lower,
3140 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003141{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003142 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003143 char *l;
3144 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003145 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003146
Victor Stinner942889a2016-09-05 15:40:10 -07003147 assert(encoding != NULL);
3148
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003149 e = encoding;
3150 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003151 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003152 punct = 0;
3153 while (1) {
3154 char c = *e;
3155 if (c == 0) {
3156 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003157 }
Victor Stinner942889a2016-09-05 15:40:10 -07003158
3159 if (Py_ISALNUM(c) || c == '.') {
3160 if (punct && l != lower) {
3161 if (l == l_end) {
3162 return 0;
3163 }
3164 *l++ = '_';
3165 }
3166 punct = 0;
3167
3168 if (l == l_end) {
3169 return 0;
3170 }
3171 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003172 }
3173 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003174 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003175 }
Victor Stinner942889a2016-09-05 15:40:10 -07003176
3177 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003178 }
3179 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003180 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003181}
3182
Alexander Belopolsky40018472011-02-26 01:02:56 +00003183PyObject *
3184PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003185 Py_ssize_t size,
3186 const char *encoding,
3187 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003188{
3189 PyObject *buffer = NULL, *unicode;
3190 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003191 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3192
3193 if (encoding == NULL) {
3194 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3195 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003196
Fred Drakee4315f52000-05-09 19:53:39 +00003197 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003198 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3199 char *lower = buflower;
3200
3201 /* Fast paths */
3202 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3203 lower += 3;
3204 if (*lower == '_') {
3205 /* Match "utf8" and "utf_8" */
3206 lower++;
3207 }
3208
3209 if (lower[0] == '8' && lower[1] == 0) {
3210 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3211 }
3212 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3213 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3214 }
3215 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3216 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3217 }
3218 }
3219 else {
3220 if (strcmp(lower, "ascii") == 0
3221 || strcmp(lower, "us_ascii") == 0) {
3222 return PyUnicode_DecodeASCII(s, size, errors);
3223 }
Steve Dowercc16be82016-09-08 10:35:16 -07003224 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003225 else if (strcmp(lower, "mbcs") == 0) {
3226 return PyUnicode_DecodeMBCS(s, size, errors);
3227 }
3228 #endif
3229 else if (strcmp(lower, "latin1") == 0
3230 || strcmp(lower, "latin_1") == 0
3231 || strcmp(lower, "iso_8859_1") == 0
3232 || strcmp(lower, "iso8859_1") == 0) {
3233 return PyUnicode_DecodeLatin1(s, size, errors);
3234 }
3235 }
Victor Stinner37296e82010-06-10 13:36:23 +00003236 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003237
3238 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003239 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003240 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003241 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003242 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003243 if (buffer == NULL)
3244 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003245 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003246 if (unicode == NULL)
3247 goto onError;
3248 if (!PyUnicode_Check(unicode)) {
3249 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003250 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3251 "use codecs.decode() to decode to arbitrary types",
3252 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003253 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003254 Py_DECREF(unicode);
3255 goto onError;
3256 }
3257 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003258 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003259
Benjamin Peterson29060642009-01-31 22:14:21 +00003260 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003261 Py_XDECREF(buffer);
3262 return NULL;
3263}
3264
Alexander Belopolsky40018472011-02-26 01:02:56 +00003265PyObject *
3266PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003267 const char *encoding,
3268 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003269{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003270 if (!PyUnicode_Check(unicode)) {
3271 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003272 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003273 }
3274
Serhiy Storchaka00939072016-10-27 21:05:49 +03003275 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3276 "PyUnicode_AsDecodedObject() is deprecated; "
3277 "use PyCodec_Decode() to decode from str", 1) < 0)
3278 return NULL;
3279
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003280 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003281 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003282
3283 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003284 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003285}
3286
Alexander Belopolsky40018472011-02-26 01:02:56 +00003287PyObject *
3288PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003289 const char *encoding,
3290 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003291{
3292 PyObject *v;
3293
3294 if (!PyUnicode_Check(unicode)) {
3295 PyErr_BadArgument();
3296 goto onError;
3297 }
3298
Serhiy Storchaka00939072016-10-27 21:05:49 +03003299 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3300 "PyUnicode_AsDecodedUnicode() is deprecated; "
3301 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3302 return NULL;
3303
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003304 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003305 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003306
3307 /* Decode via the codec registry */
3308 v = PyCodec_Decode(unicode, encoding, errors);
3309 if (v == NULL)
3310 goto onError;
3311 if (!PyUnicode_Check(v)) {
3312 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003313 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3314 "use codecs.decode() to decode to arbitrary types",
3315 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003316 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003317 Py_DECREF(v);
3318 goto onError;
3319 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003320 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003321
Benjamin Peterson29060642009-01-31 22:14:21 +00003322 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003323 return NULL;
3324}
3325
Alexander Belopolsky40018472011-02-26 01:02:56 +00003326PyObject *
3327PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003328 Py_ssize_t size,
3329 const char *encoding,
3330 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003331{
3332 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003333
Guido van Rossumd57fd912000-03-10 22:53:23 +00003334 unicode = PyUnicode_FromUnicode(s, size);
3335 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003336 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003337 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3338 Py_DECREF(unicode);
3339 return v;
3340}
3341
Alexander Belopolsky40018472011-02-26 01:02:56 +00003342PyObject *
3343PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003344 const char *encoding,
3345 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003346{
3347 PyObject *v;
3348
3349 if (!PyUnicode_Check(unicode)) {
3350 PyErr_BadArgument();
3351 goto onError;
3352 }
3353
Serhiy Storchaka00939072016-10-27 21:05:49 +03003354 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3355 "PyUnicode_AsEncodedObject() is deprecated; "
3356 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3357 "or PyCodec_Encode() for generic encoding", 1) < 0)
3358 return NULL;
3359
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003360 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003361 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003362
3363 /* Encode via the codec registry */
3364 v = PyCodec_Encode(unicode, encoding, errors);
3365 if (v == NULL)
3366 goto onError;
3367 return v;
3368
Benjamin Peterson29060642009-01-31 22:14:21 +00003369 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003370 return NULL;
3371}
3372
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003373static size_t
3374wcstombs_errorpos(const wchar_t *wstr)
3375{
3376 size_t len;
3377#if SIZEOF_WCHAR_T == 2
3378 wchar_t buf[3];
3379#else
3380 wchar_t buf[2];
3381#endif
3382 char outbuf[MB_LEN_MAX];
3383 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003384
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003385#if SIZEOF_WCHAR_T == 2
3386 buf[2] = 0;
3387#else
3388 buf[1] = 0;
3389#endif
3390 start = wstr;
3391 while (*wstr != L'\0')
3392 {
3393 previous = wstr;
3394#if SIZEOF_WCHAR_T == 2
3395 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3396 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3397 {
3398 buf[0] = wstr[0];
3399 buf[1] = wstr[1];
3400 wstr += 2;
3401 }
3402 else {
3403 buf[0] = *wstr;
3404 buf[1] = 0;
3405 wstr++;
3406 }
3407#else
3408 buf[0] = *wstr;
3409 wstr++;
3410#endif
3411 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003412 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003413 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003414 }
3415
3416 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003417 return 0;
3418}
3419
Victor Stinner1b579672011-12-17 05:47:23 +01003420static int
3421locale_error_handler(const char *errors, int *surrogateescape)
3422{
Victor Stinner50149202015-09-22 00:26:54 +02003423 _Py_error_handler error_handler = get_error_handler(errors);
3424 switch (error_handler)
3425 {
3426 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003427 *surrogateescape = 0;
3428 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003429 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003430 *surrogateescape = 1;
3431 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003432 default:
3433 PyErr_Format(PyExc_ValueError,
3434 "only 'strict' and 'surrogateescape' error handlers "
3435 "are supported, not '%s'",
3436 errors);
3437 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003438 }
Victor Stinner1b579672011-12-17 05:47:23 +01003439}
3440
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003441PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003442PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003443{
3444 Py_ssize_t wlen, wlen2;
3445 wchar_t *wstr;
3446 PyObject *bytes = NULL;
3447 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003448 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003449 PyObject *exc;
3450 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003451 int surrogateescape;
3452
3453 if (locale_error_handler(errors, &surrogateescape) < 0)
3454 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003455
3456 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3457 if (wstr == NULL)
3458 return NULL;
3459
3460 wlen2 = wcslen(wstr);
3461 if (wlen2 != wlen) {
3462 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003463 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003464 return NULL;
3465 }
3466
3467 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003468 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003469 char *str;
3470
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003471 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003472 if (str == NULL) {
3473 if (error_pos == (size_t)-1) {
3474 PyErr_NoMemory();
3475 PyMem_Free(wstr);
3476 return NULL;
3477 }
3478 else {
3479 goto encode_error;
3480 }
3481 }
3482 PyMem_Free(wstr);
3483
3484 bytes = PyBytes_FromString(str);
3485 PyMem_Free(str);
3486 }
3487 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003488 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003489 size_t len, len2;
3490
3491 len = wcstombs(NULL, wstr, 0);
3492 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003493 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003494 goto encode_error;
3495 }
3496
3497 bytes = PyBytes_FromStringAndSize(NULL, len);
3498 if (bytes == NULL) {
3499 PyMem_Free(wstr);
3500 return NULL;
3501 }
3502
3503 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3504 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003505 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003506 goto encode_error;
3507 }
3508 PyMem_Free(wstr);
3509 }
3510 return bytes;
3511
3512encode_error:
3513 errmsg = strerror(errno);
3514 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003515
3516 if (error_pos == (size_t)-1)
3517 error_pos = wcstombs_errorpos(wstr);
3518
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003519 PyMem_Free(wstr);
3520 Py_XDECREF(bytes);
3521
Victor Stinner2f197072011-12-17 07:08:30 +01003522 if (errmsg != NULL) {
3523 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003524 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003525 if (wstr != NULL) {
3526 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003527 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003528 } else
3529 errmsg = NULL;
3530 }
3531 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003532 reason = PyUnicode_FromString(
3533 "wcstombs() encountered an unencodable "
3534 "wide character");
3535 if (reason == NULL)
3536 return NULL;
3537
3538 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3539 "locale", unicode,
3540 (Py_ssize_t)error_pos,
3541 (Py_ssize_t)(error_pos+1),
3542 reason);
3543 Py_DECREF(reason);
3544 if (exc != NULL) {
3545 PyCodec_StrictErrors(exc);
3546 Py_XDECREF(exc);
3547 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003548 return NULL;
3549}
3550
Victor Stinnerad158722010-10-27 00:25:46 +00003551PyObject *
3552PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003553{
Steve Dowercc16be82016-09-08 10:35:16 -07003554#if defined(__APPLE__)
3555 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003556#else
Victor Stinner793b5312011-04-27 00:24:21 +02003557 PyInterpreterState *interp = PyThreadState_GET()->interp;
3558 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3559 cannot use it to encode and decode filenames before it is loaded. Load
3560 the Python codec requires to encode at least its own filename. Use the C
3561 version of the locale codec until the codec registry is initialized and
3562 the Python codec is loaded.
3563
3564 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3565 cannot only rely on it: check also interp->fscodec_initialized for
3566 subinterpreters. */
3567 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003568 return PyUnicode_AsEncodedString(unicode,
3569 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003570 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003571 }
3572 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003573 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003574 }
Victor Stinnerad158722010-10-27 00:25:46 +00003575#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003576}
3577
Alexander Belopolsky40018472011-02-26 01:02:56 +00003578PyObject *
3579PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003580 const char *encoding,
3581 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003582{
3583 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003584 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003585
Guido van Rossumd57fd912000-03-10 22:53:23 +00003586 if (!PyUnicode_Check(unicode)) {
3587 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003588 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003589 }
Fred Drakee4315f52000-05-09 19:53:39 +00003590
Victor Stinner942889a2016-09-05 15:40:10 -07003591 if (encoding == NULL) {
3592 return _PyUnicode_AsUTF8String(unicode, errors);
3593 }
3594
Fred Drakee4315f52000-05-09 19:53:39 +00003595 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003596 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3597 char *lower = buflower;
3598
3599 /* Fast paths */
3600 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3601 lower += 3;
3602 if (*lower == '_') {
3603 /* Match "utf8" and "utf_8" */
3604 lower++;
3605 }
3606
3607 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003608 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003609 }
3610 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3611 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3612 }
3613 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3614 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3615 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003616 }
Victor Stinner942889a2016-09-05 15:40:10 -07003617 else {
3618 if (strcmp(lower, "ascii") == 0
3619 || strcmp(lower, "us_ascii") == 0) {
3620 return _PyUnicode_AsASCIIString(unicode, errors);
3621 }
Steve Dowercc16be82016-09-08 10:35:16 -07003622#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003623 else if (strcmp(lower, "mbcs") == 0) {
3624 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3625 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003626#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003627 else if (strcmp(lower, "latin1") == 0 ||
3628 strcmp(lower, "latin_1") == 0 ||
3629 strcmp(lower, "iso_8859_1") == 0 ||
3630 strcmp(lower, "iso8859_1") == 0) {
3631 return _PyUnicode_AsLatin1String(unicode, errors);
3632 }
3633 }
Victor Stinner37296e82010-06-10 13:36:23 +00003634 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003635
3636 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003637 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003638 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003639 return NULL;
3640
3641 /* The normal path */
3642 if (PyBytes_Check(v))
3643 return v;
3644
3645 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003646 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003647 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003648 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003649
3650 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003651 "encoder %s returned bytearray instead of bytes; "
3652 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003653 encoding);
3654 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003655 Py_DECREF(v);
3656 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003657 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003658
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003659 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3660 Py_DECREF(v);
3661 return b;
3662 }
3663
3664 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003665 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3666 "use codecs.encode() to encode to arbitrary types",
3667 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003668 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003669 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003670 return NULL;
3671}
3672
Alexander Belopolsky40018472011-02-26 01:02:56 +00003673PyObject *
3674PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003675 const char *encoding,
3676 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003677{
3678 PyObject *v;
3679
3680 if (!PyUnicode_Check(unicode)) {
3681 PyErr_BadArgument();
3682 goto onError;
3683 }
3684
Serhiy Storchaka00939072016-10-27 21:05:49 +03003685 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3686 "PyUnicode_AsEncodedUnicode() is deprecated; "
3687 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3688 return NULL;
3689
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003690 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003691 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003692
3693 /* Encode via the codec registry */
3694 v = PyCodec_Encode(unicode, encoding, errors);
3695 if (v == NULL)
3696 goto onError;
3697 if (!PyUnicode_Check(v)) {
3698 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003699 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3700 "use codecs.encode() to encode to arbitrary types",
3701 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003702 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003703 Py_DECREF(v);
3704 goto onError;
3705 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003706 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003707
Benjamin Peterson29060642009-01-31 22:14:21 +00003708 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003709 return NULL;
3710}
3711
Victor Stinner2f197072011-12-17 07:08:30 +01003712static size_t
3713mbstowcs_errorpos(const char *str, size_t len)
3714{
3715#ifdef HAVE_MBRTOWC
3716 const char *start = str;
3717 mbstate_t mbs;
3718 size_t converted;
3719 wchar_t ch;
3720
3721 memset(&mbs, 0, sizeof mbs);
3722 while (len)
3723 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003724 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003725 if (converted == 0)
3726 /* Reached end of string */
3727 break;
3728 if (converted == (size_t)-1 || converted == (size_t)-2) {
3729 /* Conversion error or incomplete character */
3730 return str - start;
3731 }
3732 else {
3733 str += converted;
3734 len -= converted;
3735 }
3736 }
3737 /* failed to find the undecodable byte sequence */
3738 return 0;
3739#endif
3740 return 0;
3741}
3742
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003743PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003744PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003745 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003746{
3747 wchar_t smallbuf[256];
3748 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3749 wchar_t *wstr;
3750 size_t wlen, wlen2;
3751 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003752 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003753 size_t error_pos;
3754 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003755 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3756 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003757
3758 if (locale_error_handler(errors, &surrogateescape) < 0)
3759 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003760
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003761 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3762 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003763 return NULL;
3764 }
3765
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003766 if (surrogateescape) {
3767 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003768 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003769 if (wstr == NULL) {
3770 if (wlen == (size_t)-1)
3771 PyErr_NoMemory();
3772 else
3773 PyErr_SetFromErrno(PyExc_OSError);
3774 return NULL;
3775 }
3776
3777 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003778 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003779 }
3780 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003781 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003782#ifndef HAVE_BROKEN_MBSTOWCS
3783 wlen = mbstowcs(NULL, str, 0);
3784#else
3785 wlen = len;
3786#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003787 if (wlen == (size_t)-1)
3788 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003789 if (wlen+1 <= smallbuf_len) {
3790 wstr = smallbuf;
3791 }
3792 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003793 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003794 if (!wstr)
3795 return PyErr_NoMemory();
3796 }
3797
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003798 wlen2 = mbstowcs(wstr, str, wlen+1);
3799 if (wlen2 == (size_t)-1) {
3800 if (wstr != smallbuf)
3801 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003802 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003803 }
3804#ifdef HAVE_BROKEN_MBSTOWCS
3805 assert(wlen2 == wlen);
3806#endif
3807 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3808 if (wstr != smallbuf)
3809 PyMem_Free(wstr);
3810 }
3811 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003812
3813decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003814 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003815 errmsg = strerror(errno);
3816 assert(errmsg != NULL);
3817
3818 error_pos = mbstowcs_errorpos(str, len);
3819 if (errmsg != NULL) {
3820 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003821 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003822 if (wstr != NULL) {
3823 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003824 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003825 }
Victor Stinner2f197072011-12-17 07:08:30 +01003826 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003827 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003828 reason = PyUnicode_FromString(
3829 "mbstowcs() encountered an invalid multibyte sequence");
3830 if (reason == NULL)
3831 return NULL;
3832
3833 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3834 "locale", str, len,
3835 (Py_ssize_t)error_pos,
3836 (Py_ssize_t)(error_pos+1),
3837 reason);
3838 Py_DECREF(reason);
3839 if (exc != NULL) {
3840 PyCodec_StrictErrors(exc);
3841 Py_XDECREF(exc);
3842 }
3843 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003844}
3845
3846PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003847PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003848{
3849 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003850 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003851}
3852
3853
3854PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003855PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003856 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003857 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3858}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003859
Christian Heimes5894ba72007-11-04 11:43:14 +00003860PyObject*
3861PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3862{
Steve Dowercc16be82016-09-08 10:35:16 -07003863#if defined(__APPLE__)
3864 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003865#else
Victor Stinner793b5312011-04-27 00:24:21 +02003866 PyInterpreterState *interp = PyThreadState_GET()->interp;
3867 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3868 cannot use it to encode and decode filenames before it is loaded. Load
3869 the Python codec requires to encode at least its own filename. Use the C
3870 version of the locale codec until the codec registry is initialized and
3871 the Python codec is loaded.
3872
3873 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3874 cannot only rely on it: check also interp->fscodec_initialized for
3875 subinterpreters. */
3876 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003877 return PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003878 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003879 Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003880 }
3881 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003882 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003883 }
Victor Stinnerad158722010-10-27 00:25:46 +00003884#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003885}
3886
Martin v. Löwis011e8422009-05-05 04:43:17 +00003887
3888int
3889PyUnicode_FSConverter(PyObject* arg, void* addr)
3890{
Brett Cannonec6ce872016-09-06 15:50:29 -07003891 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003892 PyObject *output = NULL;
3893 Py_ssize_t size;
3894 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003895 if (arg == NULL) {
3896 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003897 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003898 return 1;
3899 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003900 path = PyOS_FSPath(arg);
3901 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003902 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003903 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003904 if (PyBytes_Check(path)) {
3905 output = path;
3906 }
3907 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3908 output = PyUnicode_EncodeFSDefault(path);
3909 Py_DECREF(path);
3910 if (!output) {
3911 return 0;
3912 }
3913 assert(PyBytes_Check(output));
3914 }
3915
Victor Stinner0ea2a462010-04-30 00:22:08 +00003916 size = PyBytes_GET_SIZE(output);
3917 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003918 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003919 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003920 Py_DECREF(output);
3921 return 0;
3922 }
3923 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003924 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003925}
3926
3927
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003928int
3929PyUnicode_FSDecoder(PyObject* arg, void* addr)
3930{
Brett Cannona5711202016-09-06 19:36:01 -07003931 int is_buffer = 0;
3932 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003933 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003934 if (arg == NULL) {
3935 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka7a113a02017-04-20 22:55:06 +03003936 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003937 return 1;
3938 }
Brett Cannona5711202016-09-06 19:36:01 -07003939
3940 is_buffer = PyObject_CheckBuffer(arg);
3941 if (!is_buffer) {
3942 path = PyOS_FSPath(arg);
3943 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003944 return 0;
3945 }
Brett Cannona5711202016-09-06 19:36:01 -07003946 }
3947 else {
3948 path = arg;
3949 Py_INCREF(arg);
3950 }
3951
3952 if (PyUnicode_Check(path)) {
3953 if (PyUnicode_READY(path) == -1) {
3954 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003955 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003956 }
3957 output = path;
3958 }
3959 else if (PyBytes_Check(path) || is_buffer) {
3960 PyObject *path_bytes = NULL;
3961
3962 if (!PyBytes_Check(path) &&
3963 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3964 "path should be string, bytes, or os.PathLike, not %.200s",
3965 Py_TYPE(arg)->tp_name)) {
3966 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003967 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003968 }
3969 path_bytes = PyBytes_FromObject(path);
3970 Py_DECREF(path);
3971 if (!path_bytes) {
3972 return 0;
3973 }
3974 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3975 PyBytes_GET_SIZE(path_bytes));
3976 Py_DECREF(path_bytes);
3977 if (!output) {
3978 return 0;
3979 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003980 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003981 else {
3982 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003983 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003984 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003985 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003986 return 0;
3987 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003988 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003989 Py_DECREF(output);
3990 return 0;
3991 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003992 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003993 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003994 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003995 Py_DECREF(output);
3996 return 0;
3997 }
3998 *(PyObject**)addr = output;
3999 return Py_CLEANUP_SUPPORTED;
4000}
4001
4002
Martin v. Löwis5b222132007-06-10 09:51:05 +00004003char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00004005{
Christian Heimesf3863112007-11-22 07:46:41 +00004006 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004007
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00004008 if (!PyUnicode_Check(unicode)) {
4009 PyErr_BadArgument();
4010 return NULL;
4011 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004012 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00004013 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004014
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004015 if (PyUnicode_UTF8(unicode) == NULL) {
4016 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03004017 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004018 if (bytes == NULL)
4019 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004020 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
4021 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01004022 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004023 Py_DECREF(bytes);
4024 return NULL;
4025 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004026 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02004027 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004028 PyBytes_AS_STRING(bytes),
4029 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004030 Py_DECREF(bytes);
4031 }
4032
4033 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004034 *psize = PyUnicode_UTF8_LENGTH(unicode);
4035 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004036}
4037
4038char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004039PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004040{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004041 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4042}
4043
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004044Py_UNICODE *
4045PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4046{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004047 const unsigned char *one_byte;
4048#if SIZEOF_WCHAR_T == 4
4049 const Py_UCS2 *two_bytes;
4050#else
4051 const Py_UCS4 *four_bytes;
4052 const Py_UCS4 *ucs4_end;
4053 Py_ssize_t num_surrogates;
4054#endif
4055 wchar_t *w;
4056 wchar_t *wchar_end;
4057
4058 if (!PyUnicode_Check(unicode)) {
4059 PyErr_BadArgument();
4060 return NULL;
4061 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004062 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004063 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004064 assert(_PyUnicode_KIND(unicode) != 0);
4065 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004066
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004067 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004068#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004069 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4070 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004071 num_surrogates = 0;
4072
4073 for (; four_bytes < ucs4_end; ++four_bytes) {
4074 if (*four_bytes > 0xFFFF)
4075 ++num_surrogates;
4076 }
4077
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004078 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4079 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4080 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004081 PyErr_NoMemory();
4082 return NULL;
4083 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004084 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004085
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004086 w = _PyUnicode_WSTR(unicode);
4087 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4088 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004089 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4090 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004091 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004092 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004093 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4094 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004095 }
4096 else
4097 *w = *four_bytes;
4098
4099 if (w > wchar_end) {
4100 assert(0 && "Miscalculated string end");
4101 }
4102 }
4103 *w = 0;
4104#else
4105 /* sizeof(wchar_t) == 4 */
4106 Py_FatalError("Impossible unicode object state, wstr and str "
4107 "should share memory already.");
4108 return NULL;
4109#endif
4110 }
4111 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004112 if ((size_t)_PyUnicode_LENGTH(unicode) >
4113 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4114 PyErr_NoMemory();
4115 return NULL;
4116 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004117 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4118 (_PyUnicode_LENGTH(unicode) + 1));
4119 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004120 PyErr_NoMemory();
4121 return NULL;
4122 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004123 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4124 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4125 w = _PyUnicode_WSTR(unicode);
4126 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004127
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004128 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4129 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004130 for (; w < wchar_end; ++one_byte, ++w)
4131 *w = *one_byte;
4132 /* null-terminate the wstr */
4133 *w = 0;
4134 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004135 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004136#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004137 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004138 for (; w < wchar_end; ++two_bytes, ++w)
4139 *w = *two_bytes;
4140 /* null-terminate the wstr */
4141 *w = 0;
4142#else
4143 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004144 PyObject_FREE(_PyUnicode_WSTR(unicode));
4145 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004146 Py_FatalError("Impossible unicode object state, wstr "
4147 "and str should share memory already.");
4148 return NULL;
4149#endif
4150 }
4151 else {
4152 assert(0 && "This should never happen.");
4153 }
4154 }
4155 }
4156 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004157 *size = PyUnicode_WSTR_LENGTH(unicode);
4158 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004159}
4160
Alexander Belopolsky40018472011-02-26 01:02:56 +00004161Py_UNICODE *
4162PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004163{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004164 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004165}
4166
Serhiy Storchaka08349052017-06-28 09:27:35 +03004167const Py_UNICODE *
4168_PyUnicode_AsUnicode(PyObject *unicode)
4169{
4170 Py_ssize_t size;
4171 const Py_UNICODE *wstr;
4172
4173 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
4174 if (wstr && wcslen(wstr) != (size_t)size) {
4175 PyErr_SetString(PyExc_ValueError, "embedded null character");
4176 return NULL;
4177 }
4178 return wstr;
4179}
4180
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004181
Alexander Belopolsky40018472011-02-26 01:02:56 +00004182Py_ssize_t
4183PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004184{
4185 if (!PyUnicode_Check(unicode)) {
4186 PyErr_BadArgument();
4187 goto onError;
4188 }
4189 return PyUnicode_GET_SIZE(unicode);
4190
Benjamin Peterson29060642009-01-31 22:14:21 +00004191 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004192 return -1;
4193}
4194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004195Py_ssize_t
4196PyUnicode_GetLength(PyObject *unicode)
4197{
Victor Stinner07621332012-06-16 04:53:46 +02004198 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004199 PyErr_BadArgument();
4200 return -1;
4201 }
Victor Stinner07621332012-06-16 04:53:46 +02004202 if (PyUnicode_READY(unicode) == -1)
4203 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004204 return PyUnicode_GET_LENGTH(unicode);
4205}
4206
4207Py_UCS4
4208PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4209{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004210 void *data;
4211 int kind;
4212
Serhiy Storchakaddb536b2017-09-08 10:43:54 +03004213 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004214 PyErr_BadArgument();
4215 return (Py_UCS4)-1;
4216 }
Serhiy Storchakaddb536b2017-09-08 10:43:54 +03004217 if (PyUnicode_READY(unicode) == -1) {
4218 return (Py_UCS4)-1;
4219 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004220 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004221 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004222 return (Py_UCS4)-1;
4223 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004224 data = PyUnicode_DATA(unicode);
4225 kind = PyUnicode_KIND(unicode);
4226 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004227}
4228
4229int
4230PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4231{
4232 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004233 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004234 return -1;
4235 }
Victor Stinner488fa492011-12-12 00:01:39 +01004236 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004237 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004238 PyErr_SetString(PyExc_IndexError, "string index out of range");
4239 return -1;
4240 }
Victor Stinner488fa492011-12-12 00:01:39 +01004241 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004242 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004243 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4244 PyErr_SetString(PyExc_ValueError, "character out of range");
4245 return -1;
4246 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004247 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4248 index, ch);
4249 return 0;
4250}
4251
Alexander Belopolsky40018472011-02-26 01:02:56 +00004252const char *
4253PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004254{
Victor Stinner42cb4622010-09-01 19:39:01 +00004255 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004256}
4257
Victor Stinner554f3f02010-06-16 23:33:54 +00004258/* create or adjust a UnicodeDecodeError */
4259static void
4260make_decode_exception(PyObject **exceptionObject,
4261 const char *encoding,
4262 const char *input, Py_ssize_t length,
4263 Py_ssize_t startpos, Py_ssize_t endpos,
4264 const char *reason)
4265{
4266 if (*exceptionObject == NULL) {
4267 *exceptionObject = PyUnicodeDecodeError_Create(
4268 encoding, input, length, startpos, endpos, reason);
4269 }
4270 else {
4271 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4272 goto onError;
4273 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4274 goto onError;
4275 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4276 goto onError;
4277 }
4278 return;
4279
4280onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004281 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004282}
4283
Steve Dowercc16be82016-09-08 10:35:16 -07004284#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004285/* error handling callback helper:
4286 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004287 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004288 and adjust various state variables.
4289 return 0 on success, -1 on error
4290*/
4291
Alexander Belopolsky40018472011-02-26 01:02:56 +00004292static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004293unicode_decode_call_errorhandler_wchar(
4294 const char *errors, PyObject **errorHandler,
4295 const char *encoding, const char *reason,
4296 const char **input, const char **inend, Py_ssize_t *startinpos,
4297 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4298 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004299{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004300 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004301
4302 PyObject *restuple = NULL;
4303 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004304 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004305 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004306 Py_ssize_t requiredsize;
4307 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004308 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004309 wchar_t *repwstr;
4310 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004311
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004312 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4313 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004314
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004315 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004316 *errorHandler = PyCodec_LookupError(errors);
4317 if (*errorHandler == NULL)
4318 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004319 }
4320
Victor Stinner554f3f02010-06-16 23:33:54 +00004321 make_decode_exception(exceptionObject,
4322 encoding,
4323 *input, *inend - *input,
4324 *startinpos, *endinpos,
4325 reason);
4326 if (*exceptionObject == NULL)
4327 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004328
4329 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4330 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004331 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004332 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004333 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004334 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004335 }
4336 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004337 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004338
4339 /* Copy back the bytes variables, which might have been modified by the
4340 callback */
4341 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4342 if (!inputobj)
4343 goto onError;
4344 if (!PyBytes_Check(inputobj)) {
4345 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4346 }
4347 *input = PyBytes_AS_STRING(inputobj);
4348 insize = PyBytes_GET_SIZE(inputobj);
4349 *inend = *input + insize;
4350 /* we can DECREF safely, as the exception has another reference,
4351 so the object won't go away. */
4352 Py_DECREF(inputobj);
4353
4354 if (newpos<0)
4355 newpos = insize+newpos;
4356 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004357 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004358 goto onError;
4359 }
4360
4361 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4362 if (repwstr == NULL)
4363 goto onError;
4364 /* need more space? (at least enough for what we
4365 have+the replacement+the rest of the string (starting
4366 at the new input position), so we won't have to check space
4367 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004368 requiredsize = *outpos;
4369 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4370 goto overflow;
4371 requiredsize += repwlen;
4372 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4373 goto overflow;
4374 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004375 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004376 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004377 requiredsize = 2*outsize;
4378 if (unicode_resize(output, requiredsize) < 0)
4379 goto onError;
4380 }
4381 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4382 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004383 *endinpos = newpos;
4384 *inptr = *input + newpos;
4385
4386 /* we made it! */
4387 Py_XDECREF(restuple);
4388 return 0;
4389
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004390 overflow:
4391 PyErr_SetString(PyExc_OverflowError,
4392 "decoded result is too long for a Python string");
4393
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004394 onError:
4395 Py_XDECREF(restuple);
4396 return -1;
4397}
Steve Dowercc16be82016-09-08 10:35:16 -07004398#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004399
4400static int
4401unicode_decode_call_errorhandler_writer(
4402 const char *errors, PyObject **errorHandler,
4403 const char *encoding, const char *reason,
4404 const char **input, const char **inend, Py_ssize_t *startinpos,
4405 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4406 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4407{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004408 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004409
4410 PyObject *restuple = NULL;
4411 PyObject *repunicode = NULL;
4412 Py_ssize_t insize;
4413 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004414 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004415 PyObject *inputobj = NULL;
4416
4417 if (*errorHandler == NULL) {
4418 *errorHandler = PyCodec_LookupError(errors);
4419 if (*errorHandler == NULL)
4420 goto onError;
4421 }
4422
4423 make_decode_exception(exceptionObject,
4424 encoding,
4425 *input, *inend - *input,
4426 *startinpos, *endinpos,
4427 reason);
4428 if (*exceptionObject == NULL)
4429 goto onError;
4430
4431 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4432 if (restuple == NULL)
4433 goto onError;
4434 if (!PyTuple_Check(restuple)) {
4435 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4436 goto onError;
4437 }
4438 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004439 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004440
4441 /* Copy back the bytes variables, which might have been modified by the
4442 callback */
4443 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4444 if (!inputobj)
4445 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004446 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004447 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004448 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004449 *input = PyBytes_AS_STRING(inputobj);
4450 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004451 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004452 /* we can DECREF safely, as the exception has another reference,
4453 so the object won't go away. */
4454 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004455
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004456 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004457 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004458 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004459 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004460 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004461 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004462
Victor Stinner8f674cc2013-04-17 23:02:17 +02004463 if (PyUnicode_READY(repunicode) < 0)
4464 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004465 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004466 if (replen > 1) {
4467 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004468 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004469 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4470 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4471 goto onError;
4472 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004473 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004474 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004475
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004476 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004477 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004478
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004479 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004480 Py_XDECREF(restuple);
4481 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004482
Benjamin Peterson29060642009-01-31 22:14:21 +00004483 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004484 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004485 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004486}
4487
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004488/* --- UTF-7 Codec -------------------------------------------------------- */
4489
Antoine Pitrou244651a2009-05-04 18:56:13 +00004490/* See RFC2152 for details. We encode conservatively and decode liberally. */
4491
4492/* Three simple macros defining base-64. */
4493
4494/* Is c a base-64 character? */
4495
4496#define IS_BASE64(c) \
4497 (((c) >= 'A' && (c) <= 'Z') || \
4498 ((c) >= 'a' && (c) <= 'z') || \
4499 ((c) >= '0' && (c) <= '9') || \
4500 (c) == '+' || (c) == '/')
4501
4502/* given that c is a base-64 character, what is its base-64 value? */
4503
4504#define FROM_BASE64(c) \
4505 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4506 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4507 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4508 (c) == '+' ? 62 : 63)
4509
4510/* What is the base-64 character of the bottom 6 bits of n? */
4511
4512#define TO_BASE64(n) \
4513 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4514
4515/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4516 * decoded as itself. We are permissive on decoding; the only ASCII
4517 * byte not decoding to itself is the + which begins a base64
4518 * string. */
4519
4520#define DECODE_DIRECT(c) \
4521 ((c) <= 127 && (c) != '+')
4522
4523/* The UTF-7 encoder treats ASCII characters differently according to
4524 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4525 * the above). See RFC2152. This array identifies these different
4526 * sets:
4527 * 0 : "Set D"
4528 * alphanumeric and '(),-./:?
4529 * 1 : "Set O"
4530 * !"#$%&*;<=>@[]^_`{|}
4531 * 2 : "whitespace"
4532 * ht nl cr sp
4533 * 3 : special (must be base64 encoded)
4534 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4535 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004536
Tim Petersced69f82003-09-16 20:30:58 +00004537static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004538char utf7_category[128] = {
4539/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4540 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4541/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4542 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4543/* sp ! " # $ % & ' ( ) * + , - . / */
4544 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4545/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4546 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4547/* @ A B C D E F G H I J K L M N O */
4548 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4549/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4550 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4551/* ` a b c d e f g h i j k l m n o */
4552 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4553/* p q r s t u v w x y z { | } ~ del */
4554 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004555};
4556
Antoine Pitrou244651a2009-05-04 18:56:13 +00004557/* ENCODE_DIRECT: this character should be encoded as itself. The
4558 * answer depends on whether we are encoding set O as itself, and also
4559 * on whether we are encoding whitespace as itself. RFC2152 makes it
4560 * clear that the answers to these questions vary between
4561 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004562
Antoine Pitrou244651a2009-05-04 18:56:13 +00004563#define ENCODE_DIRECT(c, directO, directWS) \
4564 ((c) < 128 && (c) > 0 && \
4565 ((utf7_category[(c)] == 0) || \
4566 (directWS && (utf7_category[(c)] == 2)) || \
4567 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004568
Alexander Belopolsky40018472011-02-26 01:02:56 +00004569PyObject *
4570PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004571 Py_ssize_t size,
4572 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004573{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004574 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4575}
4576
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577/* The decoder. The only state we preserve is our read position,
4578 * i.e. how many characters we have consumed. So if we end in the
4579 * middle of a shift sequence we have to back off the read position
4580 * and the output to the beginning of the sequence, otherwise we lose
4581 * all the shift state (seen bits, number of bits seen, high
4582 * surrogate). */
4583
Alexander Belopolsky40018472011-02-26 01:02:56 +00004584PyObject *
4585PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004586 Py_ssize_t size,
4587 const char *errors,
4588 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004589{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004590 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004591 Py_ssize_t startinpos;
4592 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004593 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004594 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004595 const char *errmsg = "";
4596 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004597 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004598 unsigned int base64bits = 0;
4599 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004600 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004601 PyObject *errorHandler = NULL;
4602 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004603
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004604 if (size == 0) {
4605 if (consumed)
4606 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004607 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004608 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004609
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004610 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004611 _PyUnicodeWriter_Init(&writer);
4612 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004613
4614 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004615 e = s + size;
4616
4617 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004618 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004619 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004620 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004621
Antoine Pitrou244651a2009-05-04 18:56:13 +00004622 if (inShift) { /* in a base-64 section */
4623 if (IS_BASE64(ch)) { /* consume a base-64 character */
4624 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4625 base64bits += 6;
4626 s++;
4627 if (base64bits >= 16) {
4628 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004629 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004630 base64bits -= 16;
4631 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004632 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004633 if (surrogate) {
4634 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004635 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4636 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004637 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004638 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004639 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004640 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004641 }
4642 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004643 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004644 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004645 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004646 }
4647 }
Victor Stinner551ac952011-11-29 22:58:13 +01004648 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004649 /* first surrogate */
4650 surrogate = outCh;
4651 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004652 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004653 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004654 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004655 }
4656 }
4657 }
4658 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004659 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004660 if (base64bits > 0) { /* left-over bits */
4661 if (base64bits >= 6) {
4662 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004663 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004664 errmsg = "partial character in shift sequence";
4665 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004666 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004667 else {
4668 /* Some bits remain; they should be zero */
4669 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004670 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004671 errmsg = "non-zero padding bits in shift sequence";
4672 goto utf7Error;
4673 }
4674 }
4675 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004676 if (surrogate && DECODE_DIRECT(ch)) {
4677 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4678 goto onError;
4679 }
4680 surrogate = 0;
4681 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004682 /* '-' is absorbed; other terminating
4683 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004684 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004685 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004686 }
4687 }
4688 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004689 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004690 s++; /* consume '+' */
4691 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004692 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004693 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004694 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004695 }
4696 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004697 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004698 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004699 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004700 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004701 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004702 }
4703 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004704 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004705 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004706 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004707 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004708 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004709 else {
4710 startinpos = s-starts;
4711 s++;
4712 errmsg = "unexpected special character";
4713 goto utf7Error;
4714 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004715 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004716utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004717 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004718 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004719 errors, &errorHandler,
4720 "utf7", errmsg,
4721 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004722 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004723 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004724 }
4725
Antoine Pitrou244651a2009-05-04 18:56:13 +00004726 /* end of string */
4727
4728 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4729 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004730 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004731 if (surrogate ||
4732 (base64bits >= 6) ||
4733 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004734 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004735 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004736 errors, &errorHandler,
4737 "utf7", "unterminated shift sequence",
4738 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004739 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004740 goto onError;
4741 if (s < e)
4742 goto restart;
4743 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004744 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004745
4746 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004747 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004748 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004749 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004750 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004751 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004752 writer.kind, writer.data, shiftOutStart);
4753 Py_XDECREF(errorHandler);
4754 Py_XDECREF(exc);
4755 _PyUnicodeWriter_Dealloc(&writer);
4756 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004757 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004758 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004759 }
4760 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004761 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004762 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004763 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004764
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004765 Py_XDECREF(errorHandler);
4766 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004767 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004768
Benjamin Peterson29060642009-01-31 22:14:21 +00004769 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004770 Py_XDECREF(errorHandler);
4771 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004772 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004773 return NULL;
4774}
4775
4776
Alexander Belopolsky40018472011-02-26 01:02:56 +00004777PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004778_PyUnicode_EncodeUTF7(PyObject *str,
4779 int base64SetO,
4780 int base64WhiteSpace,
4781 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004782{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004783 int kind;
4784 void *data;
4785 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004786 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004787 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004788 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004789 unsigned int base64bits = 0;
4790 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004791 char * out;
4792 char * start;
4793
Benjamin Petersonbac79492012-01-14 13:34:47 -05004794 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004795 return NULL;
4796 kind = PyUnicode_KIND(str);
4797 data = PyUnicode_DATA(str);
4798 len = PyUnicode_GET_LENGTH(str);
4799
4800 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004801 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004802
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004803 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004804 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004805 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004806 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004807 if (v == NULL)
4808 return NULL;
4809
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004810 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004811 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004812 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004813
Antoine Pitrou244651a2009-05-04 18:56:13 +00004814 if (inShift) {
4815 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4816 /* shifting out */
4817 if (base64bits) { /* output remaining bits */
4818 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4819 base64buffer = 0;
4820 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004821 }
4822 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004823 /* Characters not in the BASE64 set implicitly unshift the sequence
4824 so no '-' is required, except if the character is itself a '-' */
4825 if (IS_BASE64(ch) || ch == '-') {
4826 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004827 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004828 *out++ = (char) ch;
4829 }
4830 else {
4831 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004832 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004833 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004834 else { /* not in a shift sequence */
4835 if (ch == '+') {
4836 *out++ = '+';
4837 *out++ = '-';
4838 }
4839 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4840 *out++ = (char) ch;
4841 }
4842 else {
4843 *out++ = '+';
4844 inShift = 1;
4845 goto encode_char;
4846 }
4847 }
4848 continue;
4849encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004850 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004851 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004852
Antoine Pitrou244651a2009-05-04 18:56:13 +00004853 /* code first surrogate */
4854 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004855 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004856 while (base64bits >= 6) {
4857 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4858 base64bits -= 6;
4859 }
4860 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004861 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004862 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004863 base64bits += 16;
4864 base64buffer = (base64buffer << 16) | ch;
4865 while (base64bits >= 6) {
4866 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4867 base64bits -= 6;
4868 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004869 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004870 if (base64bits)
4871 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4872 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004873 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004874 if (_PyBytes_Resize(&v, out - start) < 0)
4875 return NULL;
4876 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004877}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004878PyObject *
4879PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4880 Py_ssize_t size,
4881 int base64SetO,
4882 int base64WhiteSpace,
4883 const char *errors)
4884{
4885 PyObject *result;
4886 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4887 if (tmp == NULL)
4888 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004889 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004890 base64WhiteSpace, errors);
4891 Py_DECREF(tmp);
4892 return result;
4893}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004894
Antoine Pitrou244651a2009-05-04 18:56:13 +00004895#undef IS_BASE64
4896#undef FROM_BASE64
4897#undef TO_BASE64
4898#undef DECODE_DIRECT
4899#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004900
Guido van Rossumd57fd912000-03-10 22:53:23 +00004901/* --- UTF-8 Codec -------------------------------------------------------- */
4902
Alexander Belopolsky40018472011-02-26 01:02:56 +00004903PyObject *
4904PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004905 Py_ssize_t size,
4906 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004907{
Walter Dörwald69652032004-09-07 20:24:22 +00004908 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4909}
4910
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004911#include "stringlib/asciilib.h"
4912#include "stringlib/codecs.h"
4913#include "stringlib/undef.h"
4914
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004915#include "stringlib/ucs1lib.h"
4916#include "stringlib/codecs.h"
4917#include "stringlib/undef.h"
4918
4919#include "stringlib/ucs2lib.h"
4920#include "stringlib/codecs.h"
4921#include "stringlib/undef.h"
4922
4923#include "stringlib/ucs4lib.h"
4924#include "stringlib/codecs.h"
4925#include "stringlib/undef.h"
4926
Antoine Pitrouab868312009-01-10 15:40:25 +00004927/* Mask to quickly check whether a C 'long' contains a
4928 non-ASCII, UTF8-encoded char. */
4929#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004930# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004931#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004932# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004933#else
4934# error C 'long' size should be either 4 or 8!
4935#endif
4936
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004937static Py_ssize_t
4938ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004939{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004940 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004941 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004942
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004943 /*
4944 * Issue #17237: m68k is a bit different from most architectures in
4945 * that objects do not use "natural alignment" - for example, int and
4946 * long are only aligned at 2-byte boundaries. Therefore the assert()
4947 * won't work; also, tests have shown that skipping the "optimised
4948 * version" will even speed up m68k.
4949 */
4950#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004951#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004952 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4953 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004954 /* Fast path, see in STRINGLIB(utf8_decode) for
4955 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004956 /* Help allocation */
4957 const char *_p = p;
4958 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004959 while (_p < aligned_end) {
4960 unsigned long value = *(const unsigned long *) _p;
4961 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004962 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004963 *((unsigned long *)q) = value;
4964 _p += SIZEOF_LONG;
4965 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004966 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004967 p = _p;
4968 while (p < end) {
4969 if ((unsigned char)*p & 0x80)
4970 break;
4971 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004972 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004973 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004974 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004975#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004976#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004977 while (p < end) {
4978 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4979 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004980 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004981 /* Help allocation */
4982 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004983 while (_p < aligned_end) {
4984 unsigned long value = *(unsigned long *) _p;
4985 if (value & ASCII_CHAR_MASK)
4986 break;
4987 _p += SIZEOF_LONG;
4988 }
4989 p = _p;
4990 if (_p == end)
4991 break;
4992 }
4993 if ((unsigned char)*p & 0x80)
4994 break;
4995 ++p;
4996 }
4997 memcpy(dest, start, p - start);
4998 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004999}
Antoine Pitrouab868312009-01-10 15:40:25 +00005000
Victor Stinner785938e2011-12-11 20:09:03 +01005001PyObject *
5002PyUnicode_DecodeUTF8Stateful(const char *s,
5003 Py_ssize_t size,
5004 const char *errors,
5005 Py_ssize_t *consumed)
5006{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005007 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01005008 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005009 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005010
5011 Py_ssize_t startinpos;
5012 Py_ssize_t endinpos;
5013 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02005014 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005015 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02005016 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01005017
5018 if (size == 0) {
5019 if (consumed)
5020 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005021 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01005022 }
5023
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005024 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5025 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01005026 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005027 *consumed = 1;
5028 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01005029 }
5030
Victor Stinner8f674cc2013-04-17 23:02:17 +02005031 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005032 writer.min_length = size;
5033 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005034 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01005035
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005036 writer.pos = ascii_decode(s, end, writer.data);
5037 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005038 while (s < end) {
5039 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005040 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02005041
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005042 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005043 if (PyUnicode_IS_ASCII(writer.buffer))
5044 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005045 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005046 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005047 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005048 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005049 } else {
5050 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005051 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005052 }
5053
5054 switch (ch) {
5055 case 0:
5056 if (s == end || consumed)
5057 goto End;
5058 errmsg = "unexpected end of data";
5059 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005060 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005061 break;
5062 case 1:
5063 errmsg = "invalid start byte";
5064 startinpos = s - starts;
5065 endinpos = startinpos + 1;
5066 break;
5067 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005068 case 3:
5069 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005070 errmsg = "invalid continuation byte";
5071 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005072 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005073 break;
5074 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005075 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005076 goto onError;
5077 continue;
5078 }
5079
Victor Stinner1d65d912015-10-05 13:43:50 +02005080 if (error_handler == _Py_ERROR_UNKNOWN)
5081 error_handler = get_error_handler(errors);
5082
5083 switch (error_handler) {
5084 case _Py_ERROR_IGNORE:
5085 s += (endinpos - startinpos);
5086 break;
5087
5088 case _Py_ERROR_REPLACE:
5089 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5090 goto onError;
5091 s += (endinpos - startinpos);
5092 break;
5093
5094 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005095 {
5096 Py_ssize_t i;
5097
Victor Stinner1d65d912015-10-05 13:43:50 +02005098 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5099 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005100 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005101 ch = (Py_UCS4)(unsigned char)(starts[i]);
5102 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5103 ch + 0xdc00);
5104 writer.pos++;
5105 }
5106 s += (endinpos - startinpos);
5107 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005108 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005109
5110 default:
5111 if (unicode_decode_call_errorhandler_writer(
5112 errors, &error_handler_obj,
5113 "utf-8", errmsg,
5114 &starts, &end, &startinpos, &endinpos, &exc, &s,
5115 &writer))
5116 goto onError;
5117 }
Victor Stinner785938e2011-12-11 20:09:03 +01005118 }
5119
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005120End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005121 if (consumed)
5122 *consumed = s - starts;
5123
Victor Stinner1d65d912015-10-05 13:43:50 +02005124 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005125 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005126 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005127
5128onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005129 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005130 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005131 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005132 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005133}
5134
Xavier de Gaye76febd02016-12-15 20:59:58 +01005135#if defined(__APPLE__) || defined(__ANDROID__)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005136
5137/* Simplified UTF-8 decoder using surrogateescape error handler,
Xavier de Gaye76febd02016-12-15 20:59:58 +01005138 used to decode the command line arguments on Mac OS X and Android.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005139
5140 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005141 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005142
5143wchar_t*
5144_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5145{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005146 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005147 wchar_t *unicode;
5148 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005149
5150 /* Note: size will always be longer than the resulting Unicode
5151 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005152 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005153 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005154 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005155 if (!unicode)
5156 return NULL;
5157
5158 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005159 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005160 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005161 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005162 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005163#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005164 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005165#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005166 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005167#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005168 if (ch > 0xFF) {
5169#if SIZEOF_WCHAR_T == 4
5170 assert(0);
5171#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005172 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005173 /* compute and append the two surrogates: */
5174 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5175 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5176#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005177 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005178 else {
5179 if (!ch && s == e)
5180 break;
5181 /* surrogateescape */
5182 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5183 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005184 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005185 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005186 return unicode;
5187}
5188
Xavier de Gaye76febd02016-12-15 20:59:58 +01005189#endif /* __APPLE__ or __ANDROID__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005191/* Primary internal function which creates utf8 encoded bytes objects.
5192
5193 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005194 and allocate exactly as much space needed at the end. Else allocate the
5195 maximum possible needed (4 result bytes per Unicode character), and return
5196 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005197*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005198PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005199_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005200{
Victor Stinner6099a032011-12-18 14:22:26 +01005201 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005202 void *data;
5203 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005204
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005205 if (!PyUnicode_Check(unicode)) {
5206 PyErr_BadArgument();
5207 return NULL;
5208 }
5209
5210 if (PyUnicode_READY(unicode) == -1)
5211 return NULL;
5212
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005213 if (PyUnicode_UTF8(unicode))
5214 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5215 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005216
5217 kind = PyUnicode_KIND(unicode);
5218 data = PyUnicode_DATA(unicode);
5219 size = PyUnicode_GET_LENGTH(unicode);
5220
Benjamin Petersonead6b532011-12-20 17:23:42 -06005221 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005222 default:
5223 assert(0);
5224 case PyUnicode_1BYTE_KIND:
5225 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5226 assert(!PyUnicode_IS_ASCII(unicode));
5227 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5228 case PyUnicode_2BYTE_KIND:
5229 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5230 case PyUnicode_4BYTE_KIND:
5231 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005232 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005233}
5234
Alexander Belopolsky40018472011-02-26 01:02:56 +00005235PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005236PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5237 Py_ssize_t size,
5238 const char *errors)
5239{
5240 PyObject *v, *unicode;
5241
5242 unicode = PyUnicode_FromUnicode(s, size);
5243 if (unicode == NULL)
5244 return NULL;
5245 v = _PyUnicode_AsUTF8String(unicode, errors);
5246 Py_DECREF(unicode);
5247 return v;
5248}
5249
5250PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005251PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005252{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005253 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005254}
5255
Walter Dörwald41980ca2007-08-16 21:55:45 +00005256/* --- UTF-32 Codec ------------------------------------------------------- */
5257
5258PyObject *
5259PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005260 Py_ssize_t size,
5261 const char *errors,
5262 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005263{
5264 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5265}
5266
5267PyObject *
5268PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005269 Py_ssize_t size,
5270 const char *errors,
5271 int *byteorder,
5272 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005273{
5274 const char *starts = s;
5275 Py_ssize_t startinpos;
5276 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005277 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005278 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005279 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005280 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005281 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005282 PyObject *errorHandler = NULL;
5283 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005284
Walter Dörwald41980ca2007-08-16 21:55:45 +00005285 q = (unsigned char *)s;
5286 e = q + size;
5287
5288 if (byteorder)
5289 bo = *byteorder;
5290
5291 /* Check for BOM marks (U+FEFF) in the input and adjust current
5292 byte order setting accordingly. In native mode, the leading BOM
5293 mark is skipped, in all other modes, it is copied to the output
5294 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005295 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005296 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005297 if (bom == 0x0000FEFF) {
5298 bo = -1;
5299 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005300 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005301 else if (bom == 0xFFFE0000) {
5302 bo = 1;
5303 q += 4;
5304 }
5305 if (byteorder)
5306 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005307 }
5308
Victor Stinnere64322e2012-10-30 23:12:47 +01005309 if (q == e) {
5310 if (consumed)
5311 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005312 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005313 }
5314
Victor Stinnere64322e2012-10-30 23:12:47 +01005315#ifdef WORDS_BIGENDIAN
5316 le = bo < 0;
5317#else
5318 le = bo <= 0;
5319#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005320 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005321
Victor Stinner8f674cc2013-04-17 23:02:17 +02005322 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005323 writer.min_length = (e - q + 3) / 4;
5324 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005325 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005326
Victor Stinnere64322e2012-10-30 23:12:47 +01005327 while (1) {
5328 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005329 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005330
Victor Stinnere64322e2012-10-30 23:12:47 +01005331 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005332 enum PyUnicode_Kind kind = writer.kind;
5333 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005334 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005335 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005336 if (le) {
5337 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005338 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005339 if (ch > maxch)
5340 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005341 if (kind != PyUnicode_1BYTE_KIND &&
5342 Py_UNICODE_IS_SURROGATE(ch))
5343 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005344 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005345 q += 4;
5346 } while (q <= last);
5347 }
5348 else {
5349 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005350 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005351 if (ch > maxch)
5352 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005353 if (kind != PyUnicode_1BYTE_KIND &&
5354 Py_UNICODE_IS_SURROGATE(ch))
5355 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005356 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005357 q += 4;
5358 } while (q <= last);
5359 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005360 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005361 }
5362
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005363 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005364 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005365 startinpos = ((const char *)q) - starts;
5366 endinpos = startinpos + 4;
5367 }
5368 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005369 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005370 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005371 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005372 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005373 startinpos = ((const char *)q) - starts;
5374 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005375 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005376 else {
5377 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005378 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005379 goto onError;
5380 q += 4;
5381 continue;
5382 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005383 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005384 startinpos = ((const char *)q) - starts;
5385 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005386 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005387
5388 /* The remaining input chars are ignored if the callback
5389 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005390 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005391 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005392 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005393 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005394 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005395 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005396 }
5397
Walter Dörwald41980ca2007-08-16 21:55:45 +00005398 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005399 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005400
Walter Dörwald41980ca2007-08-16 21:55:45 +00005401 Py_XDECREF(errorHandler);
5402 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005403 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005404
Benjamin Peterson29060642009-01-31 22:14:21 +00005405 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005406 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005407 Py_XDECREF(errorHandler);
5408 Py_XDECREF(exc);
5409 return NULL;
5410}
5411
5412PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005413_PyUnicode_EncodeUTF32(PyObject *str,
5414 const char *errors,
5415 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005416{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005417 enum PyUnicode_Kind kind;
5418 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005419 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005420 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005421 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005422#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005423 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005424#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005425 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005426#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005427 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005428 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005429 PyObject *errorHandler = NULL;
5430 PyObject *exc = NULL;
5431 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005432
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005433 if (!PyUnicode_Check(str)) {
5434 PyErr_BadArgument();
5435 return NULL;
5436 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005437 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005438 return NULL;
5439 kind = PyUnicode_KIND(str);
5440 data = PyUnicode_DATA(str);
5441 len = PyUnicode_GET_LENGTH(str);
5442
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005443 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005444 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005445 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005446 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005447 if (v == NULL)
5448 return NULL;
5449
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005450 /* output buffer is 4-bytes aligned */
5451 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005452 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005453 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005454 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005455 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005456 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005457
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005458 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005459 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005460 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005461 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005462 else
5463 encoding = "utf-32";
5464
5465 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005466 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5467 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005468 }
5469
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005470 pos = 0;
5471 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005472 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005473
5474 if (kind == PyUnicode_2BYTE_KIND) {
5475 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5476 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005477 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005478 else {
5479 assert(kind == PyUnicode_4BYTE_KIND);
5480 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5481 &out, native_ordering);
5482 }
5483 if (pos == len)
5484 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005485
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005486 rep = unicode_encode_call_errorhandler(
5487 errors, &errorHandler,
5488 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005489 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005490 if (!rep)
5491 goto error;
5492
5493 if (PyBytes_Check(rep)) {
5494 repsize = PyBytes_GET_SIZE(rep);
5495 if (repsize & 3) {
5496 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005497 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005498 "surrogates not allowed");
5499 goto error;
5500 }
5501 moreunits = repsize / 4;
5502 }
5503 else {
5504 assert(PyUnicode_Check(rep));
5505 if (PyUnicode_READY(rep) < 0)
5506 goto error;
5507 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5508 if (!PyUnicode_IS_ASCII(rep)) {
5509 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005510 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005511 "surrogates not allowed");
5512 goto error;
5513 }
5514 }
5515
5516 /* four bytes are reserved for each surrogate */
5517 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005518 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka82a90752017-07-11 07:27:56 +03005519 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005520 /* integer overflow */
5521 PyErr_NoMemory();
5522 goto error;
5523 }
Serhiy Storchaka82a90752017-07-11 07:27:56 +03005524 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005525 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005526 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005527 }
5528
5529 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005530 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005531 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005532 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005533 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005534 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5535 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005536 }
5537
5538 Py_CLEAR(rep);
5539 }
5540
5541 /* Cut back to size actually needed. This is necessary for, for example,
5542 encoding of a string containing isolated surrogates and the 'ignore'
5543 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005544 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005545 if (nsize != PyBytes_GET_SIZE(v))
5546 _PyBytes_Resize(&v, nsize);
5547 Py_XDECREF(errorHandler);
5548 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005549 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005550 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005551 error:
5552 Py_XDECREF(rep);
5553 Py_XDECREF(errorHandler);
5554 Py_XDECREF(exc);
5555 Py_XDECREF(v);
5556 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005557}
5558
Alexander Belopolsky40018472011-02-26 01:02:56 +00005559PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005560PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5561 Py_ssize_t size,
5562 const char *errors,
5563 int byteorder)
5564{
5565 PyObject *result;
5566 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5567 if (tmp == NULL)
5568 return NULL;
5569 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5570 Py_DECREF(tmp);
5571 return result;
5572}
5573
5574PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005575PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005576{
Victor Stinnerb960b342011-11-20 19:12:52 +01005577 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005578}
5579
Guido van Rossumd57fd912000-03-10 22:53:23 +00005580/* --- UTF-16 Codec ------------------------------------------------------- */
5581
Tim Peters772747b2001-08-09 22:21:55 +00005582PyObject *
5583PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005584 Py_ssize_t size,
5585 const char *errors,
5586 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005587{
Walter Dörwald69652032004-09-07 20:24:22 +00005588 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5589}
5590
5591PyObject *
5592PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005593 Py_ssize_t size,
5594 const char *errors,
5595 int *byteorder,
5596 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005597{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005598 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005599 Py_ssize_t startinpos;
5600 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005601 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005602 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005603 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005604 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005605 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005606 PyObject *errorHandler = NULL;
5607 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005608 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005609
Tim Peters772747b2001-08-09 22:21:55 +00005610 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005611 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005612
5613 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005614 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005616 /* Check for BOM marks (U+FEFF) in the input and adjust current
5617 byte order setting accordingly. In native mode, the leading BOM
5618 mark is skipped, in all other modes, it is copied to the output
5619 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005620 if (bo == 0 && size >= 2) {
5621 const Py_UCS4 bom = (q[1] << 8) | q[0];
5622 if (bom == 0xFEFF) {
5623 q += 2;
5624 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005625 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005626 else if (bom == 0xFFFE) {
5627 q += 2;
5628 bo = 1;
5629 }
5630 if (byteorder)
5631 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005632 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633
Antoine Pitrou63065d72012-05-15 23:48:04 +02005634 if (q == e) {
5635 if (consumed)
5636 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005637 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005638 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005639
Christian Heimes743e0cd2012-10-17 23:52:17 +02005640#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005641 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005642 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005643#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005644 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005645 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005646#endif
Tim Peters772747b2001-08-09 22:21:55 +00005647
Antoine Pitrou63065d72012-05-15 23:48:04 +02005648 /* Note: size will always be longer than the resulting Unicode
5649 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005650 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005651 writer.min_length = (e - q + 1) / 2;
5652 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005653 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005654
Antoine Pitrou63065d72012-05-15 23:48:04 +02005655 while (1) {
5656 Py_UCS4 ch = 0;
5657 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005658 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005659 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005660 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005661 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005662 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005663 native_ordering);
5664 else
5665 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005666 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005667 native_ordering);
5668 } else if (kind == PyUnicode_2BYTE_KIND) {
5669 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005670 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005671 native_ordering);
5672 } else {
5673 assert(kind == PyUnicode_4BYTE_KIND);
5674 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005675 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005676 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005677 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005678 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005679
Antoine Pitrou63065d72012-05-15 23:48:04 +02005680 switch (ch)
5681 {
5682 case 0:
5683 /* remaining byte at the end? (size should be even) */
5684 if (q == e || consumed)
5685 goto End;
5686 errmsg = "truncated data";
5687 startinpos = ((const char *)q) - starts;
5688 endinpos = ((const char *)e) - starts;
5689 break;
5690 /* The remaining input chars are ignored if the callback
5691 chooses to skip the input */
5692 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005693 q -= 2;
5694 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005695 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005696 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005697 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005698 endinpos = ((const char *)e) - starts;
5699 break;
5700 case 2:
5701 errmsg = "illegal encoding";
5702 startinpos = ((const char *)q) - 2 - starts;
5703 endinpos = startinpos + 2;
5704 break;
5705 case 3:
5706 errmsg = "illegal UTF-16 surrogate";
5707 startinpos = ((const char *)q) - 4 - starts;
5708 endinpos = startinpos + 2;
5709 break;
5710 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005711 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005712 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005713 continue;
5714 }
5715
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005716 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005717 errors,
5718 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005719 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005720 &starts,
5721 (const char **)&e,
5722 &startinpos,
5723 &endinpos,
5724 &exc,
5725 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005726 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005727 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728 }
5729
Antoine Pitrou63065d72012-05-15 23:48:04 +02005730End:
Walter Dörwald69652032004-09-07 20:24:22 +00005731 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005732 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005733
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005734 Py_XDECREF(errorHandler);
5735 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005736 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737
Benjamin Peterson29060642009-01-31 22:14:21 +00005738 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005739 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005740 Py_XDECREF(errorHandler);
5741 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742 return NULL;
5743}
5744
Tim Peters772747b2001-08-09 22:21:55 +00005745PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005746_PyUnicode_EncodeUTF16(PyObject *str,
5747 const char *errors,
5748 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005750 enum PyUnicode_Kind kind;
5751 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005752 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005753 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005754 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005755 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005756#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005757 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005758#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005759 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005760#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005761 const char *encoding;
5762 Py_ssize_t nsize, pos;
5763 PyObject *errorHandler = NULL;
5764 PyObject *exc = NULL;
5765 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005766
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005767 if (!PyUnicode_Check(str)) {
5768 PyErr_BadArgument();
5769 return NULL;
5770 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005771 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005772 return NULL;
5773 kind = PyUnicode_KIND(str);
5774 data = PyUnicode_DATA(str);
5775 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005776
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005777 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005778 if (kind == PyUnicode_4BYTE_KIND) {
5779 const Py_UCS4 *in = (const Py_UCS4 *)data;
5780 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005781 while (in < end) {
5782 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005783 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005784 }
5785 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005786 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005787 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005788 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005789 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005790 nsize = len + pairs + (byteorder == 0);
5791 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005792 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005793 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005794 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005795
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005796 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005797 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005798 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005799 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005800 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005801 }
5802 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005803 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005804 }
Tim Peters772747b2001-08-09 22:21:55 +00005805
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005806 if (kind == PyUnicode_1BYTE_KIND) {
5807 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5808 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005809 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005810
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005811 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005812 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005813 }
5814 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005815 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005816 }
5817 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005818 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005819 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005820
5821 pos = 0;
5822 while (pos < len) {
5823 Py_ssize_t repsize, moreunits;
5824
5825 if (kind == PyUnicode_2BYTE_KIND) {
5826 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5827 &out, native_ordering);
5828 }
5829 else {
5830 assert(kind == PyUnicode_4BYTE_KIND);
5831 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5832 &out, native_ordering);
5833 }
5834 if (pos == len)
5835 break;
5836
5837 rep = unicode_encode_call_errorhandler(
5838 errors, &errorHandler,
5839 encoding, "surrogates not allowed",
5840 str, &exc, pos, pos + 1, &pos);
5841 if (!rep)
5842 goto error;
5843
5844 if (PyBytes_Check(rep)) {
5845 repsize = PyBytes_GET_SIZE(rep);
5846 if (repsize & 1) {
5847 raise_encode_exception(&exc, encoding,
5848 str, pos - 1, pos,
5849 "surrogates not allowed");
5850 goto error;
5851 }
5852 moreunits = repsize / 2;
5853 }
5854 else {
5855 assert(PyUnicode_Check(rep));
5856 if (PyUnicode_READY(rep) < 0)
5857 goto error;
5858 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5859 if (!PyUnicode_IS_ASCII(rep)) {
5860 raise_encode_exception(&exc, encoding,
5861 str, pos - 1, pos,
5862 "surrogates not allowed");
5863 goto error;
5864 }
5865 }
5866
5867 /* two bytes are reserved for each surrogate */
5868 if (moreunits > 1) {
5869 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka82a90752017-07-11 07:27:56 +03005870 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005871 /* integer overflow */
5872 PyErr_NoMemory();
5873 goto error;
5874 }
Serhiy Storchaka82a90752017-07-11 07:27:56 +03005875 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005876 goto error;
5877 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5878 }
5879
5880 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005881 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005882 out += moreunits;
5883 } else /* rep is unicode */ {
5884 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5885 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5886 &out, native_ordering);
5887 }
5888
5889 Py_CLEAR(rep);
5890 }
5891
5892 /* Cut back to size actually needed. This is necessary for, for example,
5893 encoding of a string containing isolated surrogates and the 'ignore' handler
5894 is used. */
5895 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5896 if (nsize != PyBytes_GET_SIZE(v))
5897 _PyBytes_Resize(&v, nsize);
5898 Py_XDECREF(errorHandler);
5899 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005900 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005901 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005902 error:
5903 Py_XDECREF(rep);
5904 Py_XDECREF(errorHandler);
5905 Py_XDECREF(exc);
5906 Py_XDECREF(v);
5907 return NULL;
5908#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005909}
5910
Alexander Belopolsky40018472011-02-26 01:02:56 +00005911PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005912PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5913 Py_ssize_t size,
5914 const char *errors,
5915 int byteorder)
5916{
5917 PyObject *result;
5918 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5919 if (tmp == NULL)
5920 return NULL;
5921 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5922 Py_DECREF(tmp);
5923 return result;
5924}
5925
5926PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005927PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005929 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005930}
5931
5932/* --- Unicode Escape Codec ----------------------------------------------- */
5933
Fredrik Lundh06d12682001-01-24 07:59:11 +00005934static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005935
Alexander Belopolsky40018472011-02-26 01:02:56 +00005936PyObject *
Eric V. Smith56466482016-10-31 14:46:26 -04005937_PyUnicode_DecodeUnicodeEscape(const char *s,
5938 Py_ssize_t size,
5939 const char *errors,
5940 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005942 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005943 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005944 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005945 PyObject *errorHandler = NULL;
5946 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005947
Eric V. Smith56466482016-10-31 14:46:26 -04005948 // so we can remember if we've seen an invalid escape char or not
5949 *first_invalid_escape = NULL;
5950
Victor Stinner62ec3312016-09-06 17:04:34 -07005951 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005952 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005953 }
5954 /* Escaped strings will always be longer than the resulting
5955 Unicode string, so we start with size here and then reduce the
5956 length after conversion to the true value.
5957 (but if the error callback returns a long replacement string
5958 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005959 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005960 writer.min_length = size;
5961 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5962 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005963 }
5964
Guido van Rossumd57fd912000-03-10 22:53:23 +00005965 end = s + size;
5966 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005967 unsigned char c = (unsigned char) *s++;
5968 Py_UCS4 ch;
5969 int count;
5970 Py_ssize_t startinpos;
5971 Py_ssize_t endinpos;
5972 const char *message;
5973
5974#define WRITE_ASCII_CHAR(ch) \
5975 do { \
5976 assert(ch <= 127); \
5977 assert(writer.pos < writer.size); \
5978 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5979 } while(0)
5980
5981#define WRITE_CHAR(ch) \
5982 do { \
5983 if (ch <= writer.maxchar) { \
5984 assert(writer.pos < writer.size); \
5985 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5986 } \
5987 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5988 goto onError; \
5989 } \
5990 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005991
5992 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005993 if (c != '\\') {
5994 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995 continue;
5996 }
5997
Victor Stinner62ec3312016-09-06 17:04:34 -07005998 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006000 if (s >= end) {
6001 message = "\\ at end of string";
6002 goto error;
6003 }
6004 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006005
Victor Stinner62ec3312016-09-06 17:04:34 -07006006 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006007 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008
Benjamin Peterson29060642009-01-31 22:14:21 +00006009 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006010 case '\n': continue;
6011 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6012 case '\'': WRITE_ASCII_CHAR('\''); continue;
6013 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6014 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006015 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006016 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6017 case 't': WRITE_ASCII_CHAR('\t'); continue;
6018 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6019 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006020 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006021 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006022 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006023 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006024
Benjamin Peterson29060642009-01-31 22:14:21 +00006025 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006026 case '0': case '1': case '2': case '3':
6027 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006028 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006029 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006030 ch = (ch<<3) + *s++ - '0';
6031 if (s < end && '0' <= *s && *s <= '7') {
6032 ch = (ch<<3) + *s++ - '0';
6033 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006034 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006035 WRITE_CHAR(ch);
6036 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037
Benjamin Peterson29060642009-01-31 22:14:21 +00006038 /* hex escapes */
6039 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006040 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006041 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006042 message = "truncated \\xXX escape";
6043 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044
Benjamin Peterson29060642009-01-31 22:14:21 +00006045 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006046 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006047 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006048 message = "truncated \\uXXXX escape";
6049 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006050
Benjamin Peterson29060642009-01-31 22:14:21 +00006051 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006052 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006053 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006054 message = "truncated \\UXXXXXXXX escape";
6055 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006056 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006057 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006058 ch <<= 4;
6059 if (c >= '0' && c <= '9') {
6060 ch += c - '0';
6061 }
6062 else if (c >= 'a' && c <= 'f') {
6063 ch += c - ('a' - 10);
6064 }
6065 else if (c >= 'A' && c <= 'F') {
6066 ch += c - ('A' - 10);
6067 }
6068 else {
6069 break;
6070 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006071 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006072 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006073 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006074 }
6075
6076 /* when we get here, ch is a 32-bit unicode character */
6077 if (ch > MAX_UNICODE) {
6078 message = "illegal Unicode character";
6079 goto error;
6080 }
6081
6082 WRITE_CHAR(ch);
6083 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006084
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006086 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006087 if (ucnhash_CAPI == NULL) {
6088 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006089 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6090 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006091 if (ucnhash_CAPI == NULL) {
6092 PyErr_SetString(
6093 PyExc_UnicodeError,
6094 "\\N escapes not supported (can't load unicodedata module)"
6095 );
6096 goto onError;
6097 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006098 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006099
6100 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006101 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006102 const char *start = ++s;
6103 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006104 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006105 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006106 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006107 namelen = s - start;
6108 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006109 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006110 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006111 ch = 0xffffffff; /* in case 'getcode' messes up */
6112 if (namelen <= INT_MAX &&
6113 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6114 &ch, 0)) {
6115 assert(ch <= MAX_UNICODE);
6116 WRITE_CHAR(ch);
6117 continue;
6118 }
6119 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006120 }
6121 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006122 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006123
6124 default:
Eric V. Smith56466482016-10-31 14:46:26 -04006125 if (*first_invalid_escape == NULL) {
6126 *first_invalid_escape = s-1; /* Back up one char, since we've
6127 already incremented s. */
6128 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006129 WRITE_ASCII_CHAR('\\');
6130 WRITE_CHAR(c);
6131 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006132 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006133
6134 error:
6135 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006136 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006137 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006138 errors, &errorHandler,
6139 "unicodeescape", message,
6140 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006141 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006142 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006143 }
6144 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6145 goto onError;
6146 }
6147
6148#undef WRITE_ASCII_CHAR
6149#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006150 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006151
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006152 Py_XDECREF(errorHandler);
6153 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006154 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006155
Benjamin Peterson29060642009-01-31 22:14:21 +00006156 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006157 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006158 Py_XDECREF(errorHandler);
6159 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006160 return NULL;
6161}
6162
Eric V. Smith56466482016-10-31 14:46:26 -04006163PyObject *
6164PyUnicode_DecodeUnicodeEscape(const char *s,
6165 Py_ssize_t size,
6166 const char *errors)
6167{
6168 const char *first_invalid_escape;
6169 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6170 &first_invalid_escape);
6171 if (result == NULL)
6172 return NULL;
6173 if (first_invalid_escape != NULL) {
6174 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6175 "invalid escape sequence '\\%c'",
6176 *first_invalid_escape) < 0) {
6177 Py_DECREF(result);
6178 return NULL;
6179 }
6180 }
6181 return result;
6182}
6183
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006184/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006185
Alexander Belopolsky40018472011-02-26 01:02:56 +00006186PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006187PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006189 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006190 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006192 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006194 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195
Ezio Melottie7f90372012-10-05 03:33:31 +03006196 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006197 escape.
6198
Ezio Melottie7f90372012-10-05 03:33:31 +03006199 For UCS1 strings it's '\xxx', 4 bytes per source character.
6200 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6201 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006202 */
6203
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006204 if (!PyUnicode_Check(unicode)) {
6205 PyErr_BadArgument();
6206 return NULL;
6207 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006208 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006209 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006210 }
Victor Stinner358af132015-10-12 22:36:57 +02006211
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006212 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006213 if (len == 0) {
6214 return PyBytes_FromStringAndSize(NULL, 0);
6215 }
6216
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006217 kind = PyUnicode_KIND(unicode);
6218 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006219 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6220 bytes, and 1 byte characters 4. */
6221 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006222 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006223 return PyErr_NoMemory();
6224 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006225 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006226 if (repr == NULL) {
6227 return NULL;
6228 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006229
Victor Stinner62ec3312016-09-06 17:04:34 -07006230 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006231 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006232 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006233
Victor Stinner62ec3312016-09-06 17:04:34 -07006234 /* U+0000-U+00ff range */
6235 if (ch < 0x100) {
6236 if (ch >= ' ' && ch < 127) {
6237 if (ch != '\\') {
6238 /* Copy printable US ASCII as-is */
6239 *p++ = (char) ch;
6240 }
6241 /* Escape backslashes */
6242 else {
6243 *p++ = '\\';
6244 *p++ = '\\';
6245 }
6246 }
Victor Stinner358af132015-10-12 22:36:57 +02006247
Victor Stinner62ec3312016-09-06 17:04:34 -07006248 /* Map special whitespace to '\t', \n', '\r' */
6249 else if (ch == '\t') {
6250 *p++ = '\\';
6251 *p++ = 't';
6252 }
6253 else if (ch == '\n') {
6254 *p++ = '\\';
6255 *p++ = 'n';
6256 }
6257 else if (ch == '\r') {
6258 *p++ = '\\';
6259 *p++ = 'r';
6260 }
6261
6262 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6263 else {
6264 *p++ = '\\';
6265 *p++ = 'x';
6266 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6267 *p++ = Py_hexdigits[ch & 0x000F];
6268 }
Tim Petersced69f82003-09-16 20:30:58 +00006269 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006270 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006271 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006272 *p++ = '\\';
6273 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006274 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6275 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6276 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6277 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006278 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006279 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6280 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006281
Victor Stinner62ec3312016-09-06 17:04:34 -07006282 /* Make sure that the first two digits are zero */
6283 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006284 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006285 *p++ = 'U';
6286 *p++ = '0';
6287 *p++ = '0';
6288 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6289 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6290 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6291 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6292 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6293 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006294 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006295 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006296
Victor Stinner62ec3312016-09-06 17:04:34 -07006297 assert(p - PyBytes_AS_STRING(repr) > 0);
6298 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6299 return NULL;
6300 }
6301 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006302}
6303
Alexander Belopolsky40018472011-02-26 01:02:56 +00006304PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006305PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6306 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006307{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006308 PyObject *result;
6309 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006310 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006311 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006312 }
6313
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006314 result = PyUnicode_AsUnicodeEscapeString(tmp);
6315 Py_DECREF(tmp);
6316 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006317}
6318
6319/* --- Raw Unicode Escape Codec ------------------------------------------- */
6320
Alexander Belopolsky40018472011-02-26 01:02:56 +00006321PyObject *
6322PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006323 Py_ssize_t size,
6324 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006325{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006326 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006327 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006328 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006329 PyObject *errorHandler = NULL;
6330 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006331
Victor Stinner62ec3312016-09-06 17:04:34 -07006332 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006333 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006334 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006335
Guido van Rossumd57fd912000-03-10 22:53:23 +00006336 /* Escaped strings will always be longer than the resulting
6337 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006338 length after conversion to the true value. (But decoding error
6339 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006340 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006341 writer.min_length = size;
6342 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6343 goto onError;
6344 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006345
Guido van Rossumd57fd912000-03-10 22:53:23 +00006346 end = s + size;
6347 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006348 unsigned char c = (unsigned char) *s++;
6349 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006350 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006351 Py_ssize_t startinpos;
6352 Py_ssize_t endinpos;
6353 const char *message;
6354
6355#define WRITE_CHAR(ch) \
6356 do { \
6357 if (ch <= writer.maxchar) { \
6358 assert(writer.pos < writer.size); \
6359 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6360 } \
6361 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6362 goto onError; \
6363 } \
6364 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006365
Benjamin Peterson29060642009-01-31 22:14:21 +00006366 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006367 if (c != '\\' || s >= end) {
6368 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006369 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006370 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006371
Victor Stinner62ec3312016-09-06 17:04:34 -07006372 c = (unsigned char) *s++;
6373 if (c == 'u') {
6374 count = 4;
6375 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006376 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006377 else if (c == 'U') {
6378 count = 8;
6379 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006380 }
6381 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006382 assert(writer.pos < writer.size);
6383 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6384 WRITE_CHAR(c);
6385 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006386 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006387 startinpos = s - starts - 2;
6388
6389 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6390 for (ch = 0; count && s < end; ++s, --count) {
6391 c = (unsigned char)*s;
6392 ch <<= 4;
6393 if (c >= '0' && c <= '9') {
6394 ch += c - '0';
6395 }
6396 else if (c >= 'a' && c <= 'f') {
6397 ch += c - ('a' - 10);
6398 }
6399 else if (c >= 'A' && c <= 'F') {
6400 ch += c - ('A' - 10);
6401 }
6402 else {
6403 break;
6404 }
6405 }
6406 if (!count) {
6407 if (ch <= MAX_UNICODE) {
6408 WRITE_CHAR(ch);
6409 continue;
6410 }
6411 message = "\\Uxxxxxxxx out of range";
6412 }
6413
6414 endinpos = s-starts;
6415 writer.min_length = end - s + writer.pos;
6416 if (unicode_decode_call_errorhandler_writer(
6417 errors, &errorHandler,
6418 "rawunicodeescape", message,
6419 &starts, &end, &startinpos, &endinpos, &exc, &s,
6420 &writer)) {
6421 goto onError;
6422 }
6423 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6424 goto onError;
6425 }
6426
6427#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006428 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006429 Py_XDECREF(errorHandler);
6430 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006431 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006432
Benjamin Peterson29060642009-01-31 22:14:21 +00006433 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006434 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006435 Py_XDECREF(errorHandler);
6436 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006437 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006438
Guido van Rossumd57fd912000-03-10 22:53:23 +00006439}
6440
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006441
Alexander Belopolsky40018472011-02-26 01:02:56 +00006442PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006443PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006444{
Victor Stinner62ec3312016-09-06 17:04:34 -07006445 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006446 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006447 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006448 int kind;
6449 void *data;
6450 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006451
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006452 if (!PyUnicode_Check(unicode)) {
6453 PyErr_BadArgument();
6454 return NULL;
6455 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006456 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006457 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006458 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006459 kind = PyUnicode_KIND(unicode);
6460 data = PyUnicode_DATA(unicode);
6461 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006462 if (kind == PyUnicode_1BYTE_KIND) {
6463 return PyBytes_FromStringAndSize(data, len);
6464 }
Victor Stinner0e368262011-11-10 20:12:49 +01006465
Victor Stinner62ec3312016-09-06 17:04:34 -07006466 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6467 bytes, and 1 byte characters 4. */
6468 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006469
Victor Stinner62ec3312016-09-06 17:04:34 -07006470 if (len > PY_SSIZE_T_MAX / expandsize) {
6471 return PyErr_NoMemory();
6472 }
6473 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6474 if (repr == NULL) {
6475 return NULL;
6476 }
6477 if (len == 0) {
6478 return repr;
6479 }
6480
6481 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006482 for (pos = 0; pos < len; pos++) {
6483 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006484
Victor Stinner62ec3312016-09-06 17:04:34 -07006485 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6486 if (ch < 0x100) {
6487 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006488 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006489 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6490 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006491 *p++ = '\\';
6492 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006493 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6494 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6495 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6496 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006497 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006498 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6499 else {
6500 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6501 *p++ = '\\';
6502 *p++ = 'U';
6503 *p++ = '0';
6504 *p++ = '0';
6505 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6506 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6507 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6508 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6509 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6510 *p++ = Py_hexdigits[ch & 15];
6511 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006512 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006513
Victor Stinner62ec3312016-09-06 17:04:34 -07006514 assert(p > PyBytes_AS_STRING(repr));
6515 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6516 return NULL;
6517 }
6518 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519}
6520
Alexander Belopolsky40018472011-02-26 01:02:56 +00006521PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006522PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6523 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006524{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006525 PyObject *result;
6526 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6527 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006528 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006529 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6530 Py_DECREF(tmp);
6531 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006532}
6533
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006534/* --- Unicode Internal Codec ------------------------------------------- */
6535
Alexander Belopolsky40018472011-02-26 01:02:56 +00006536PyObject *
6537_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006538 Py_ssize_t size,
6539 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006540{
6541 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006542 Py_ssize_t startinpos;
6543 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006544 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006545 const char *end;
6546 const char *reason;
6547 PyObject *errorHandler = NULL;
6548 PyObject *exc = NULL;
6549
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006550 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006551 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006552 1))
6553 return NULL;
6554
Serhiy Storchaka82a90752017-07-11 07:27:56 +03006555 if (size < 0) {
6556 PyErr_BadInternalCall();
6557 return NULL;
6558 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006559 if (size == 0)
6560 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006561
Victor Stinner8f674cc2013-04-17 23:02:17 +02006562 _PyUnicodeWriter_Init(&writer);
6563 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6564 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006565 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006566 }
6567 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006568
Victor Stinner8f674cc2013-04-17 23:02:17 +02006569 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006570 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006571 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006572 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006573 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006574 endinpos = end-starts;
6575 reason = "truncated input";
6576 goto error;
6577 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006578 /* We copy the raw representation one byte at a time because the
6579 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006580 ((char *) &uch)[0] = s[0];
6581 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006582#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006583 ((char *) &uch)[2] = s[2];
6584 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006585#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006586 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006587#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006588 /* We have to sanity check the raw data, otherwise doom looms for
6589 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006590 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006591 endinpos = s - starts + Py_UNICODE_SIZE;
6592 reason = "illegal code point (> 0x10FFFF)";
6593 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006594 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006595#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006596 s += Py_UNICODE_SIZE;
6597#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006598 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006599 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006600 Py_UNICODE uch2;
6601 ((char *) &uch2)[0] = s[0];
6602 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006603 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006604 {
Victor Stinner551ac952011-11-29 22:58:13 +01006605 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006606 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006607 }
6608 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006609#endif
6610
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006611 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006612 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006613 continue;
6614
6615 error:
6616 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006617 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006618 errors, &errorHandler,
6619 "unicode_internal", reason,
6620 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006621 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006622 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006623 }
6624
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006625 Py_XDECREF(errorHandler);
6626 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006627 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006628
Benjamin Peterson29060642009-01-31 22:14:21 +00006629 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006630 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006631 Py_XDECREF(errorHandler);
6632 Py_XDECREF(exc);
6633 return NULL;
6634}
6635
Guido van Rossumd57fd912000-03-10 22:53:23 +00006636/* --- Latin-1 Codec ------------------------------------------------------ */
6637
Alexander Belopolsky40018472011-02-26 01:02:56 +00006638PyObject *
6639PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006640 Py_ssize_t size,
6641 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006642{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006643 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006644 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006645}
6646
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006647/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006648static void
6649make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006650 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006651 PyObject *unicode,
6652 Py_ssize_t startpos, Py_ssize_t endpos,
6653 const char *reason)
6654{
6655 if (*exceptionObject == NULL) {
6656 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006657 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006658 encoding, unicode, startpos, endpos, reason);
6659 }
6660 else {
6661 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6662 goto onError;
6663 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6664 goto onError;
6665 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6666 goto onError;
6667 return;
6668 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006669 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006670 }
6671}
6672
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006673/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006674static void
6675raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006676 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006677 PyObject *unicode,
6678 Py_ssize_t startpos, Py_ssize_t endpos,
6679 const char *reason)
6680{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006681 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006682 encoding, unicode, startpos, endpos, reason);
6683 if (*exceptionObject != NULL)
6684 PyCodec_StrictErrors(*exceptionObject);
6685}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006686
6687/* error handling callback helper:
6688 build arguments, call the callback and check the arguments,
6689 put the result into newpos and return the replacement string, which
6690 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006691static PyObject *
6692unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006693 PyObject **errorHandler,
6694 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006695 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006696 Py_ssize_t startpos, Py_ssize_t endpos,
6697 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006698{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006699 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006700 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006701 PyObject *restuple;
6702 PyObject *resunicode;
6703
6704 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006706 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006707 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006708 }
6709
Benjamin Petersonbac79492012-01-14 13:34:47 -05006710 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006711 return NULL;
6712 len = PyUnicode_GET_LENGTH(unicode);
6713
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006714 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006715 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006717 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006718
6719 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006721 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006723 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006724 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 Py_DECREF(restuple);
6726 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006727 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006728 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 &resunicode, newpos)) {
6730 Py_DECREF(restuple);
6731 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006732 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006733 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6734 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6735 Py_DECREF(restuple);
6736 return NULL;
6737 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006738 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006739 *newpos = len + *newpos;
6740 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006741 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 Py_DECREF(restuple);
6743 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006744 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006745 Py_INCREF(resunicode);
6746 Py_DECREF(restuple);
6747 return resunicode;
6748}
6749
Alexander Belopolsky40018472011-02-26 01:02:56 +00006750static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006751unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006752 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006753 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006754{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006755 /* input state */
6756 Py_ssize_t pos=0, size;
6757 int kind;
6758 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006759 /* pointer into the output */
6760 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006761 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6762 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006763 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006764 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006765 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006766 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006767 /* output object */
6768 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006769
Benjamin Petersonbac79492012-01-14 13:34:47 -05006770 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006771 return NULL;
6772 size = PyUnicode_GET_LENGTH(unicode);
6773 kind = PyUnicode_KIND(unicode);
6774 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006775 /* allocate enough for a simple encoding without
6776 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006777 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006778 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006779
6780 _PyBytesWriter_Init(&writer);
6781 str = _PyBytesWriter_Alloc(&writer, size);
6782 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006783 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006784
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006785 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006786 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006787
Benjamin Peterson29060642009-01-31 22:14:21 +00006788 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006789 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006790 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006791 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006792 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006793 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006794 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006795 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006797 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006798 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006799 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006800
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006801 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006802 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006803
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006804 /* Only overallocate the buffer if it's not the last write */
6805 writer.overallocate = (collend < size);
6806
Benjamin Peterson29060642009-01-31 22:14:21 +00006807 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006808 if (error_handler == _Py_ERROR_UNKNOWN)
6809 error_handler = get_error_handler(errors);
6810
6811 switch (error_handler) {
6812 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006813 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006814 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006815
6816 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006817 memset(str, '?', collend - collstart);
6818 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006819 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006820 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006821 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006822 break;
Victor Stinner50149202015-09-22 00:26:54 +02006823
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006824 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006825 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006826 writer.min_size -= (collend - collstart);
6827 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006828 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006829 if (str == NULL)
6830 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006831 pos = collend;
6832 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006833
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006834 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006835 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006836 writer.min_size -= (collend - collstart);
6837 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006838 unicode, collstart, collend);
6839 if (str == NULL)
6840 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006841 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006842 break;
Victor Stinner50149202015-09-22 00:26:54 +02006843
Victor Stinnerc3713e92015-09-29 12:32:13 +02006844 case _Py_ERROR_SURROGATEESCAPE:
6845 for (i = collstart; i < collend; ++i) {
6846 ch = PyUnicode_READ(kind, data, i);
6847 if (ch < 0xdc80 || 0xdcff < ch) {
6848 /* Not a UTF-8b surrogate */
6849 break;
6850 }
6851 *str++ = (char)(ch - 0xdc00);
6852 ++pos;
6853 }
6854 if (i >= collend)
6855 break;
6856 collstart = pos;
6857 assert(collstart != collend);
6858 /* fallback to general error handling */
6859
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006861 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6862 encoding, reason, unicode, &exc,
6863 collstart, collend, &newpos);
6864 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006865 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006866
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006867 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006868 writer.min_size -= 1;
6869
Victor Stinner6bd525b2015-10-09 13:10:05 +02006870 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006871 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006872 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006873 PyBytes_AS_STRING(rep),
6874 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006875 if (str == NULL)
6876 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006877 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006878 else {
6879 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006880
Victor Stinner6bd525b2015-10-09 13:10:05 +02006881 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006882 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006883
6884 if (PyUnicode_IS_ASCII(rep)) {
6885 /* Fast path: all characters are smaller than limit */
6886 assert(limit >= 128);
6887 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6888 str = _PyBytesWriter_WriteBytes(&writer, str,
6889 PyUnicode_DATA(rep),
6890 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006891 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006892 else {
6893 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6894
6895 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6896 if (str == NULL)
6897 goto onError;
6898
6899 /* check if there is anything unencodable in the
6900 replacement and copy it to the output */
6901 for (i = 0; repsize-->0; ++i, ++str) {
6902 ch = PyUnicode_READ_CHAR(rep, i);
6903 if (ch >= limit) {
6904 raise_encode_exception(&exc, encoding, unicode,
6905 pos, pos+1, reason);
6906 goto onError;
6907 }
6908 *str = (char)ch;
6909 }
6910 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006911 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006912 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006913 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006914 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006915
6916 /* If overallocation was disabled, ensure that it was the last
6917 write. Otherwise, we missed an optimization */
6918 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006919 }
6920 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006921
Victor Stinner50149202015-09-22 00:26:54 +02006922 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006923 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006924 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006925
6926 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006927 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006928 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006929 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006930 Py_XDECREF(exc);
6931 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006932}
6933
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006934/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006935PyObject *
6936PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006937 Py_ssize_t size,
6938 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006939{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006940 PyObject *result;
6941 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6942 if (unicode == NULL)
6943 return NULL;
6944 result = unicode_encode_ucs1(unicode, errors, 256);
6945 Py_DECREF(unicode);
6946 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006947}
6948
Alexander Belopolsky40018472011-02-26 01:02:56 +00006949PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006950_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006951{
6952 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006953 PyErr_BadArgument();
6954 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006955 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006956 if (PyUnicode_READY(unicode) == -1)
6957 return NULL;
6958 /* Fast path: if it is a one-byte string, construct
6959 bytes object directly. */
6960 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6961 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6962 PyUnicode_GET_LENGTH(unicode));
6963 /* Non-Latin-1 characters present. Defer to above function to
6964 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006965 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006966}
6967
6968PyObject*
6969PyUnicode_AsLatin1String(PyObject *unicode)
6970{
6971 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006972}
6973
6974/* --- 7-bit ASCII Codec -------------------------------------------------- */
6975
Alexander Belopolsky40018472011-02-26 01:02:56 +00006976PyObject *
6977PyUnicode_DecodeASCII(const char *s,
6978 Py_ssize_t size,
6979 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006980{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006981 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006982 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006983 int kind;
6984 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006985 Py_ssize_t startinpos;
6986 Py_ssize_t endinpos;
6987 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006988 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006989 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006990 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006991 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006992
Guido van Rossumd57fd912000-03-10 22:53:23 +00006993 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006994 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006995
Guido van Rossumd57fd912000-03-10 22:53:23 +00006996 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006997 if (size == 1 && (unsigned char)s[0] < 128)
6998 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006999
Victor Stinner8f674cc2013-04-17 23:02:17 +02007000 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007001 writer.min_length = size;
7002 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02007003 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007004
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007005 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007006 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007007 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007008 writer.pos = outpos;
7009 if (writer.pos == size)
7010 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007011
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007012 s += writer.pos;
7013 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007014 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02007015 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00007016 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007017 PyUnicode_WRITE(kind, data, writer.pos, c);
7018 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007019 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007020 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00007021 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007022
7023 /* byte outsize range 0x00..0x7f: call the error handler */
7024
7025 if (error_handler == _Py_ERROR_UNKNOWN)
7026 error_handler = get_error_handler(errors);
7027
7028 switch (error_handler)
7029 {
7030 case _Py_ERROR_REPLACE:
7031 case _Py_ERROR_SURROGATEESCAPE:
7032 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02007033 but we may switch to UCS2 at the first write */
7034 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7035 goto onError;
7036 kind = writer.kind;
7037 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007038
7039 if (error_handler == _Py_ERROR_REPLACE)
7040 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7041 else
7042 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7043 writer.pos++;
7044 ++s;
7045 break;
7046
7047 case _Py_ERROR_IGNORE:
7048 ++s;
7049 break;
7050
7051 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007052 startinpos = s-starts;
7053 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007054 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007055 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007056 "ascii", "ordinal not in range(128)",
7057 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007058 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007059 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007060 kind = writer.kind;
7061 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007062 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007063 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007064 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007065 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007066 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007067
Benjamin Peterson29060642009-01-31 22:14:21 +00007068 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007069 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007070 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007071 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007072 return NULL;
7073}
7074
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007075/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007076PyObject *
7077PyUnicode_EncodeASCII(const Py_UNICODE *p,
7078 Py_ssize_t size,
7079 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007080{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007081 PyObject *result;
7082 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7083 if (unicode == NULL)
7084 return NULL;
7085 result = unicode_encode_ucs1(unicode, errors, 128);
7086 Py_DECREF(unicode);
7087 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007088}
7089
Alexander Belopolsky40018472011-02-26 01:02:56 +00007090PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007091_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007092{
7093 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007094 PyErr_BadArgument();
7095 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007096 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007097 if (PyUnicode_READY(unicode) == -1)
7098 return NULL;
7099 /* Fast path: if it is an ASCII-only string, construct bytes object
7100 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007101 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007102 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7103 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007104 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007105}
7106
7107PyObject *
7108PyUnicode_AsASCIIString(PyObject *unicode)
7109{
7110 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007111}
7112
Steve Dowercc16be82016-09-08 10:35:16 -07007113#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007114
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007115/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007116
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007117#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007118#define NEED_RETRY
7119#endif
7120
Victor Stinner3a50e702011-10-18 21:21:00 +02007121#ifndef WC_ERR_INVALID_CHARS
7122# define WC_ERR_INVALID_CHARS 0x0080
7123#endif
7124
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007125static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007126code_page_name(UINT code_page, PyObject **obj)
7127{
7128 *obj = NULL;
7129 if (code_page == CP_ACP)
7130 return "mbcs";
7131 if (code_page == CP_UTF7)
7132 return "CP_UTF7";
7133 if (code_page == CP_UTF8)
7134 return "CP_UTF8";
7135
7136 *obj = PyBytes_FromFormat("cp%u", code_page);
7137 if (*obj == NULL)
7138 return NULL;
7139 return PyBytes_AS_STRING(*obj);
7140}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007141
Victor Stinner3a50e702011-10-18 21:21:00 +02007142static DWORD
7143decode_code_page_flags(UINT code_page)
7144{
7145 if (code_page == CP_UTF7) {
7146 /* The CP_UTF7 decoder only supports flags=0 */
7147 return 0;
7148 }
7149 else
7150 return MB_ERR_INVALID_CHARS;
7151}
7152
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007153/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007154 * Decode a byte string from a Windows code page into unicode object in strict
7155 * mode.
7156 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007157 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7158 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007159 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007160static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007161decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007162 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 const char *in,
7164 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007165{
Victor Stinner3a50e702011-10-18 21:21:00 +02007166 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007167 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007168 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007169
7170 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007171 assert(insize > 0);
7172 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7173 if (outsize <= 0)
7174 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007175
7176 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007177 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007178 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007179 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007180 if (*v == NULL)
7181 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007182 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007183 }
7184 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007185 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007186 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007187 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007188 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007189 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007190 }
7191
7192 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7194 if (outsize <= 0)
7195 goto error;
7196 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007197
Victor Stinner3a50e702011-10-18 21:21:00 +02007198error:
7199 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7200 return -2;
7201 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007202 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007203}
7204
Victor Stinner3a50e702011-10-18 21:21:00 +02007205/*
7206 * Decode a byte string from a code page into unicode object with an error
7207 * handler.
7208 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007209 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007210 * UnicodeDecodeError exception and returns -1 on error.
7211 */
7212static int
7213decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007214 PyObject **v,
7215 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007216 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007217{
7218 const char *startin = in;
7219 const char *endin = in + size;
7220 const DWORD flags = decode_code_page_flags(code_page);
7221 /* Ideally, we should get reason from FormatMessage. This is the Windows
7222 2000 English version of the message. */
7223 const char *reason = "No mapping for the Unicode character exists "
7224 "in the target code page.";
7225 /* each step cannot decode more than 1 character, but a character can be
7226 represented as a surrogate pair */
7227 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007228 int insize;
7229 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007230 PyObject *errorHandler = NULL;
7231 PyObject *exc = NULL;
7232 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007233 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007234 DWORD err;
7235 int ret = -1;
7236
7237 assert(size > 0);
7238
7239 encoding = code_page_name(code_page, &encoding_obj);
7240 if (encoding == NULL)
7241 return -1;
7242
Victor Stinner7d00cc12014-03-17 23:08:06 +01007243 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7245 UnicodeDecodeError. */
7246 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7247 if (exc != NULL) {
7248 PyCodec_StrictErrors(exc);
7249 Py_CLEAR(exc);
7250 }
7251 goto error;
7252 }
7253
7254 if (*v == NULL) {
7255 /* Create unicode object */
7256 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7257 PyErr_NoMemory();
7258 goto error;
7259 }
Victor Stinnerab595942011-12-17 04:59:06 +01007260 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007261 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007262 if (*v == NULL)
7263 goto error;
7264 startout = PyUnicode_AS_UNICODE(*v);
7265 }
7266 else {
7267 /* Extend unicode object */
7268 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7269 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7270 PyErr_NoMemory();
7271 goto error;
7272 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007273 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007274 goto error;
7275 startout = PyUnicode_AS_UNICODE(*v) + n;
7276 }
7277
7278 /* Decode the byte string character per character */
7279 out = startout;
7280 while (in < endin)
7281 {
7282 /* Decode a character */
7283 insize = 1;
7284 do
7285 {
7286 outsize = MultiByteToWideChar(code_page, flags,
7287 in, insize,
7288 buffer, Py_ARRAY_LENGTH(buffer));
7289 if (outsize > 0)
7290 break;
7291 err = GetLastError();
7292 if (err != ERROR_NO_UNICODE_TRANSLATION
7293 && err != ERROR_INSUFFICIENT_BUFFER)
7294 {
7295 PyErr_SetFromWindowsErr(0);
7296 goto error;
7297 }
7298 insize++;
7299 }
7300 /* 4=maximum length of a UTF-8 sequence */
7301 while (insize <= 4 && (in + insize) <= endin);
7302
7303 if (outsize <= 0) {
7304 Py_ssize_t startinpos, endinpos, outpos;
7305
Victor Stinner7d00cc12014-03-17 23:08:06 +01007306 /* last character in partial decode? */
7307 if (in + insize >= endin && !final)
7308 break;
7309
Victor Stinner3a50e702011-10-18 21:21:00 +02007310 startinpos = in - startin;
7311 endinpos = startinpos + 1;
7312 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007313 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007314 errors, &errorHandler,
7315 encoding, reason,
7316 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007317 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007318 {
7319 goto error;
7320 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007321 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007322 }
7323 else {
7324 in += insize;
7325 memcpy(out, buffer, outsize * sizeof(wchar_t));
7326 out += outsize;
7327 }
7328 }
7329
7330 /* write a NUL character at the end */
7331 *out = 0;
7332
7333 /* Extend unicode object */
7334 outsize = out - startout;
7335 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007336 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007337 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007338 /* (in - startin) <= size and size is an int */
7339 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007340
7341error:
7342 Py_XDECREF(encoding_obj);
7343 Py_XDECREF(errorHandler);
7344 Py_XDECREF(exc);
7345 return ret;
7346}
7347
Victor Stinner3a50e702011-10-18 21:21:00 +02007348static PyObject *
7349decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007350 const char *s, Py_ssize_t size,
7351 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007352{
Victor Stinner76a31a62011-11-04 00:05:13 +01007353 PyObject *v = NULL;
7354 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007355
Victor Stinner3a50e702011-10-18 21:21:00 +02007356 if (code_page < 0) {
7357 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7358 return NULL;
7359 }
Serhiy Storchaka82a90752017-07-11 07:27:56 +03007360 if (size < 0) {
7361 PyErr_BadInternalCall();
7362 return NULL;
7363 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007364
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007365 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007366 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007367
Victor Stinner76a31a62011-11-04 00:05:13 +01007368 do
7369 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007370#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007371 if (size > INT_MAX) {
7372 chunk_size = INT_MAX;
7373 final = 0;
7374 done = 0;
7375 }
7376 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007377#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007378 {
7379 chunk_size = (int)size;
7380 final = (consumed == NULL);
7381 done = 1;
7382 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007383
Victor Stinner76a31a62011-11-04 00:05:13 +01007384 if (chunk_size == 0 && done) {
7385 if (v != NULL)
7386 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007387 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007388 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007389
Victor Stinner76a31a62011-11-04 00:05:13 +01007390 converted = decode_code_page_strict(code_page, &v,
7391 s, chunk_size);
7392 if (converted == -2)
7393 converted = decode_code_page_errors(code_page, &v,
7394 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007395 errors, final);
7396 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007397
7398 if (converted < 0) {
7399 Py_XDECREF(v);
7400 return NULL;
7401 }
7402
7403 if (consumed)
7404 *consumed += converted;
7405
7406 s += converted;
7407 size -= converted;
7408 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007409
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007410 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007411}
7412
Alexander Belopolsky40018472011-02-26 01:02:56 +00007413PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007414PyUnicode_DecodeCodePageStateful(int code_page,
7415 const char *s,
7416 Py_ssize_t size,
7417 const char *errors,
7418 Py_ssize_t *consumed)
7419{
7420 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7421}
7422
7423PyObject *
7424PyUnicode_DecodeMBCSStateful(const char *s,
7425 Py_ssize_t size,
7426 const char *errors,
7427 Py_ssize_t *consumed)
7428{
7429 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7430}
7431
7432PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007433PyUnicode_DecodeMBCS(const char *s,
7434 Py_ssize_t size,
7435 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007436{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007437 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7438}
7439
Victor Stinner3a50e702011-10-18 21:21:00 +02007440static DWORD
7441encode_code_page_flags(UINT code_page, const char *errors)
7442{
7443 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007444 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 }
7446 else if (code_page == CP_UTF7) {
7447 /* CP_UTF7 only supports flags=0 */
7448 return 0;
7449 }
7450 else {
7451 if (errors != NULL && strcmp(errors, "replace") == 0)
7452 return 0;
7453 else
7454 return WC_NO_BEST_FIT_CHARS;
7455 }
7456}
7457
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007458/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 * Encode a Unicode string to a Windows code page into a byte string in strict
7460 * mode.
7461 *
7462 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007463 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007464 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007465static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007466encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007467 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007468 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007469{
Victor Stinner554f3f02010-06-16 23:33:54 +00007470 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007471 BOOL *pusedDefaultChar = &usedDefaultChar;
7472 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007473 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007474 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 const DWORD flags = encode_code_page_flags(code_page, NULL);
7476 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007477 /* Create a substring so that we can get the UTF-16 representation
7478 of just the slice under consideration. */
7479 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007480
Martin v. Löwis3d325192011-11-04 18:23:06 +01007481 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007482
Victor Stinner3a50e702011-10-18 21:21:00 +02007483 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007484 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007485 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007486 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007487
Victor Stinner2fc507f2011-11-04 20:06:39 +01007488 substring = PyUnicode_Substring(unicode, offset, offset+len);
7489 if (substring == NULL)
7490 return -1;
7491 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7492 if (p == NULL) {
7493 Py_DECREF(substring);
7494 return -1;
7495 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007496 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007497
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007498 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007499 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007500 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007501 NULL, 0,
7502 NULL, pusedDefaultChar);
7503 if (outsize <= 0)
7504 goto error;
7505 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007506 if (pusedDefaultChar && *pusedDefaultChar) {
7507 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007508 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007509 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007510
Victor Stinner3a50e702011-10-18 21:21:00 +02007511 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007512 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007513 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007514 if (*outbytes == NULL) {
7515 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007516 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007517 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007518 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007519 }
7520 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007521 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007522 const Py_ssize_t n = PyBytes_Size(*outbytes);
7523 if (outsize > PY_SSIZE_T_MAX - n) {
7524 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007525 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007526 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007527 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007528 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7529 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007530 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007531 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007532 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007533 }
7534
7535 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007536 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007537 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007538 out, outsize,
7539 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007540 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007541 if (outsize <= 0)
7542 goto error;
7543 if (pusedDefaultChar && *pusedDefaultChar)
7544 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007545 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007546
Victor Stinner3a50e702011-10-18 21:21:00 +02007547error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007548 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007549 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7550 return -2;
7551 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007552 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007553}
7554
Victor Stinner3a50e702011-10-18 21:21:00 +02007555/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007556 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007557 * error handler.
7558 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007559 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007560 * -1 on other error.
7561 */
7562static int
7563encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007564 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007565 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007566{
Victor Stinner3a50e702011-10-18 21:21:00 +02007567 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007568 Py_ssize_t pos = unicode_offset;
7569 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007570 /* Ideally, we should get reason from FormatMessage. This is the Windows
7571 2000 English version of the message. */
7572 const char *reason = "invalid character";
7573 /* 4=maximum length of a UTF-8 sequence */
7574 char buffer[4];
7575 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7576 Py_ssize_t outsize;
7577 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007578 PyObject *errorHandler = NULL;
7579 PyObject *exc = NULL;
7580 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007581 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007582 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007583 PyObject *rep;
7584 int ret = -1;
7585
7586 assert(insize > 0);
7587
7588 encoding = code_page_name(code_page, &encoding_obj);
7589 if (encoding == NULL)
7590 return -1;
7591
7592 if (errors == NULL || strcmp(errors, "strict") == 0) {
7593 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7594 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007595 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007596 if (exc != NULL) {
7597 PyCodec_StrictErrors(exc);
7598 Py_DECREF(exc);
7599 }
7600 Py_XDECREF(encoding_obj);
7601 return -1;
7602 }
7603
7604 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7605 pusedDefaultChar = &usedDefaultChar;
7606 else
7607 pusedDefaultChar = NULL;
7608
7609 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7610 PyErr_NoMemory();
7611 goto error;
7612 }
7613 outsize = insize * Py_ARRAY_LENGTH(buffer);
7614
7615 if (*outbytes == NULL) {
7616 /* Create string object */
7617 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7618 if (*outbytes == NULL)
7619 goto error;
7620 out = PyBytes_AS_STRING(*outbytes);
7621 }
7622 else {
7623 /* Extend string object */
7624 Py_ssize_t n = PyBytes_Size(*outbytes);
7625 if (n > PY_SSIZE_T_MAX - outsize) {
7626 PyErr_NoMemory();
7627 goto error;
7628 }
7629 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7630 goto error;
7631 out = PyBytes_AS_STRING(*outbytes) + n;
7632 }
7633
7634 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007635 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007636 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007637 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7638 wchar_t chars[2];
7639 int charsize;
7640 if (ch < 0x10000) {
7641 chars[0] = (wchar_t)ch;
7642 charsize = 1;
7643 }
7644 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007645 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7646 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007647 charsize = 2;
7648 }
7649
Victor Stinner3a50e702011-10-18 21:21:00 +02007650 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007651 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007652 buffer, Py_ARRAY_LENGTH(buffer),
7653 NULL, pusedDefaultChar);
7654 if (outsize > 0) {
7655 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7656 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007657 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007658 memcpy(out, buffer, outsize);
7659 out += outsize;
7660 continue;
7661 }
7662 }
7663 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7664 PyErr_SetFromWindowsErr(0);
7665 goto error;
7666 }
7667
Victor Stinner3a50e702011-10-18 21:21:00 +02007668 rep = unicode_encode_call_errorhandler(
7669 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007670 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007671 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007672 if (rep == NULL)
7673 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007674 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007675
7676 if (PyBytes_Check(rep)) {
7677 outsize = PyBytes_GET_SIZE(rep);
7678 if (outsize != 1) {
7679 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7680 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7681 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7682 Py_DECREF(rep);
7683 goto error;
7684 }
7685 out = PyBytes_AS_STRING(*outbytes) + offset;
7686 }
7687 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7688 out += outsize;
7689 }
7690 else {
7691 Py_ssize_t i;
7692 enum PyUnicode_Kind kind;
7693 void *data;
7694
Benjamin Petersonbac79492012-01-14 13:34:47 -05007695 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007696 Py_DECREF(rep);
7697 goto error;
7698 }
7699
7700 outsize = PyUnicode_GET_LENGTH(rep);
7701 if (outsize != 1) {
7702 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7703 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7704 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7705 Py_DECREF(rep);
7706 goto error;
7707 }
7708 out = PyBytes_AS_STRING(*outbytes) + offset;
7709 }
7710 kind = PyUnicode_KIND(rep);
7711 data = PyUnicode_DATA(rep);
7712 for (i=0; i < outsize; i++) {
7713 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7714 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007715 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007716 encoding, unicode,
7717 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007718 "unable to encode error handler result to ASCII");
7719 Py_DECREF(rep);
7720 goto error;
7721 }
7722 *out = (unsigned char)ch;
7723 out++;
7724 }
7725 }
7726 Py_DECREF(rep);
7727 }
7728 /* write a NUL byte */
7729 *out = 0;
7730 outsize = out - PyBytes_AS_STRING(*outbytes);
7731 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7732 if (_PyBytes_Resize(outbytes, outsize) < 0)
7733 goto error;
7734 ret = 0;
7735
7736error:
7737 Py_XDECREF(encoding_obj);
7738 Py_XDECREF(errorHandler);
7739 Py_XDECREF(exc);
7740 return ret;
7741}
7742
Victor Stinner3a50e702011-10-18 21:21:00 +02007743static PyObject *
7744encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007745 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007746 const char *errors)
7747{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007748 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007749 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007750 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007751 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007752
Victor Stinner29dacf22015-01-26 16:41:32 +01007753 if (!PyUnicode_Check(unicode)) {
7754 PyErr_BadArgument();
7755 return NULL;
7756 }
7757
Benjamin Petersonbac79492012-01-14 13:34:47 -05007758 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007759 return NULL;
7760 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007761
Victor Stinner3a50e702011-10-18 21:21:00 +02007762 if (code_page < 0) {
7763 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7764 return NULL;
7765 }
7766
Martin v. Löwis3d325192011-11-04 18:23:06 +01007767 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007768 return PyBytes_FromStringAndSize(NULL, 0);
7769
Victor Stinner7581cef2011-11-03 22:32:33 +01007770 offset = 0;
7771 do
7772 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007773#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007774 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007775 chunks. */
7776 if (len > INT_MAX/2) {
7777 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007778 done = 0;
7779 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007780 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007781#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007782 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007783 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007784 done = 1;
7785 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007786
Victor Stinner76a31a62011-11-04 00:05:13 +01007787 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007788 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007789 errors);
7790 if (ret == -2)
7791 ret = encode_code_page_errors(code_page, &outbytes,
7792 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007793 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007794 if (ret < 0) {
7795 Py_XDECREF(outbytes);
7796 return NULL;
7797 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007798
Victor Stinner7581cef2011-11-03 22:32:33 +01007799 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007800 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007801 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007802
Victor Stinner3a50e702011-10-18 21:21:00 +02007803 return outbytes;
7804}
7805
7806PyObject *
7807PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7808 Py_ssize_t size,
7809 const char *errors)
7810{
Victor Stinner7581cef2011-11-03 22:32:33 +01007811 PyObject *unicode, *res;
7812 unicode = PyUnicode_FromUnicode(p, size);
7813 if (unicode == NULL)
7814 return NULL;
7815 res = encode_code_page(CP_ACP, unicode, errors);
7816 Py_DECREF(unicode);
7817 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007818}
7819
7820PyObject *
7821PyUnicode_EncodeCodePage(int code_page,
7822 PyObject *unicode,
7823 const char *errors)
7824{
Victor Stinner7581cef2011-11-03 22:32:33 +01007825 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007826}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007827
Alexander Belopolsky40018472011-02-26 01:02:56 +00007828PyObject *
7829PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007830{
Victor Stinner7581cef2011-11-03 22:32:33 +01007831 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007832}
7833
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007834#undef NEED_RETRY
7835
Steve Dowercc16be82016-09-08 10:35:16 -07007836#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007837
Guido van Rossumd57fd912000-03-10 22:53:23 +00007838/* --- Character Mapping Codec -------------------------------------------- */
7839
Victor Stinnerfb161b12013-04-18 01:44:27 +02007840static int
7841charmap_decode_string(const char *s,
7842 Py_ssize_t size,
7843 PyObject *mapping,
7844 const char *errors,
7845 _PyUnicodeWriter *writer)
7846{
7847 const char *starts = s;
7848 const char *e;
7849 Py_ssize_t startinpos, endinpos;
7850 PyObject *errorHandler = NULL, *exc = NULL;
7851 Py_ssize_t maplen;
7852 enum PyUnicode_Kind mapkind;
7853 void *mapdata;
7854 Py_UCS4 x;
7855 unsigned char ch;
7856
7857 if (PyUnicode_READY(mapping) == -1)
7858 return -1;
7859
7860 maplen = PyUnicode_GET_LENGTH(mapping);
7861 mapdata = PyUnicode_DATA(mapping);
7862 mapkind = PyUnicode_KIND(mapping);
7863
7864 e = s + size;
7865
7866 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7867 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7868 * is disabled in encoding aliases, latin1 is preferred because
7869 * its implementation is faster. */
7870 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7871 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7872 Py_UCS4 maxchar = writer->maxchar;
7873
7874 assert (writer->kind == PyUnicode_1BYTE_KIND);
7875 while (s < e) {
7876 ch = *s;
7877 x = mapdata_ucs1[ch];
7878 if (x > maxchar) {
7879 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7880 goto onError;
7881 maxchar = writer->maxchar;
7882 outdata = (Py_UCS1 *)writer->data;
7883 }
7884 outdata[writer->pos] = x;
7885 writer->pos++;
7886 ++s;
7887 }
7888 return 0;
7889 }
7890
7891 while (s < e) {
7892 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7893 enum PyUnicode_Kind outkind = writer->kind;
7894 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7895 if (outkind == PyUnicode_1BYTE_KIND) {
7896 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7897 Py_UCS4 maxchar = writer->maxchar;
7898 while (s < e) {
7899 ch = *s;
7900 x = mapdata_ucs2[ch];
7901 if (x > maxchar)
7902 goto Error;
7903 outdata[writer->pos] = x;
7904 writer->pos++;
7905 ++s;
7906 }
7907 break;
7908 }
7909 else if (outkind == PyUnicode_2BYTE_KIND) {
7910 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7911 while (s < e) {
7912 ch = *s;
7913 x = mapdata_ucs2[ch];
7914 if (x == 0xFFFE)
7915 goto Error;
7916 outdata[writer->pos] = x;
7917 writer->pos++;
7918 ++s;
7919 }
7920 break;
7921 }
7922 }
7923 ch = *s;
7924
7925 if (ch < maplen)
7926 x = PyUnicode_READ(mapkind, mapdata, ch);
7927 else
7928 x = 0xfffe; /* invalid value */
7929Error:
7930 if (x == 0xfffe)
7931 {
7932 /* undefined mapping */
7933 startinpos = s-starts;
7934 endinpos = startinpos+1;
7935 if (unicode_decode_call_errorhandler_writer(
7936 errors, &errorHandler,
7937 "charmap", "character maps to <undefined>",
7938 &starts, &e, &startinpos, &endinpos, &exc, &s,
7939 writer)) {
7940 goto onError;
7941 }
7942 continue;
7943 }
7944
7945 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7946 goto onError;
7947 ++s;
7948 }
7949 Py_XDECREF(errorHandler);
7950 Py_XDECREF(exc);
7951 return 0;
7952
7953onError:
7954 Py_XDECREF(errorHandler);
7955 Py_XDECREF(exc);
7956 return -1;
7957}
7958
7959static int
7960charmap_decode_mapping(const char *s,
7961 Py_ssize_t size,
7962 PyObject *mapping,
7963 const char *errors,
7964 _PyUnicodeWriter *writer)
7965{
7966 const char *starts = s;
7967 const char *e;
7968 Py_ssize_t startinpos, endinpos;
7969 PyObject *errorHandler = NULL, *exc = NULL;
7970 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007971 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007972
7973 e = s + size;
7974
7975 while (s < e) {
7976 ch = *s;
7977
7978 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7979 key = PyLong_FromLong((long)ch);
7980 if (key == NULL)
7981 goto onError;
7982
7983 item = PyObject_GetItem(mapping, key);
7984 Py_DECREF(key);
7985 if (item == NULL) {
7986 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7987 /* No mapping found means: mapping is undefined. */
7988 PyErr_Clear();
7989 goto Undefined;
7990 } else
7991 goto onError;
7992 }
7993
7994 /* Apply mapping */
7995 if (item == Py_None)
7996 goto Undefined;
7997 if (PyLong_Check(item)) {
7998 long value = PyLong_AS_LONG(item);
7999 if (value == 0xFFFE)
8000 goto Undefined;
8001 if (value < 0 || value > MAX_UNICODE) {
8002 PyErr_Format(PyExc_TypeError,
8003 "character mapping must be in range(0x%lx)",
8004 (unsigned long)MAX_UNICODE + 1);
8005 goto onError;
8006 }
8007
8008 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8009 goto onError;
8010 }
8011 else if (PyUnicode_Check(item)) {
8012 if (PyUnicode_READY(item) == -1)
8013 goto onError;
8014 if (PyUnicode_GET_LENGTH(item) == 1) {
8015 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8016 if (value == 0xFFFE)
8017 goto Undefined;
8018 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8019 goto onError;
8020 }
8021 else {
8022 writer->overallocate = 1;
8023 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8024 goto onError;
8025 }
8026 }
8027 else {
8028 /* wrong return value */
8029 PyErr_SetString(PyExc_TypeError,
8030 "character mapping must return integer, None or str");
8031 goto onError;
8032 }
8033 Py_CLEAR(item);
8034 ++s;
8035 continue;
8036
8037Undefined:
8038 /* undefined mapping */
8039 Py_CLEAR(item);
8040 startinpos = s-starts;
8041 endinpos = startinpos+1;
8042 if (unicode_decode_call_errorhandler_writer(
8043 errors, &errorHandler,
8044 "charmap", "character maps to <undefined>",
8045 &starts, &e, &startinpos, &endinpos, &exc, &s,
8046 writer)) {
8047 goto onError;
8048 }
8049 }
8050 Py_XDECREF(errorHandler);
8051 Py_XDECREF(exc);
8052 return 0;
8053
8054onError:
8055 Py_XDECREF(item);
8056 Py_XDECREF(errorHandler);
8057 Py_XDECREF(exc);
8058 return -1;
8059}
8060
Alexander Belopolsky40018472011-02-26 01:02:56 +00008061PyObject *
8062PyUnicode_DecodeCharmap(const char *s,
8063 Py_ssize_t size,
8064 PyObject *mapping,
8065 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008066{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008067 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008068
Guido van Rossumd57fd912000-03-10 22:53:23 +00008069 /* Default to Latin-1 */
8070 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008072
Guido van Rossumd57fd912000-03-10 22:53:23 +00008073 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008074 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008075 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008076 writer.min_length = size;
8077 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008078 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008079
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008080 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008081 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8082 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008083 }
8084 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008085 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8086 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008087 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008088 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008089
Benjamin Peterson29060642009-01-31 22:14:21 +00008090 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008091 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008092 return NULL;
8093}
8094
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008095/* Charmap encoding: the lookup table */
8096
Alexander Belopolsky40018472011-02-26 01:02:56 +00008097struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008098 PyObject_HEAD
8099 unsigned char level1[32];
8100 int count2, count3;
8101 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008102};
8103
8104static PyObject*
8105encoding_map_size(PyObject *obj, PyObject* args)
8106{
8107 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008108 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008109 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008110}
8111
8112static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008113 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008114 PyDoc_STR("Return the size (in bytes) of this object") },
8115 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008116};
8117
8118static void
8119encoding_map_dealloc(PyObject* o)
8120{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008121 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008122}
8123
8124static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008125 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 "EncodingMap", /*tp_name*/
8127 sizeof(struct encoding_map), /*tp_basicsize*/
8128 0, /*tp_itemsize*/
8129 /* methods */
8130 encoding_map_dealloc, /*tp_dealloc*/
8131 0, /*tp_print*/
8132 0, /*tp_getattr*/
8133 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008134 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008135 0, /*tp_repr*/
8136 0, /*tp_as_number*/
8137 0, /*tp_as_sequence*/
8138 0, /*tp_as_mapping*/
8139 0, /*tp_hash*/
8140 0, /*tp_call*/
8141 0, /*tp_str*/
8142 0, /*tp_getattro*/
8143 0, /*tp_setattro*/
8144 0, /*tp_as_buffer*/
8145 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8146 0, /*tp_doc*/
8147 0, /*tp_traverse*/
8148 0, /*tp_clear*/
8149 0, /*tp_richcompare*/
8150 0, /*tp_weaklistoffset*/
8151 0, /*tp_iter*/
8152 0, /*tp_iternext*/
8153 encoding_map_methods, /*tp_methods*/
8154 0, /*tp_members*/
8155 0, /*tp_getset*/
8156 0, /*tp_base*/
8157 0, /*tp_dict*/
8158 0, /*tp_descr_get*/
8159 0, /*tp_descr_set*/
8160 0, /*tp_dictoffset*/
8161 0, /*tp_init*/
8162 0, /*tp_alloc*/
8163 0, /*tp_new*/
8164 0, /*tp_free*/
8165 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008166};
8167
8168PyObject*
8169PyUnicode_BuildEncodingMap(PyObject* string)
8170{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008171 PyObject *result;
8172 struct encoding_map *mresult;
8173 int i;
8174 int need_dict = 0;
8175 unsigned char level1[32];
8176 unsigned char level2[512];
8177 unsigned char *mlevel1, *mlevel2, *mlevel3;
8178 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008179 int kind;
8180 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008181 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008182 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008183
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008184 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008185 PyErr_BadArgument();
8186 return NULL;
8187 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008188 kind = PyUnicode_KIND(string);
8189 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008190 length = PyUnicode_GET_LENGTH(string);
8191 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008192 memset(level1, 0xFF, sizeof level1);
8193 memset(level2, 0xFF, sizeof level2);
8194
8195 /* If there isn't a one-to-one mapping of NULL to \0,
8196 or if there are non-BMP characters, we need to use
8197 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008198 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008199 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008200 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008201 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008202 ch = PyUnicode_READ(kind, data, i);
8203 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008204 need_dict = 1;
8205 break;
8206 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008207 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008208 /* unmapped character */
8209 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008210 l1 = ch >> 11;
8211 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008212 if (level1[l1] == 0xFF)
8213 level1[l1] = count2++;
8214 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008215 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008216 }
8217
8218 if (count2 >= 0xFF || count3 >= 0xFF)
8219 need_dict = 1;
8220
8221 if (need_dict) {
8222 PyObject *result = PyDict_New();
8223 PyObject *key, *value;
8224 if (!result)
8225 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008226 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008227 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008228 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008229 if (!key || !value)
8230 goto failed1;
8231 if (PyDict_SetItem(result, key, value) == -1)
8232 goto failed1;
8233 Py_DECREF(key);
8234 Py_DECREF(value);
8235 }
8236 return result;
8237 failed1:
8238 Py_XDECREF(key);
8239 Py_XDECREF(value);
8240 Py_DECREF(result);
8241 return NULL;
8242 }
8243
8244 /* Create a three-level trie */
8245 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8246 16*count2 + 128*count3 - 1);
8247 if (!result)
8248 return PyErr_NoMemory();
8249 PyObject_Init(result, &EncodingMapType);
8250 mresult = (struct encoding_map*)result;
8251 mresult->count2 = count2;
8252 mresult->count3 = count3;
8253 mlevel1 = mresult->level1;
8254 mlevel2 = mresult->level23;
8255 mlevel3 = mresult->level23 + 16*count2;
8256 memcpy(mlevel1, level1, 32);
8257 memset(mlevel2, 0xFF, 16*count2);
8258 memset(mlevel3, 0, 128*count3);
8259 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008260 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008261 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008262 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8263 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008264 /* unmapped character */
8265 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008266 o1 = ch>>11;
8267 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008268 i2 = 16*mlevel1[o1] + o2;
8269 if (mlevel2[i2] == 0xFF)
8270 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008271 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008272 i3 = 128*mlevel2[i2] + o3;
8273 mlevel3[i3] = i;
8274 }
8275 return result;
8276}
8277
8278static int
Victor Stinner22168992011-11-20 17:09:18 +01008279encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008280{
8281 struct encoding_map *map = (struct encoding_map*)mapping;
8282 int l1 = c>>11;
8283 int l2 = (c>>7) & 0xF;
8284 int l3 = c & 0x7F;
8285 int i;
8286
Victor Stinner22168992011-11-20 17:09:18 +01008287 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008289 if (c == 0)
8290 return 0;
8291 /* level 1*/
8292 i = map->level1[l1];
8293 if (i == 0xFF) {
8294 return -1;
8295 }
8296 /* level 2*/
8297 i = map->level23[16*i+l2];
8298 if (i == 0xFF) {
8299 return -1;
8300 }
8301 /* level 3 */
8302 i = map->level23[16*map->count2 + 128*i + l3];
8303 if (i == 0) {
8304 return -1;
8305 }
8306 return i;
8307}
8308
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008309/* Lookup the character ch in the mapping. If the character
8310 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008311 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008312static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008313charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008314{
Christian Heimes217cfd12007-12-02 14:31:20 +00008315 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316 PyObject *x;
8317
8318 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008320 x = PyObject_GetItem(mapping, w);
8321 Py_DECREF(w);
8322 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8324 /* No mapping found means: mapping is undefined. */
8325 PyErr_Clear();
8326 x = Py_None;
8327 Py_INCREF(x);
8328 return x;
8329 } else
8330 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008331 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008332 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008333 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008334 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 long value = PyLong_AS_LONG(x);
8336 if (value < 0 || value > 255) {
8337 PyErr_SetString(PyExc_TypeError,
8338 "character mapping must be in range(256)");
8339 Py_DECREF(x);
8340 return NULL;
8341 }
8342 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008343 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008344 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008346 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 /* wrong return value */
8348 PyErr_Format(PyExc_TypeError,
8349 "character mapping must return integer, bytes or None, not %.400s",
8350 x->ob_type->tp_name);
8351 Py_DECREF(x);
8352 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008353 }
8354}
8355
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008356static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008357charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008358{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008359 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8360 /* exponentially overallocate to minimize reallocations */
8361 if (requiredsize < 2*outsize)
8362 requiredsize = 2*outsize;
8363 if (_PyBytes_Resize(outobj, requiredsize))
8364 return -1;
8365 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008366}
8367
Benjamin Peterson14339b62009-01-31 16:36:08 +00008368typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008370} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008372 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373 space is available. Return a new reference to the object that
8374 was put in the output buffer, or Py_None, if the mapping was undefined
8375 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008376 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008377static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008378charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008379 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008381 PyObject *rep;
8382 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008383 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384
Christian Heimes90aa7642007-12-19 02:45:37 +00008385 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008386 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008388 if (res == -1)
8389 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 if (outsize<requiredsize)
8391 if (charmapencode_resize(outobj, outpos, requiredsize))
8392 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008393 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 outstart[(*outpos)++] = (char)res;
8395 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008396 }
8397
8398 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008401 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 Py_DECREF(rep);
8403 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008404 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 if (PyLong_Check(rep)) {
8406 Py_ssize_t requiredsize = *outpos+1;
8407 if (outsize<requiredsize)
8408 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8409 Py_DECREF(rep);
8410 return enc_EXCEPTION;
8411 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008412 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008414 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 else {
8416 const char *repchars = PyBytes_AS_STRING(rep);
8417 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8418 Py_ssize_t requiredsize = *outpos+repsize;
8419 if (outsize<requiredsize)
8420 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8421 Py_DECREF(rep);
8422 return enc_EXCEPTION;
8423 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008424 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 memcpy(outstart + *outpos, repchars, repsize);
8426 *outpos += repsize;
8427 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008429 Py_DECREF(rep);
8430 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431}
8432
8433/* handle an error in PyUnicode_EncodeCharmap
8434 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008435static int
8436charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008437 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008439 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008440 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008441{
8442 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008443 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008444 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008445 enum PyUnicode_Kind kind;
8446 void *data;
8447 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008448 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008449 Py_ssize_t collstartpos = *inpos;
8450 Py_ssize_t collendpos = *inpos+1;
8451 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452 char *encoding = "charmap";
8453 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008454 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008455 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008456 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008457
Benjamin Petersonbac79492012-01-14 13:34:47 -05008458 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008459 return -1;
8460 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008461 /* find all unencodable characters */
8462 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008463 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008464 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008465 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008466 val = encoding_map_lookup(ch, mapping);
8467 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 break;
8469 ++collendpos;
8470 continue;
8471 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008472
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008473 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8474 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 if (rep==NULL)
8476 return -1;
8477 else if (rep!=Py_None) {
8478 Py_DECREF(rep);
8479 break;
8480 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008481 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483 }
8484 /* cache callback name lookup
8485 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008486 if (*error_handler == _Py_ERROR_UNKNOWN)
8487 *error_handler = get_error_handler(errors);
8488
8489 switch (*error_handler) {
8490 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008491 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008492 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008493
8494 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008495 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 x = charmapencode_output('?', mapping, res, respos);
8497 if (x==enc_EXCEPTION) {
8498 return -1;
8499 }
8500 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008501 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 return -1;
8503 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008504 }
8505 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008506 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008507 *inpos = collendpos;
8508 break;
Victor Stinner50149202015-09-22 00:26:54 +02008509
8510 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008511 /* generate replacement (temporarily (mis)uses p) */
8512 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 char buffer[2+29+1+1];
8514 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008515 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 for (cp = buffer; *cp; ++cp) {
8517 x = charmapencode_output(*cp, mapping, res, respos);
8518 if (x==enc_EXCEPTION)
8519 return -1;
8520 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008521 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 return -1;
8523 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008524 }
8525 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008526 *inpos = collendpos;
8527 break;
Victor Stinner50149202015-09-22 00:26:54 +02008528
Benjamin Peterson14339b62009-01-31 16:36:08 +00008529 default:
Victor Stinner50149202015-09-22 00:26:54 +02008530 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008531 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008533 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008535 if (PyBytes_Check(repunicode)) {
8536 /* Directly copy bytes result to output. */
8537 Py_ssize_t outsize = PyBytes_Size(*res);
8538 Py_ssize_t requiredsize;
8539 repsize = PyBytes_Size(repunicode);
8540 requiredsize = *respos + repsize;
8541 if (requiredsize > outsize)
8542 /* Make room for all additional bytes. */
8543 if (charmapencode_resize(res, respos, requiredsize)) {
8544 Py_DECREF(repunicode);
8545 return -1;
8546 }
8547 memcpy(PyBytes_AsString(*res) + *respos,
8548 PyBytes_AsString(repunicode), repsize);
8549 *respos += repsize;
8550 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008551 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008552 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008553 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008554 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008555 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008556 Py_DECREF(repunicode);
8557 return -1;
8558 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008559 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008560 data = PyUnicode_DATA(repunicode);
8561 kind = PyUnicode_KIND(repunicode);
8562 for (index = 0; index < repsize; index++) {
8563 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8564 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008566 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 return -1;
8568 }
8569 else if (x==enc_FAILED) {
8570 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008571 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 return -1;
8573 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008574 }
8575 *inpos = newpos;
8576 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 }
8578 return 0;
8579}
8580
Alexander Belopolsky40018472011-02-26 01:02:56 +00008581PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008582_PyUnicode_EncodeCharmap(PyObject *unicode,
8583 PyObject *mapping,
8584 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008585{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008586 /* output object */
8587 PyObject *res = NULL;
8588 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008589 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008590 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008592 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008593 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008594 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008595 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008596 void *data;
8597 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008598
Benjamin Petersonbac79492012-01-14 13:34:47 -05008599 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008600 return NULL;
8601 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008602 data = PyUnicode_DATA(unicode);
8603 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008604
Guido van Rossumd57fd912000-03-10 22:53:23 +00008605 /* Default to Latin-1 */
8606 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008607 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008608
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008609 /* allocate enough for a simple encoding without
8610 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008611 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008612 if (res == NULL)
8613 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008614 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008615 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008616
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008617 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008618 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008620 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 if (x==enc_EXCEPTION) /* error */
8622 goto onError;
8623 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008624 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008625 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008626 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008627 &res, &respos)) {
8628 goto onError;
8629 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008630 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 else
8632 /* done with this character => adjust input position */
8633 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008634 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008635
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008636 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008637 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008638 if (_PyBytes_Resize(&res, respos) < 0)
8639 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008640
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008641 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008642 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008643 return res;
8644
Benjamin Peterson29060642009-01-31 22:14:21 +00008645 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008646 Py_XDECREF(res);
8647 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008648 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008649 return NULL;
8650}
8651
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008652/* Deprecated */
8653PyObject *
8654PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8655 Py_ssize_t size,
8656 PyObject *mapping,
8657 const char *errors)
8658{
8659 PyObject *result;
8660 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8661 if (unicode == NULL)
8662 return NULL;
8663 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8664 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008665 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008666}
8667
Alexander Belopolsky40018472011-02-26 01:02:56 +00008668PyObject *
8669PyUnicode_AsCharmapString(PyObject *unicode,
8670 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008671{
8672 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008673 PyErr_BadArgument();
8674 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008675 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008676 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008677}
8678
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008679/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008680static void
8681make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008682 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008683 Py_ssize_t startpos, Py_ssize_t endpos,
8684 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008685{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008686 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008687 *exceptionObject = _PyUnicodeTranslateError_Create(
8688 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008689 }
8690 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008691 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8692 goto onError;
8693 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8694 goto onError;
8695 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8696 goto onError;
8697 return;
8698 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008699 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008700 }
8701}
8702
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008703/* error handling callback helper:
8704 build arguments, call the callback and check the arguments,
8705 put the result into newpos and return the replacement string, which
8706 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008707static PyObject *
8708unicode_translate_call_errorhandler(const char *errors,
8709 PyObject **errorHandler,
8710 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008712 Py_ssize_t startpos, Py_ssize_t endpos,
8713 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008714{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008715 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008716
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008717 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008718 PyObject *restuple;
8719 PyObject *resunicode;
8720
8721 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008723 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008724 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008725 }
8726
8727 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008728 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008729 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008731
8732 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008733 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008734 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008735 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008736 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008737 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008738 Py_DECREF(restuple);
8739 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008740 }
8741 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 &resunicode, &i_newpos)) {
8743 Py_DECREF(restuple);
8744 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008745 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008746 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008747 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008748 else
8749 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008751 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008752 Py_DECREF(restuple);
8753 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008754 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008755 Py_INCREF(resunicode);
8756 Py_DECREF(restuple);
8757 return resunicode;
8758}
8759
8760/* Lookup the character ch in the mapping and put the result in result,
8761 which must be decrefed by the caller.
8762 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008763static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008764charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008765{
Christian Heimes217cfd12007-12-02 14:31:20 +00008766 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008767 PyObject *x;
8768
8769 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008771 x = PyObject_GetItem(mapping, w);
8772 Py_DECREF(w);
8773 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8775 /* No mapping found means: use 1:1 mapping. */
8776 PyErr_Clear();
8777 *result = NULL;
8778 return 0;
8779 } else
8780 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008781 }
8782 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008783 *result = x;
8784 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008785 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008786 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008787 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008788 if (value < 0 || value > MAX_UNICODE) {
8789 PyErr_Format(PyExc_ValueError,
8790 "character mapping must be in range(0x%x)",
8791 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008792 Py_DECREF(x);
8793 return -1;
8794 }
8795 *result = x;
8796 return 0;
8797 }
8798 else if (PyUnicode_Check(x)) {
8799 *result = x;
8800 return 0;
8801 }
8802 else {
8803 /* wrong return value */
8804 PyErr_SetString(PyExc_TypeError,
8805 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008806 Py_DECREF(x);
8807 return -1;
8808 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008809}
Victor Stinner1194ea02014-04-04 19:37:40 +02008810
8811/* lookup the character, write the result into the writer.
8812 Return 1 if the result was written into the writer, return 0 if the mapping
8813 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008814static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008815charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8816 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008817{
Victor Stinner1194ea02014-04-04 19:37:40 +02008818 PyObject *item;
8819
8820 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008821 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008822
8823 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008824 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008825 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008826 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008827 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008828 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008829 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008830
8831 if (item == Py_None) {
8832 Py_DECREF(item);
8833 return 0;
8834 }
8835
8836 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008837 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8838 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8839 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008840 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8841 Py_DECREF(item);
8842 return -1;
8843 }
8844 Py_DECREF(item);
8845 return 1;
8846 }
8847
8848 if (!PyUnicode_Check(item)) {
8849 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008850 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008851 }
8852
8853 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8854 Py_DECREF(item);
8855 return -1;
8856 }
8857
8858 Py_DECREF(item);
8859 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008860}
8861
Victor Stinner89a76ab2014-04-05 11:44:04 +02008862static int
8863unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8864 Py_UCS1 *translate)
8865{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008866 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008867 int ret = 0;
8868
Victor Stinner89a76ab2014-04-05 11:44:04 +02008869 if (charmaptranslate_lookup(ch, mapping, &item)) {
8870 return -1;
8871 }
8872
8873 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008874 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008875 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008876 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008877 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008878 /* not found => default to 1:1 mapping */
8879 translate[ch] = ch;
8880 return 1;
8881 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008882 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008883 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008884 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8885 used it */
8886 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008887 /* invalid character or character outside ASCII:
8888 skip the fast translate */
8889 goto exit;
8890 }
8891 translate[ch] = (Py_UCS1)replace;
8892 }
8893 else if (PyUnicode_Check(item)) {
8894 Py_UCS4 replace;
8895
8896 if (PyUnicode_READY(item) == -1) {
8897 Py_DECREF(item);
8898 return -1;
8899 }
8900 if (PyUnicode_GET_LENGTH(item) != 1)
8901 goto exit;
8902
8903 replace = PyUnicode_READ_CHAR(item, 0);
8904 if (replace > 127)
8905 goto exit;
8906 translate[ch] = (Py_UCS1)replace;
8907 }
8908 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008909 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008910 goto exit;
8911 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008912 ret = 1;
8913
Benjamin Peterson1365de72014-04-07 20:15:41 -04008914 exit:
8915 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008916 return ret;
8917}
8918
8919/* Fast path for ascii => ascii translation. Return 1 if the whole string
8920 was translated into writer, return 0 if the input string was partially
8921 translated into writer, raise an exception and return -1 on error. */
8922static int
8923unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008924 _PyUnicodeWriter *writer, int ignore,
8925 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008926{
Victor Stinner872b2912014-04-05 14:27:07 +02008927 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008928 Py_ssize_t len;
8929 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008930 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008931
Victor Stinner89a76ab2014-04-05 11:44:04 +02008932 len = PyUnicode_GET_LENGTH(input);
8933
Victor Stinner872b2912014-04-05 14:27:07 +02008934 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008935
8936 in = PyUnicode_1BYTE_DATA(input);
8937 end = in + len;
8938
8939 assert(PyUnicode_IS_ASCII(writer->buffer));
8940 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8941 out = PyUnicode_1BYTE_DATA(writer->buffer);
8942
Victor Stinner872b2912014-04-05 14:27:07 +02008943 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008944 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008945 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008946 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008947 int translate = unicode_fast_translate_lookup(mapping, ch,
8948 ascii_table);
8949 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008950 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008951 if (translate == 0)
8952 goto exit;
8953 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008954 }
Victor Stinner872b2912014-04-05 14:27:07 +02008955 if (ch2 == 0xfe) {
8956 if (ignore)
8957 continue;
8958 goto exit;
8959 }
8960 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008961 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008962 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008963 }
Victor Stinner872b2912014-04-05 14:27:07 +02008964 res = 1;
8965
8966exit:
8967 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008968 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008969 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008970}
8971
Victor Stinner3222da22015-10-01 22:07:32 +02008972static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008973_PyUnicode_TranslateCharmap(PyObject *input,
8974 PyObject *mapping,
8975 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008976{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008977 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008978 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008979 Py_ssize_t size, i;
8980 int kind;
8981 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008982 _PyUnicodeWriter writer;
8983 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008984 char *reason = "character maps to <undefined>";
8985 PyObject *errorHandler = NULL;
8986 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008987 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008988 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008989
Guido van Rossumd57fd912000-03-10 22:53:23 +00008990 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008991 PyErr_BadArgument();
8992 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008993 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008994
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008995 if (PyUnicode_READY(input) == -1)
8996 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008997 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008998 kind = PyUnicode_KIND(input);
8999 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009000
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009001 if (size == 0)
9002 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009003
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009004 /* allocate enough for a simple 1:1 translation without
9005 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02009006 _PyUnicodeWriter_Init(&writer);
9007 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009008 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009009
Victor Stinner872b2912014-04-05 14:27:07 +02009010 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9011
Victor Stinner33798672016-03-01 21:59:58 +01009012 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009013 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01009014 if (PyUnicode_IS_ASCII(input)) {
9015 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9016 if (res < 0) {
9017 _PyUnicodeWriter_Dealloc(&writer);
9018 return NULL;
9019 }
9020 if (res == 1)
9021 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009022 }
Victor Stinner33798672016-03-01 21:59:58 +01009023 else {
9024 i = 0;
9025 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009026
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009027 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009028 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009029 int translate;
9030 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9031 Py_ssize_t newpos;
9032 /* startpos for collecting untranslatable chars */
9033 Py_ssize_t collstart;
9034 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009035 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009036
Victor Stinner1194ea02014-04-04 19:37:40 +02009037 ch = PyUnicode_READ(kind, data, i);
9038 translate = charmaptranslate_output(ch, mapping, &writer);
9039 if (translate < 0)
9040 goto onError;
9041
9042 if (translate != 0) {
9043 /* it worked => adjust input pointer */
9044 ++i;
9045 continue;
9046 }
9047
9048 /* untranslatable character */
9049 collstart = i;
9050 collend = i+1;
9051
9052 /* find all untranslatable characters */
9053 while (collend < size) {
9054 PyObject *x;
9055 ch = PyUnicode_READ(kind, data, collend);
9056 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009057 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009058 Py_XDECREF(x);
9059 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009060 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009061 ++collend;
9062 }
9063
9064 if (ignore) {
9065 i = collend;
9066 }
9067 else {
9068 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9069 reason, input, &exc,
9070 collstart, collend, &newpos);
9071 if (repunicode == NULL)
9072 goto onError;
9073 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009074 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009075 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009076 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009077 Py_DECREF(repunicode);
9078 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009079 }
9080 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009081 Py_XDECREF(exc);
9082 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009083 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009084
Benjamin Peterson29060642009-01-31 22:14:21 +00009085 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009086 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009087 Py_XDECREF(exc);
9088 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009089 return NULL;
9090}
9091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092/* Deprecated. Use PyUnicode_Translate instead. */
9093PyObject *
9094PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9095 Py_ssize_t size,
9096 PyObject *mapping,
9097 const char *errors)
9098{
Christian Heimes5f520f42012-09-11 14:03:25 +02009099 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009100 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9101 if (!unicode)
9102 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009103 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9104 Py_DECREF(unicode);
9105 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009106}
9107
Alexander Belopolsky40018472011-02-26 01:02:56 +00009108PyObject *
9109PyUnicode_Translate(PyObject *str,
9110 PyObject *mapping,
9111 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009112{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009113 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009114 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009115 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009116}
Tim Petersced69f82003-09-16 20:30:58 +00009117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009118static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009119fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120{
9121 /* No need to call PyUnicode_READY(self) because this function is only
9122 called as a callback from fixup() which does it already. */
9123 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9124 const int kind = PyUnicode_KIND(self);
9125 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009126 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009127 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009128 Py_ssize_t i;
9129
9130 for (i = 0; i < len; ++i) {
9131 ch = PyUnicode_READ(kind, data, i);
9132 fixed = 0;
9133 if (ch > 127) {
9134 if (Py_UNICODE_ISSPACE(ch))
9135 fixed = ' ';
9136 else {
9137 const int decimal = Py_UNICODE_TODECIMAL(ch);
9138 if (decimal >= 0)
9139 fixed = '0' + decimal;
9140 }
9141 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009142 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009143 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009144 PyUnicode_WRITE(kind, data, i, fixed);
9145 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009146 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009147 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009149 }
9150
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009151 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009152}
9153
9154PyObject *
9155_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9156{
9157 if (!PyUnicode_Check(unicode)) {
9158 PyErr_BadInternalCall();
9159 return NULL;
9160 }
9161 if (PyUnicode_READY(unicode) == -1)
9162 return NULL;
9163 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9164 /* If the string is already ASCII, just return the same string */
9165 Py_INCREF(unicode);
9166 return unicode;
9167 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009168 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169}
9170
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009171PyObject *
9172PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9173 Py_ssize_t length)
9174{
Victor Stinnerf0124502011-11-21 23:12:56 +01009175 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009176 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009177 Py_UCS4 maxchar;
9178 enum PyUnicode_Kind kind;
9179 void *data;
9180
Victor Stinner99d7ad02012-02-22 13:37:39 +01009181 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009182 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009183 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009184 if (ch > 127) {
9185 int decimal = Py_UNICODE_TODECIMAL(ch);
9186 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009187 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009188 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009189 }
9190 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009191
9192 /* Copy to a new string */
9193 decimal = PyUnicode_New(length, maxchar);
9194 if (decimal == NULL)
9195 return decimal;
9196 kind = PyUnicode_KIND(decimal);
9197 data = PyUnicode_DATA(decimal);
9198 /* Iterate over code points */
9199 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009200 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009201 if (ch > 127) {
9202 int decimal = Py_UNICODE_TODECIMAL(ch);
9203 if (decimal >= 0)
9204 ch = '0' + decimal;
9205 }
9206 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009207 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009208 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009209}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009210/* --- Decimal Encoder ---------------------------------------------------- */
9211
Alexander Belopolsky40018472011-02-26 01:02:56 +00009212int
9213PyUnicode_EncodeDecimal(Py_UNICODE *s,
9214 Py_ssize_t length,
9215 char *output,
9216 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009217{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009218 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009219 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009220 enum PyUnicode_Kind kind;
9221 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009222
9223 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009224 PyErr_BadArgument();
9225 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009226 }
9227
Victor Stinner42bf7752011-11-21 22:52:58 +01009228 unicode = PyUnicode_FromUnicode(s, length);
9229 if (unicode == NULL)
9230 return -1;
9231
Benjamin Petersonbac79492012-01-14 13:34:47 -05009232 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009233 Py_DECREF(unicode);
9234 return -1;
9235 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009236 kind = PyUnicode_KIND(unicode);
9237 data = PyUnicode_DATA(unicode);
9238
Victor Stinnerb84d7232011-11-22 01:50:07 +01009239 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009240 PyObject *exc;
9241 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009242 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009243 Py_ssize_t startpos;
9244
9245 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009246
Benjamin Peterson29060642009-01-31 22:14:21 +00009247 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009248 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009249 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009250 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009251 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009252 decimal = Py_UNICODE_TODECIMAL(ch);
9253 if (decimal >= 0) {
9254 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009255 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009256 continue;
9257 }
9258 if (0 < ch && ch < 256) {
9259 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009260 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009261 continue;
9262 }
Victor Stinner6345be92011-11-25 20:09:01 +01009263
Victor Stinner42bf7752011-11-21 22:52:58 +01009264 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009265 exc = NULL;
9266 raise_encode_exception(&exc, "decimal", unicode,
9267 startpos, startpos+1,
9268 "invalid decimal Unicode string");
9269 Py_XDECREF(exc);
9270 Py_DECREF(unicode);
9271 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009272 }
9273 /* 0-terminate the output string */
9274 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009275 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009276 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009277}
9278
Guido van Rossumd57fd912000-03-10 22:53:23 +00009279/* --- Helpers ------------------------------------------------------------ */
9280
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009281/* helper macro to fixup start/end slice values */
9282#define ADJUST_INDICES(start, end, len) \
9283 if (end > len) \
9284 end = len; \
9285 else if (end < 0) { \
9286 end += len; \
9287 if (end < 0) \
9288 end = 0; \
9289 } \
9290 if (start < 0) { \
9291 start += len; \
9292 if (start < 0) \
9293 start = 0; \
9294 }
9295
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009297any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009299 Py_ssize_t end,
9300 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009302 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303 void *buf1, *buf2;
9304 Py_ssize_t len1, len2, result;
9305
9306 kind1 = PyUnicode_KIND(s1);
9307 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009308 if (kind1 < kind2)
9309 return -1;
9310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009311 len1 = PyUnicode_GET_LENGTH(s1);
9312 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009313 ADJUST_INDICES(start, end, len1);
9314 if (end - start < len2)
9315 return -1;
9316
9317 buf1 = PyUnicode_DATA(s1);
9318 buf2 = PyUnicode_DATA(s2);
9319 if (len2 == 1) {
9320 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9321 result = findchar((const char *)buf1 + kind1*start,
9322 kind1, end - start, ch, direction);
9323 if (result == -1)
9324 return -1;
9325 else
9326 return start + result;
9327 }
9328
9329 if (kind2 != kind1) {
9330 buf2 = _PyUnicode_AsKind(s2, kind1);
9331 if (!buf2)
9332 return -2;
9333 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009334
Victor Stinner794d5672011-10-10 03:21:36 +02009335 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009336 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009337 case PyUnicode_1BYTE_KIND:
9338 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9339 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9340 else
9341 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9342 break;
9343 case PyUnicode_2BYTE_KIND:
9344 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9345 break;
9346 case PyUnicode_4BYTE_KIND:
9347 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9348 break;
9349 default:
9350 assert(0); result = -2;
9351 }
9352 }
9353 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009354 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009355 case PyUnicode_1BYTE_KIND:
9356 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9357 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9358 else
9359 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9360 break;
9361 case PyUnicode_2BYTE_KIND:
9362 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9363 break;
9364 case PyUnicode_4BYTE_KIND:
9365 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9366 break;
9367 default:
9368 assert(0); result = -2;
9369 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370 }
9371
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009372 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009373 PyMem_Free(buf2);
9374
9375 return result;
9376}
9377
9378Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009379_PyUnicode_InsertThousandsGrouping(
9380 PyObject *unicode, Py_ssize_t index,
9381 Py_ssize_t n_buffer,
9382 void *digits, Py_ssize_t n_digits,
9383 Py_ssize_t min_width,
9384 const char *grouping, PyObject *thousands_sep,
9385 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386{
Victor Stinner41a863c2012-02-24 00:37:51 +01009387 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009388 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009389 Py_ssize_t thousands_sep_len;
9390 Py_ssize_t len;
9391
9392 if (unicode != NULL) {
9393 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009394 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009395 }
9396 else {
9397 kind = PyUnicode_1BYTE_KIND;
9398 data = NULL;
9399 }
9400 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9401 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9402 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9403 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009404 if (thousands_sep_kind < kind) {
9405 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9406 if (!thousands_sep_data)
9407 return -1;
9408 }
9409 else {
9410 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9411 if (!data)
9412 return -1;
9413 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009414 }
9415
Benjamin Petersonead6b532011-12-20 17:23:42 -06009416 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009417 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009418 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009419 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009420 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009421 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009422 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009423 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009424 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009425 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009426 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009427 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009428 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009430 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009431 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009432 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009433 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009434 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009435 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009436 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009437 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009438 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009439 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009440 break;
9441 default:
9442 assert(0);
9443 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009445 if (unicode != NULL && thousands_sep_kind != kind) {
9446 if (thousands_sep_kind < kind)
9447 PyMem_Free(thousands_sep_data);
9448 else
9449 PyMem_Free(data);
9450 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009451 if (unicode == NULL) {
9452 *maxchar = 127;
9453 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009454 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009455 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009456 }
9457 }
9458 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459}
9460
9461
Alexander Belopolsky40018472011-02-26 01:02:56 +00009462Py_ssize_t
9463PyUnicode_Count(PyObject *str,
9464 PyObject *substr,
9465 Py_ssize_t start,
9466 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009467{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009468 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009469 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 void *buf1 = NULL, *buf2 = NULL;
9471 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009472
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009473 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009474 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009475
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009476 kind1 = PyUnicode_KIND(str);
9477 kind2 = PyUnicode_KIND(substr);
9478 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009479 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009480
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009481 len1 = PyUnicode_GET_LENGTH(str);
9482 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009484 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009485 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009486
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009487 buf1 = PyUnicode_DATA(str);
9488 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009489 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009490 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009491 if (!buf2)
9492 goto onError;
9493 }
9494
9495 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009496 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009497 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009498 result = asciilib_count(
9499 ((Py_UCS1*)buf1) + start, end - start,
9500 buf2, len2, PY_SSIZE_T_MAX
9501 );
9502 else
9503 result = ucs1lib_count(
9504 ((Py_UCS1*)buf1) + start, end - start,
9505 buf2, len2, PY_SSIZE_T_MAX
9506 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009507 break;
9508 case PyUnicode_2BYTE_KIND:
9509 result = ucs2lib_count(
9510 ((Py_UCS2*)buf1) + start, end - start,
9511 buf2, len2, PY_SSIZE_T_MAX
9512 );
9513 break;
9514 case PyUnicode_4BYTE_KIND:
9515 result = ucs4lib_count(
9516 ((Py_UCS4*)buf1) + start, end - start,
9517 buf2, len2, PY_SSIZE_T_MAX
9518 );
9519 break;
9520 default:
9521 assert(0); result = 0;
9522 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009523
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009524 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525 PyMem_Free(buf2);
9526
Guido van Rossumd57fd912000-03-10 22:53:23 +00009527 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009528 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009529 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009530 PyMem_Free(buf2);
9531 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009532}
9533
Alexander Belopolsky40018472011-02-26 01:02:56 +00009534Py_ssize_t
9535PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009536 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009537 Py_ssize_t start,
9538 Py_ssize_t end,
9539 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009540{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009541 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009542 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009543
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009544 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009545}
9546
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009547Py_ssize_t
9548PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9549 Py_ssize_t start, Py_ssize_t end,
9550 int direction)
9551{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009552 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009553 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009554 if (PyUnicode_READY(str) == -1)
9555 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009556 if (start < 0 || end < 0) {
9557 PyErr_SetString(PyExc_IndexError, "string index out of range");
9558 return -2;
9559 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 if (end > PyUnicode_GET_LENGTH(str))
9561 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009562 if (start >= end)
9563 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009564 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009565 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9566 kind, end-start, ch, direction);
9567 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009569 else
9570 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009571}
9572
Alexander Belopolsky40018472011-02-26 01:02:56 +00009573static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009574tailmatch(PyObject *self,
9575 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009576 Py_ssize_t start,
9577 Py_ssize_t end,
9578 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009579{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009580 int kind_self;
9581 int kind_sub;
9582 void *data_self;
9583 void *data_sub;
9584 Py_ssize_t offset;
9585 Py_ssize_t i;
9586 Py_ssize_t end_sub;
9587
9588 if (PyUnicode_READY(self) == -1 ||
9589 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009590 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009591
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009592 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9593 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009594 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009595 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009596
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009597 if (PyUnicode_GET_LENGTH(substring) == 0)
9598 return 1;
9599
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009600 kind_self = PyUnicode_KIND(self);
9601 data_self = PyUnicode_DATA(self);
9602 kind_sub = PyUnicode_KIND(substring);
9603 data_sub = PyUnicode_DATA(substring);
9604 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9605
9606 if (direction > 0)
9607 offset = end;
9608 else
9609 offset = start;
9610
9611 if (PyUnicode_READ(kind_self, data_self, offset) ==
9612 PyUnicode_READ(kind_sub, data_sub, 0) &&
9613 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9614 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9615 /* If both are of the same kind, memcmp is sufficient */
9616 if (kind_self == kind_sub) {
9617 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009618 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009619 data_sub,
9620 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009621 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009622 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009623 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009624 else {
9625 /* We do not need to compare 0 and len(substring)-1 because
9626 the if statement above ensured already that they are equal
9627 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009628 for (i = 1; i < end_sub; ++i) {
9629 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9630 PyUnicode_READ(kind_sub, data_sub, i))
9631 return 0;
9632 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009633 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009635 }
9636
9637 return 0;
9638}
9639
Alexander Belopolsky40018472011-02-26 01:02:56 +00009640Py_ssize_t
9641PyUnicode_Tailmatch(PyObject *str,
9642 PyObject *substr,
9643 Py_ssize_t start,
9644 Py_ssize_t end,
9645 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009646{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009647 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009648 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009649
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009650 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009651}
9652
Guido van Rossumd57fd912000-03-10 22:53:23 +00009653/* Apply fixfct filter to the Unicode object self and return a
9654 reference to the modified object */
9655
Alexander Belopolsky40018472011-02-26 01:02:56 +00009656static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009657fixup(PyObject *self,
9658 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009659{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009660 PyObject *u;
9661 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009662 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009663
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009664 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009665 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009666 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009667 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009669 /* fix functions return the new maximum character in a string,
9670 if the kind of the resulting unicode object does not change,
9671 everything is fine. Otherwise we need to change the string kind
9672 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009673 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009674
9675 if (maxchar_new == 0) {
9676 /* no changes */;
9677 if (PyUnicode_CheckExact(self)) {
9678 Py_DECREF(u);
9679 Py_INCREF(self);
9680 return self;
9681 }
9682 else
9683 return u;
9684 }
9685
Victor Stinnere6abb482012-05-02 01:15:40 +02009686 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009687
Victor Stinnereaab6042011-12-11 22:22:39 +01009688 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009689 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009690
9691 /* In case the maximum character changed, we need to
9692 convert the string to the new category. */
9693 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9694 if (v == NULL) {
9695 Py_DECREF(u);
9696 return NULL;
9697 }
9698 if (maxchar_new > maxchar_old) {
9699 /* If the maxchar increased so that the kind changed, not all
9700 characters are representable anymore and we need to fix the
9701 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009702 _PyUnicode_FastCopyCharacters(v, 0,
9703 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009704 maxchar_old = fixfct(v);
9705 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009706 }
9707 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009708 _PyUnicode_FastCopyCharacters(v, 0,
9709 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009710 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009711 Py_DECREF(u);
9712 assert(_PyUnicode_CheckConsistency(v, 1));
9713 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009714}
9715
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009716static PyObject *
9717ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009718{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009719 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9720 char *resdata, *data = PyUnicode_DATA(self);
9721 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009722
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009723 res = PyUnicode_New(len, 127);
9724 if (res == NULL)
9725 return NULL;
9726 resdata = PyUnicode_DATA(res);
9727 if (lower)
9728 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009729 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009730 _Py_bytes_upper(resdata, data, len);
9731 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009732}
9733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009734static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009735handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009736{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009737 Py_ssize_t j;
9738 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009739 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009740 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009741
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009742 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9743
9744 where ! is a negation and \p{xxx} is a character with property xxx.
9745 */
9746 for (j = i - 1; j >= 0; j--) {
9747 c = PyUnicode_READ(kind, data, j);
9748 if (!_PyUnicode_IsCaseIgnorable(c))
9749 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009750 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009751 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9752 if (final_sigma) {
9753 for (j = i + 1; j < length; j++) {
9754 c = PyUnicode_READ(kind, data, j);
9755 if (!_PyUnicode_IsCaseIgnorable(c))
9756 break;
9757 }
9758 final_sigma = j == length || !_PyUnicode_IsCased(c);
9759 }
9760 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009761}
9762
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009763static int
9764lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9765 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009766{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009767 /* Obscure special case. */
9768 if (c == 0x3A3) {
9769 mapped[0] = handle_capital_sigma(kind, data, length, i);
9770 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009771 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009772 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009773}
9774
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009775static Py_ssize_t
9776do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009777{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009778 Py_ssize_t i, k = 0;
9779 int n_res, j;
9780 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009781
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009782 c = PyUnicode_READ(kind, data, 0);
9783 n_res = _PyUnicode_ToUpperFull(c, mapped);
9784 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009785 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009786 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009787 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009788 for (i = 1; i < length; i++) {
9789 c = PyUnicode_READ(kind, data, i);
9790 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9791 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009792 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009793 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009794 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009795 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009796 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009797}
9798
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009799static Py_ssize_t
9800do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9801 Py_ssize_t i, k = 0;
9802
9803 for (i = 0; i < length; i++) {
9804 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9805 int n_res, j;
9806 if (Py_UNICODE_ISUPPER(c)) {
9807 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9808 }
9809 else if (Py_UNICODE_ISLOWER(c)) {
9810 n_res = _PyUnicode_ToUpperFull(c, mapped);
9811 }
9812 else {
9813 n_res = 1;
9814 mapped[0] = c;
9815 }
9816 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009817 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009818 res[k++] = mapped[j];
9819 }
9820 }
9821 return k;
9822}
9823
9824static Py_ssize_t
9825do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9826 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009827{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009828 Py_ssize_t i, k = 0;
9829
9830 for (i = 0; i < length; i++) {
9831 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9832 int n_res, j;
9833 if (lower)
9834 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9835 else
9836 n_res = _PyUnicode_ToUpperFull(c, mapped);
9837 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009838 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009839 res[k++] = mapped[j];
9840 }
9841 }
9842 return k;
9843}
9844
9845static Py_ssize_t
9846do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9847{
9848 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9849}
9850
9851static Py_ssize_t
9852do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9853{
9854 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9855}
9856
Benjamin Petersone51757f2012-01-12 21:10:29 -05009857static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009858do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9859{
9860 Py_ssize_t i, k = 0;
9861
9862 for (i = 0; i < length; i++) {
9863 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9864 Py_UCS4 mapped[3];
9865 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9866 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009867 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009868 res[k++] = mapped[j];
9869 }
9870 }
9871 return k;
9872}
9873
9874static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009875do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9876{
9877 Py_ssize_t i, k = 0;
9878 int previous_is_cased;
9879
9880 previous_is_cased = 0;
9881 for (i = 0; i < length; i++) {
9882 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9883 Py_UCS4 mapped[3];
9884 int n_res, j;
9885
9886 if (previous_is_cased)
9887 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9888 else
9889 n_res = _PyUnicode_ToTitleFull(c, mapped);
9890
9891 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009892 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009893 res[k++] = mapped[j];
9894 }
9895
9896 previous_is_cased = _PyUnicode_IsCased(c);
9897 }
9898 return k;
9899}
9900
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009901static PyObject *
9902case_operation(PyObject *self,
9903 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9904{
9905 PyObject *res = NULL;
9906 Py_ssize_t length, newlength = 0;
9907 int kind, outkind;
9908 void *data, *outdata;
9909 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9910
Benjamin Petersoneea48462012-01-16 14:28:50 -05009911 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009912
9913 kind = PyUnicode_KIND(self);
9914 data = PyUnicode_DATA(self);
9915 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009916 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009917 PyErr_SetString(PyExc_OverflowError, "string is too long");
9918 return NULL;
9919 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009920 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009921 if (tmp == NULL)
9922 return PyErr_NoMemory();
9923 newlength = perform(kind, data, length, tmp, &maxchar);
9924 res = PyUnicode_New(newlength, maxchar);
9925 if (res == NULL)
9926 goto leave;
9927 tmpend = tmp + newlength;
9928 outdata = PyUnicode_DATA(res);
9929 outkind = PyUnicode_KIND(res);
9930 switch (outkind) {
9931 case PyUnicode_1BYTE_KIND:
9932 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9933 break;
9934 case PyUnicode_2BYTE_KIND:
9935 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9936 break;
9937 case PyUnicode_4BYTE_KIND:
9938 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9939 break;
9940 default:
9941 assert(0);
9942 break;
9943 }
9944 leave:
9945 PyMem_FREE(tmp);
9946 return res;
9947}
9948
Tim Peters8ce9f162004-08-27 01:49:32 +00009949PyObject *
9950PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009951{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009952 PyObject *res;
9953 PyObject *fseq;
9954 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009955 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009956
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009957 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009958 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009959 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009960 }
9961
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009962 /* NOTE: the following code can't call back into Python code,
9963 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009964 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009965
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009966 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009967 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009968 res = _PyUnicode_JoinArray(separator, items, seqlen);
9969 Py_DECREF(fseq);
9970 return res;
9971}
9972
9973PyObject *
9974_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9975{
9976 PyObject *res = NULL; /* the result */
9977 PyObject *sep = NULL;
9978 Py_ssize_t seplen;
9979 PyObject *item;
9980 Py_ssize_t sz, i, res_offset;
9981 Py_UCS4 maxchar;
9982 Py_UCS4 item_maxchar;
9983 int use_memcpy;
9984 unsigned char *res_data = NULL, *sep_data = NULL;
9985 PyObject *last_obj;
9986 unsigned int kind = 0;
9987
Tim Peters05eba1f2004-08-27 21:32:02 +00009988 /* If empty sequence, return u"". */
9989 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009990 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009991 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009992
Tim Peters05eba1f2004-08-27 21:32:02 +00009993 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009994 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009995 if (seqlen == 1) {
9996 if (PyUnicode_CheckExact(items[0])) {
9997 res = items[0];
9998 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009999 return res;
10000 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010001 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +020010002 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +000010003 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010004 else {
Victor Stinneracf47b82011-10-06 12:32:37 +020010005 /* Set up sep and seplen */
10006 if (separator == NULL) {
10007 /* fall back to a blank space separator */
10008 sep = PyUnicode_FromOrdinal(' ');
10009 if (!sep)
10010 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +020010011 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +020010012 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +000010013 }
Victor Stinneracf47b82011-10-06 12:32:37 +020010014 else {
10015 if (!PyUnicode_Check(separator)) {
10016 PyErr_Format(PyExc_TypeError,
10017 "separator: expected str instance,"
10018 " %.80s found",
10019 Py_TYPE(separator)->tp_name);
10020 goto onError;
10021 }
10022 if (PyUnicode_READY(separator))
10023 goto onError;
10024 sep = separator;
10025 seplen = PyUnicode_GET_LENGTH(separator);
10026 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10027 /* inc refcount to keep this code path symmetric with the
10028 above case of a blank separator */
10029 Py_INCREF(sep);
10030 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010031 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +000010032 }
10033
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010034 /* There are at least two things to join, or else we have a subclass
10035 * of str in the sequence.
10036 * Do a pre-pass to figure out the total amount of space we'll
10037 * need (sz), and see whether all argument are strings.
10038 */
10039 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +020010040#ifdef Py_DEBUG
10041 use_memcpy = 0;
10042#else
10043 use_memcpy = 1;
10044#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010045 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +080010046 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010047 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010048 if (!PyUnicode_Check(item)) {
10049 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +020010050 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +000010051 " %.80s found",
10052 i, Py_TYPE(item)->tp_name);
10053 goto onError;
10054 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 if (PyUnicode_READY(item) == -1)
10056 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010057 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010059 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010060 if (i != 0) {
10061 add_sz += seplen;
10062 }
10063 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010064 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010065 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010066 goto onError;
10067 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010068 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010069 if (use_memcpy && last_obj != NULL) {
10070 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10071 use_memcpy = 0;
10072 }
10073 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010074 }
Tim Petersced69f82003-09-16 20:30:58 +000010075
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010077 if (res == NULL)
10078 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010079
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010080 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010081#ifdef Py_DEBUG
10082 use_memcpy = 0;
10083#else
10084 if (use_memcpy) {
10085 res_data = PyUnicode_1BYTE_DATA(res);
10086 kind = PyUnicode_KIND(res);
10087 if (seplen != 0)
10088 sep_data = PyUnicode_1BYTE_DATA(sep);
10089 }
10090#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010091 if (use_memcpy) {
10092 for (i = 0; i < seqlen; ++i) {
10093 Py_ssize_t itemlen;
10094 item = items[i];
10095
10096 /* Copy item, and maybe the separator. */
10097 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010098 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010099 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010100 kind * seplen);
10101 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010102 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010103
10104 itemlen = PyUnicode_GET_LENGTH(item);
10105 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010106 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010107 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010108 kind * itemlen);
10109 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010110 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010111 }
10112 assert(res_data == PyUnicode_1BYTE_DATA(res)
10113 + kind * PyUnicode_GET_LENGTH(res));
10114 }
10115 else {
10116 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10117 Py_ssize_t itemlen;
10118 item = items[i];
10119
10120 /* Copy item, and maybe the separator. */
10121 if (i && seplen != 0) {
10122 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10123 res_offset += seplen;
10124 }
10125
10126 itemlen = PyUnicode_GET_LENGTH(item);
10127 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010128 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010129 res_offset += itemlen;
10130 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010131 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010132 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010133 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010136 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010138
Benjamin Peterson29060642009-01-31 22:14:21 +000010139 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010141 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010142 return NULL;
10143}
10144
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145#define FILL(kind, data, value, start, length) \
10146 do { \
10147 Py_ssize_t i_ = 0; \
10148 assert(kind != PyUnicode_WCHAR_KIND); \
10149 switch ((kind)) { \
10150 case PyUnicode_1BYTE_KIND: { \
10151 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010152 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 break; \
10154 } \
10155 case PyUnicode_2BYTE_KIND: { \
10156 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10157 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10158 break; \
10159 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010160 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10162 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10163 break; \
10164 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010165 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 } \
10167 } while (0)
10168
Victor Stinnerd3f08822012-05-29 12:57:52 +020010169void
10170_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10171 Py_UCS4 fill_char)
10172{
10173 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10174 const void *data = PyUnicode_DATA(unicode);
10175 assert(PyUnicode_IS_READY(unicode));
10176 assert(unicode_modifiable(unicode));
10177 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10178 assert(start >= 0);
10179 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10180 FILL(kind, data, fill_char, start, length);
10181}
10182
Victor Stinner3fe55312012-01-04 00:33:50 +010010183Py_ssize_t
10184PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10185 Py_UCS4 fill_char)
10186{
10187 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010188
10189 if (!PyUnicode_Check(unicode)) {
10190 PyErr_BadInternalCall();
10191 return -1;
10192 }
10193 if (PyUnicode_READY(unicode) == -1)
10194 return -1;
10195 if (unicode_check_modifiable(unicode))
10196 return -1;
10197
Victor Stinnerd3f08822012-05-29 12:57:52 +020010198 if (start < 0) {
10199 PyErr_SetString(PyExc_IndexError, "string index out of range");
10200 return -1;
10201 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010202 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10203 PyErr_SetString(PyExc_ValueError,
10204 "fill character is bigger than "
10205 "the string maximum character");
10206 return -1;
10207 }
10208
10209 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10210 length = Py_MIN(maxlen, length);
10211 if (length <= 0)
10212 return 0;
10213
Victor Stinnerd3f08822012-05-29 12:57:52 +020010214 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010215 return length;
10216}
10217
Victor Stinner9310abb2011-10-05 00:59:23 +020010218static PyObject *
10219pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010220 Py_ssize_t left,
10221 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010223{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 PyObject *u;
10225 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010226 int kind;
10227 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010228
10229 if (left < 0)
10230 left = 0;
10231 if (right < 0)
10232 right = 0;
10233
Victor Stinnerc4b49542011-12-11 22:44:26 +010010234 if (left == 0 && right == 0)
10235 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010236
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10238 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010239 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10240 return NULL;
10241 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010243 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010245 if (!u)
10246 return NULL;
10247
10248 kind = PyUnicode_KIND(u);
10249 data = PyUnicode_DATA(u);
10250 if (left)
10251 FILL(kind, data, fill, 0, left);
10252 if (right)
10253 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010254 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010255 assert(_PyUnicode_CheckConsistency(u, 1));
10256 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010257}
10258
Alexander Belopolsky40018472011-02-26 01:02:56 +000010259PyObject *
10260PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010261{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010262 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010263
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010264 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010265 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010266
Benjamin Petersonead6b532011-12-20 17:23:42 -060010267 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010269 if (PyUnicode_IS_ASCII(string))
10270 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010271 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010272 PyUnicode_GET_LENGTH(string), keepends);
10273 else
10274 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010275 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010276 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 break;
10278 case PyUnicode_2BYTE_KIND:
10279 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010280 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 PyUnicode_GET_LENGTH(string), keepends);
10282 break;
10283 case PyUnicode_4BYTE_KIND:
10284 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010285 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 PyUnicode_GET_LENGTH(string), keepends);
10287 break;
10288 default:
10289 assert(0);
10290 list = 0;
10291 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010292 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010293}
10294
Alexander Belopolsky40018472011-02-26 01:02:56 +000010295static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010296split(PyObject *self,
10297 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010298 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010300 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 void *buf1, *buf2;
10302 Py_ssize_t len1, len2;
10303 PyObject* out;
10304
Guido van Rossumd57fd912000-03-10 22:53:23 +000010305 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010306 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 if (PyUnicode_READY(self) == -1)
10309 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010311 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010312 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010314 if (PyUnicode_IS_ASCII(self))
10315 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010316 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010317 PyUnicode_GET_LENGTH(self), maxcount
10318 );
10319 else
10320 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010321 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010322 PyUnicode_GET_LENGTH(self), maxcount
10323 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 case PyUnicode_2BYTE_KIND:
10325 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010326 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 PyUnicode_GET_LENGTH(self), maxcount
10328 );
10329 case PyUnicode_4BYTE_KIND:
10330 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010331 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 PyUnicode_GET_LENGTH(self), maxcount
10333 );
10334 default:
10335 assert(0);
10336 return NULL;
10337 }
10338
10339 if (PyUnicode_READY(substring) == -1)
10340 return NULL;
10341
10342 kind1 = PyUnicode_KIND(self);
10343 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 len1 = PyUnicode_GET_LENGTH(self);
10345 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010346 if (kind1 < kind2 || len1 < len2) {
10347 out = PyList_New(1);
10348 if (out == NULL)
10349 return NULL;
10350 Py_INCREF(self);
10351 PyList_SET_ITEM(out, 0, self);
10352 return out;
10353 }
10354 buf1 = PyUnicode_DATA(self);
10355 buf2 = PyUnicode_DATA(substring);
10356 if (kind2 != kind1) {
10357 buf2 = _PyUnicode_AsKind(substring, kind1);
10358 if (!buf2)
10359 return NULL;
10360 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010362 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010364 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10365 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010366 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010367 else
10368 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010369 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 break;
10371 case PyUnicode_2BYTE_KIND:
10372 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010373 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010374 break;
10375 case PyUnicode_4BYTE_KIND:
10376 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010377 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 break;
10379 default:
10380 out = NULL;
10381 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010382 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 PyMem_Free(buf2);
10384 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385}
10386
Alexander Belopolsky40018472011-02-26 01:02:56 +000010387static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010388rsplit(PyObject *self,
10389 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010390 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010391{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010392 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 void *buf1, *buf2;
10394 Py_ssize_t len1, len2;
10395 PyObject* out;
10396
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010397 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010398 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 if (PyUnicode_READY(self) == -1)
10401 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010402
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010404 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010406 if (PyUnicode_IS_ASCII(self))
10407 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010408 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010409 PyUnicode_GET_LENGTH(self), maxcount
10410 );
10411 else
10412 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010413 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010414 PyUnicode_GET_LENGTH(self), maxcount
10415 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 case PyUnicode_2BYTE_KIND:
10417 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010418 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 PyUnicode_GET_LENGTH(self), maxcount
10420 );
10421 case PyUnicode_4BYTE_KIND:
10422 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010423 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 PyUnicode_GET_LENGTH(self), maxcount
10425 );
10426 default:
10427 assert(0);
10428 return NULL;
10429 }
10430
10431 if (PyUnicode_READY(substring) == -1)
10432 return NULL;
10433
10434 kind1 = PyUnicode_KIND(self);
10435 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010436 len1 = PyUnicode_GET_LENGTH(self);
10437 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010438 if (kind1 < kind2 || len1 < len2) {
10439 out = PyList_New(1);
10440 if (out == NULL)
10441 return NULL;
10442 Py_INCREF(self);
10443 PyList_SET_ITEM(out, 0, self);
10444 return out;
10445 }
10446 buf1 = PyUnicode_DATA(self);
10447 buf2 = PyUnicode_DATA(substring);
10448 if (kind2 != kind1) {
10449 buf2 = _PyUnicode_AsKind(substring, kind1);
10450 if (!buf2)
10451 return NULL;
10452 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010453
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010454 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010455 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010456 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10457 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010458 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010459 else
10460 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010461 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010462 break;
10463 case PyUnicode_2BYTE_KIND:
10464 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010465 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 break;
10467 case PyUnicode_4BYTE_KIND:
10468 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010469 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 break;
10471 default:
10472 out = NULL;
10473 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010474 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 PyMem_Free(buf2);
10476 return out;
10477}
10478
10479static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010480anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10481 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010483 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010485 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10486 return asciilib_find(buf1, len1, buf2, len2, offset);
10487 else
10488 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489 case PyUnicode_2BYTE_KIND:
10490 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10491 case PyUnicode_4BYTE_KIND:
10492 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10493 }
10494 assert(0);
10495 return -1;
10496}
10497
10498static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010499anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10500 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010502 switch (kind) {
10503 case PyUnicode_1BYTE_KIND:
10504 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10505 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10506 else
10507 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10508 case PyUnicode_2BYTE_KIND:
10509 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10510 case PyUnicode_4BYTE_KIND:
10511 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10512 }
10513 assert(0);
10514 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010515}
10516
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010517static void
10518replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10519 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10520{
10521 int kind = PyUnicode_KIND(u);
10522 void *data = PyUnicode_DATA(u);
10523 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10524 if (kind == PyUnicode_1BYTE_KIND) {
10525 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10526 (Py_UCS1 *)data + len,
10527 u1, u2, maxcount);
10528 }
10529 else if (kind == PyUnicode_2BYTE_KIND) {
10530 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10531 (Py_UCS2 *)data + len,
10532 u1, u2, maxcount);
10533 }
10534 else {
10535 assert(kind == PyUnicode_4BYTE_KIND);
10536 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10537 (Py_UCS4 *)data + len,
10538 u1, u2, maxcount);
10539 }
10540}
10541
Alexander Belopolsky40018472011-02-26 01:02:56 +000010542static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543replace(PyObject *self, PyObject *str1,
10544 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010545{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 PyObject *u;
10547 char *sbuf = PyUnicode_DATA(self);
10548 char *buf1 = PyUnicode_DATA(str1);
10549 char *buf2 = PyUnicode_DATA(str2);
10550 int srelease = 0, release1 = 0, release2 = 0;
10551 int skind = PyUnicode_KIND(self);
10552 int kind1 = PyUnicode_KIND(str1);
10553 int kind2 = PyUnicode_KIND(str2);
10554 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10555 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10556 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010557 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010558 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010559
10560 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010561 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010562 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010563 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010564
Victor Stinner59de0ee2011-10-07 10:01:28 +020010565 if (str1 == str2)
10566 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010567
Victor Stinner49a0a212011-10-12 23:46:10 +020010568 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010569 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10570 if (maxchar < maxchar_str1)
10571 /* substring too wide to be present */
10572 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010573 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10574 /* Replacing str1 with str2 may cause a maxchar reduction in the
10575 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010576 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010577 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010579 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010580 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010582 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010584 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010585 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010586 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010587
Victor Stinner69ed0f42013-04-09 21:48:24 +020010588 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010589 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010590 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010591 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010592 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010594 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010596
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010597 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10598 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010599 }
10600 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 int rkind = skind;
10602 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010603 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 if (kind1 < rkind) {
10606 /* widen substring */
10607 buf1 = _PyUnicode_AsKind(str1, rkind);
10608 if (!buf1) goto error;
10609 release1 = 1;
10610 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010611 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010612 if (i < 0)
10613 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 if (rkind > kind2) {
10615 /* widen replacement */
10616 buf2 = _PyUnicode_AsKind(str2, rkind);
10617 if (!buf2) goto error;
10618 release2 = 1;
10619 }
10620 else if (rkind < kind2) {
10621 /* widen self and buf1 */
10622 rkind = kind2;
10623 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010624 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 sbuf = _PyUnicode_AsKind(self, rkind);
10626 if (!sbuf) goto error;
10627 srelease = 1;
10628 buf1 = _PyUnicode_AsKind(str1, rkind);
10629 if (!buf1) goto error;
10630 release1 = 1;
10631 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010632 u = PyUnicode_New(slen, maxchar);
10633 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010635 assert(PyUnicode_KIND(u) == rkind);
10636 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010637
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010638 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010639 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010640 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010642 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010643 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010644
10645 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010646 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010647 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010648 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010649 if (i == -1)
10650 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010651 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010653 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010654 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010655 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010657 }
10658 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010659 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010660 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 int rkind = skind;
10662 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010663
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010664 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010665 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 buf1 = _PyUnicode_AsKind(str1, rkind);
10667 if (!buf1) goto error;
10668 release1 = 1;
10669 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010670 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010671 if (n == 0)
10672 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010673 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010674 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 buf2 = _PyUnicode_AsKind(str2, rkind);
10676 if (!buf2) goto error;
10677 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010678 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010680 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 rkind = kind2;
10682 sbuf = _PyUnicode_AsKind(self, rkind);
10683 if (!sbuf) goto error;
10684 srelease = 1;
10685 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010686 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 buf1 = _PyUnicode_AsKind(str1, rkind);
10688 if (!buf1) goto error;
10689 release1 = 1;
10690 }
10691 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10692 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010693 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010694 PyErr_SetString(PyExc_OverflowError,
10695 "replace string is too long");
10696 goto error;
10697 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010698 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010699 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010700 _Py_INCREF_UNICODE_EMPTY();
10701 if (!unicode_empty)
10702 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010703 u = unicode_empty;
10704 goto done;
10705 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010706 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 PyErr_SetString(PyExc_OverflowError,
10708 "replace string is too long");
10709 goto error;
10710 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010711 u = PyUnicode_New(new_size, maxchar);
10712 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010713 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010714 assert(PyUnicode_KIND(u) == rkind);
10715 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010716 ires = i = 0;
10717 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010718 while (n-- > 0) {
10719 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010720 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010721 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010722 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010723 if (j == -1)
10724 break;
10725 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010726 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010727 memcpy(res + rkind * ires,
10728 sbuf + rkind * i,
10729 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010730 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010731 }
10732 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010733 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010734 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010736 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010737 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010738 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010739 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010740 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010741 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010742 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010743 memcpy(res + rkind * ires,
10744 sbuf + rkind * i,
10745 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010746 }
10747 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010748 /* interleave */
10749 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010750 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010751 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010752 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010753 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010754 if (--n <= 0)
10755 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010756 memcpy(res + rkind * ires,
10757 sbuf + rkind * i,
10758 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010759 ires++;
10760 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010761 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010762 memcpy(res + rkind * ires,
10763 sbuf + rkind * i,
10764 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010765 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010766 }
10767
10768 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010769 unicode_adjust_maxchar(&u);
10770 if (u == NULL)
10771 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010772 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010773
10774 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775 if (srelease)
10776 PyMem_FREE(sbuf);
10777 if (release1)
10778 PyMem_FREE(buf1);
10779 if (release2)
10780 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010781 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010783
Benjamin Peterson29060642009-01-31 22:14:21 +000010784 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010785 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786 if (srelease)
10787 PyMem_FREE(sbuf);
10788 if (release1)
10789 PyMem_FREE(buf1);
10790 if (release2)
10791 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010792 return unicode_result_unchanged(self);
10793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 error:
10795 if (srelease && sbuf)
10796 PyMem_FREE(sbuf);
10797 if (release1 && buf1)
10798 PyMem_FREE(buf1);
10799 if (release2 && buf2)
10800 PyMem_FREE(buf2);
10801 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802}
10803
10804/* --- Unicode Object Methods --------------------------------------------- */
10805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010806PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010807 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808\n\
10809Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010810characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010811
10812static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010813unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010814{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010815 if (PyUnicode_READY(self) == -1)
10816 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010817 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818}
10819
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010820PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010821 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010822\n\
10823Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010824have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010825
10826static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010827unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010828{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010829 if (PyUnicode_READY(self) == -1)
10830 return NULL;
10831 if (PyUnicode_GET_LENGTH(self) == 0)
10832 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010833 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010834}
10835
Benjamin Petersond5890c82012-01-14 13:23:30 -050010836PyDoc_STRVAR(casefold__doc__,
10837 "S.casefold() -> str\n\
10838\n\
10839Return a version of S suitable for caseless comparisons.");
10840
10841static PyObject *
10842unicode_casefold(PyObject *self)
10843{
10844 if (PyUnicode_READY(self) == -1)
10845 return NULL;
10846 if (PyUnicode_IS_ASCII(self))
10847 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010848 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010849}
10850
10851
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010852/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010853
10854static int
10855convert_uc(PyObject *obj, void *addr)
10856{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010857 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010858
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010859 if (!PyUnicode_Check(obj)) {
10860 PyErr_Format(PyExc_TypeError,
10861 "The fill character must be a unicode character, "
10862 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010863 return 0;
10864 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010865 if (PyUnicode_READY(obj) < 0)
10866 return 0;
10867 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010868 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010869 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010870 return 0;
10871 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010872 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010873 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010874}
10875
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010876PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010877 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010878\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010879Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010880done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010881
10882static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010883unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010885 Py_ssize_t marg, left;
10886 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010887 Py_UCS4 fillchar = ' ';
10888
Victor Stinnere9a29352011-10-01 02:14:59 +020010889 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010890 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010891
Benjamin Petersonbac79492012-01-14 13:34:47 -050010892 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010893 return NULL;
10894
Victor Stinnerc4b49542011-12-11 22:44:26 +010010895 if (PyUnicode_GET_LENGTH(self) >= width)
10896 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010897
Victor Stinnerc4b49542011-12-11 22:44:26 +010010898 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899 left = marg / 2 + (marg & width & 1);
10900
Victor Stinner9310abb2011-10-05 00:59:23 +020010901 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010902}
10903
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010904/* This function assumes that str1 and str2 are readied by the caller. */
10905
Marc-André Lemburge5034372000-08-08 08:04:29 +000010906static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010907unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010908{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010909#define COMPARE(TYPE1, TYPE2) \
10910 do { \
10911 TYPE1* p1 = (TYPE1 *)data1; \
10912 TYPE2* p2 = (TYPE2 *)data2; \
10913 TYPE1* end = p1 + len; \
10914 Py_UCS4 c1, c2; \
10915 for (; p1 != end; p1++, p2++) { \
10916 c1 = *p1; \
10917 c2 = *p2; \
10918 if (c1 != c2) \
10919 return (c1 < c2) ? -1 : 1; \
10920 } \
10921 } \
10922 while (0)
10923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010924 int kind1, kind2;
10925 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010926 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010927
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010928 kind1 = PyUnicode_KIND(str1);
10929 kind2 = PyUnicode_KIND(str2);
10930 data1 = PyUnicode_DATA(str1);
10931 data2 = PyUnicode_DATA(str2);
10932 len1 = PyUnicode_GET_LENGTH(str1);
10933 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010934 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010935
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010936 switch(kind1) {
10937 case PyUnicode_1BYTE_KIND:
10938 {
10939 switch(kind2) {
10940 case PyUnicode_1BYTE_KIND:
10941 {
10942 int cmp = memcmp(data1, data2, len);
10943 /* normalize result of memcmp() into the range [-1; 1] */
10944 if (cmp < 0)
10945 return -1;
10946 if (cmp > 0)
10947 return 1;
10948 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010949 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010950 case PyUnicode_2BYTE_KIND:
10951 COMPARE(Py_UCS1, Py_UCS2);
10952 break;
10953 case PyUnicode_4BYTE_KIND:
10954 COMPARE(Py_UCS1, Py_UCS4);
10955 break;
10956 default:
10957 assert(0);
10958 }
10959 break;
10960 }
10961 case PyUnicode_2BYTE_KIND:
10962 {
10963 switch(kind2) {
10964 case PyUnicode_1BYTE_KIND:
10965 COMPARE(Py_UCS2, Py_UCS1);
10966 break;
10967 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010968 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010969 COMPARE(Py_UCS2, Py_UCS2);
10970 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010971 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010972 case PyUnicode_4BYTE_KIND:
10973 COMPARE(Py_UCS2, Py_UCS4);
10974 break;
10975 default:
10976 assert(0);
10977 }
10978 break;
10979 }
10980 case PyUnicode_4BYTE_KIND:
10981 {
10982 switch(kind2) {
10983 case PyUnicode_1BYTE_KIND:
10984 COMPARE(Py_UCS4, Py_UCS1);
10985 break;
10986 case PyUnicode_2BYTE_KIND:
10987 COMPARE(Py_UCS4, Py_UCS2);
10988 break;
10989 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010990 {
10991#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10992 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10993 /* normalize result of wmemcmp() into the range [-1; 1] */
10994 if (cmp < 0)
10995 return -1;
10996 if (cmp > 0)
10997 return 1;
10998#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010999 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020011000#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011001 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020011002 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011003 default:
11004 assert(0);
11005 }
11006 break;
11007 }
11008 default:
11009 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000011010 }
11011
Victor Stinner770e19e2012-10-04 22:59:45 +020011012 if (len1 == len2)
11013 return 0;
11014 if (len1 < len2)
11015 return -1;
11016 else
11017 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011018
11019#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000011020}
11021
Benjamin Peterson621b4302016-09-09 13:54:34 -070011022static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020011023unicode_compare_eq(PyObject *str1, PyObject *str2)
11024{
11025 int kind;
11026 void *data1, *data2;
11027 Py_ssize_t len;
11028 int cmp;
11029
Victor Stinnere5567ad2012-10-23 02:48:49 +020011030 len = PyUnicode_GET_LENGTH(str1);
11031 if (PyUnicode_GET_LENGTH(str2) != len)
11032 return 0;
11033 kind = PyUnicode_KIND(str1);
11034 if (PyUnicode_KIND(str2) != kind)
11035 return 0;
11036 data1 = PyUnicode_DATA(str1);
11037 data2 = PyUnicode_DATA(str2);
11038
11039 cmp = memcmp(data1, data2, len * kind);
11040 return (cmp == 0);
11041}
11042
11043
Alexander Belopolsky40018472011-02-26 01:02:56 +000011044int
11045PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011046{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011047 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11048 if (PyUnicode_READY(left) == -1 ||
11049 PyUnicode_READY(right) == -1)
11050 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011051
11052 /* a string is equal to itself */
11053 if (left == right)
11054 return 0;
11055
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011056 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011057 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011058 PyErr_Format(PyExc_TypeError,
11059 "Can't compare %.100s and %.100s",
11060 left->ob_type->tp_name,
11061 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011062 return -1;
11063}
11064
Martin v. Löwis5b222132007-06-10 09:51:05 +000011065int
11066PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11067{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011068 Py_ssize_t i;
11069 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011070 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011071 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011072
Victor Stinner910337b2011-10-03 03:20:16 +020011073 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011074 if (!PyUnicode_IS_READY(uni)) {
11075 const wchar_t *ws = _PyUnicode_WSTR(uni);
11076 /* Compare Unicode string and source character set string */
11077 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11078 if (chr != ustr[i])
11079 return (chr < ustr[i]) ? -1 : 1;
11080 }
11081 /* This check keeps Python strings that end in '\0' from comparing equal
11082 to C strings identical up to that point. */
11083 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11084 return 1; /* uni is longer */
11085 if (ustr[i])
11086 return -1; /* str is longer */
11087 return 0;
11088 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011089 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011090 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011091 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011092 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011093 size_t len, len2 = strlen(str);
11094 int cmp;
11095
11096 len = Py_MIN(len1, len2);
11097 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011098 if (cmp != 0) {
11099 if (cmp < 0)
11100 return -1;
11101 else
11102 return 1;
11103 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011104 if (len1 > len2)
11105 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011106 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011107 return -1; /* str is longer */
11108 return 0;
11109 }
11110 else {
11111 void *data = PyUnicode_DATA(uni);
11112 /* Compare Unicode string and source character set string */
11113 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011114 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011115 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11116 /* This check keeps Python strings that end in '\0' from comparing equal
11117 to C strings identical up to that point. */
11118 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11119 return 1; /* uni is longer */
11120 if (str[i])
11121 return -1; /* str is longer */
11122 return 0;
11123 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011124}
11125
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011126static int
11127non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11128{
11129 size_t i, len;
11130 const wchar_t *p;
11131 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11132 if (strlen(str) != len)
11133 return 0;
11134 p = _PyUnicode_WSTR(unicode);
11135 assert(p);
11136 for (i = 0; i < len; i++) {
11137 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011138 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011139 return 0;
11140 }
11141 return 1;
11142}
11143
11144int
11145_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11146{
11147 size_t len;
11148 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011149 assert(str);
11150#ifndef NDEBUG
11151 for (const char *p = str; *p; p++) {
11152 assert((unsigned char)*p < 128);
11153 }
11154#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011155 if (PyUnicode_READY(unicode) == -1) {
11156 /* Memory error or bad data */
11157 PyErr_Clear();
11158 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11159 }
11160 if (!PyUnicode_IS_ASCII(unicode))
11161 return 0;
11162 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11163 return strlen(str) == len &&
11164 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11165}
11166
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011167int
11168_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11169{
11170 PyObject *right_uni;
11171 Py_hash_t hash;
11172
11173 assert(_PyUnicode_CHECK(left));
11174 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011175#ifndef NDEBUG
11176 for (const char *p = right->string; *p; p++) {
11177 assert((unsigned char)*p < 128);
11178 }
11179#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011180
11181 if (PyUnicode_READY(left) == -1) {
11182 /* memory error or bad data */
11183 PyErr_Clear();
11184 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11185 }
11186
11187 if (!PyUnicode_IS_ASCII(left))
11188 return 0;
11189
11190 right_uni = _PyUnicode_FromId(right); /* borrowed */
11191 if (right_uni == NULL) {
11192 /* memory error or bad data */
11193 PyErr_Clear();
11194 return _PyUnicode_EqualToASCIIString(left, right->string);
11195 }
11196
11197 if (left == right_uni)
11198 return 1;
11199
11200 if (PyUnicode_CHECK_INTERNED(left))
11201 return 0;
11202
11203 assert(_PyUnicode_HASH(right_uni) != 1);
11204 hash = _PyUnicode_HASH(left);
11205 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11206 return 0;
11207
11208 return unicode_compare_eq(left, right_uni);
11209}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011210
Benjamin Peterson29060642009-01-31 22:14:21 +000011211#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011212 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011213
Alexander Belopolsky40018472011-02-26 01:02:56 +000011214PyObject *
11215PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011216{
11217 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011218 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011219
Victor Stinnere5567ad2012-10-23 02:48:49 +020011220 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11221 Py_RETURN_NOTIMPLEMENTED;
11222
11223 if (PyUnicode_READY(left) == -1 ||
11224 PyUnicode_READY(right) == -1)
11225 return NULL;
11226
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011227 if (left == right) {
11228 switch (op) {
11229 case Py_EQ:
11230 case Py_LE:
11231 case Py_GE:
11232 /* a string is equal to itself */
11233 v = Py_True;
11234 break;
11235 case Py_NE:
11236 case Py_LT:
11237 case Py_GT:
11238 v = Py_False;
11239 break;
11240 default:
11241 PyErr_BadArgument();
11242 return NULL;
11243 }
11244 }
11245 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011246 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011247 result ^= (op == Py_NE);
11248 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011249 }
11250 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011251 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011252
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011253 /* Convert the return value to a Boolean */
11254 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011255 case Py_LE:
11256 v = TEST_COND(result <= 0);
11257 break;
11258 case Py_GE:
11259 v = TEST_COND(result >= 0);
11260 break;
11261 case Py_LT:
11262 v = TEST_COND(result == -1);
11263 break;
11264 case Py_GT:
11265 v = TEST_COND(result == 1);
11266 break;
11267 default:
11268 PyErr_BadArgument();
11269 return NULL;
11270 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011271 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011272 Py_INCREF(v);
11273 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011274}
11275
Alexander Belopolsky40018472011-02-26 01:02:56 +000011276int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011277_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11278{
11279 return unicode_eq(aa, bb);
11280}
11281
11282int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011283PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011284{
Victor Stinner77282cb2013-04-14 19:22:47 +020011285 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011286 void *buf1, *buf2;
11287 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011288 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011289
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011290 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011291 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011292 "'in <string>' requires string as left operand, not %.100s",
11293 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011294 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011295 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011296 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011297 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011298 if (ensure_unicode(str) < 0)
11299 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011301 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011302 kind2 = PyUnicode_KIND(substr);
11303 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011304 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011305 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011306 len2 = PyUnicode_GET_LENGTH(substr);
11307 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011308 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011309 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011310 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011311 if (len2 == 1) {
11312 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11313 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011314 return result;
11315 }
11316 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011317 buf2 = _PyUnicode_AsKind(substr, kind1);
11318 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011319 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011320 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011321
Victor Stinner77282cb2013-04-14 19:22:47 +020011322 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011323 case PyUnicode_1BYTE_KIND:
11324 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11325 break;
11326 case PyUnicode_2BYTE_KIND:
11327 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11328 break;
11329 case PyUnicode_4BYTE_KIND:
11330 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11331 break;
11332 default:
11333 result = -1;
11334 assert(0);
11335 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011336
Victor Stinner77282cb2013-04-14 19:22:47 +020011337 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338 PyMem_Free(buf2);
11339
Guido van Rossum403d68b2000-03-13 15:55:09 +000011340 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011341}
11342
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343/* Concat to string or Unicode object giving a new Unicode object. */
11344
Alexander Belopolsky40018472011-02-26 01:02:56 +000011345PyObject *
11346PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011348 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011349 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011350 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011352 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11353 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354
11355 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011356 if (left == unicode_empty)
11357 return PyUnicode_FromObject(right);
11358 if (right == unicode_empty)
11359 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011361 left_len = PyUnicode_GET_LENGTH(left);
11362 right_len = PyUnicode_GET_LENGTH(right);
11363 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011364 PyErr_SetString(PyExc_OverflowError,
11365 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011366 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011367 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011368 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011369
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011370 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11371 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011372 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011373
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011375 result = PyUnicode_New(new_len, maxchar);
11376 if (result == NULL)
11377 return NULL;
11378 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11379 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11380 assert(_PyUnicode_CheckConsistency(result, 1));
11381 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011382}
11383
Walter Dörwald1ab83302007-05-18 17:15:44 +000011384void
Victor Stinner23e56682011-10-03 03:54:37 +020011385PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011386{
Victor Stinner23e56682011-10-03 03:54:37 +020011387 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011388 Py_UCS4 maxchar, maxchar2;
11389 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011390
11391 if (p_left == NULL) {
11392 if (!PyErr_Occurred())
11393 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011394 return;
11395 }
Victor Stinner23e56682011-10-03 03:54:37 +020011396 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011397 if (right == NULL || left == NULL
11398 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011399 if (!PyErr_Occurred())
11400 PyErr_BadInternalCall();
11401 goto error;
11402 }
11403
Benjamin Petersonbac79492012-01-14 13:34:47 -050011404 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011405 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011406 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011407 goto error;
11408
Victor Stinner488fa492011-12-12 00:01:39 +010011409 /* Shortcuts */
11410 if (left == unicode_empty) {
11411 Py_DECREF(left);
11412 Py_INCREF(right);
11413 *p_left = right;
11414 return;
11415 }
11416 if (right == unicode_empty)
11417 return;
11418
11419 left_len = PyUnicode_GET_LENGTH(left);
11420 right_len = PyUnicode_GET_LENGTH(right);
11421 if (left_len > PY_SSIZE_T_MAX - right_len) {
11422 PyErr_SetString(PyExc_OverflowError,
11423 "strings are too large to concat");
11424 goto error;
11425 }
11426 new_len = left_len + right_len;
11427
11428 if (unicode_modifiable(left)
11429 && PyUnicode_CheckExact(right)
11430 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011431 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11432 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011433 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011434 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011435 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11436 {
11437 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011438 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011439 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011440
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011441 /* copy 'right' into the newly allocated area of 'left' */
11442 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011443 }
Victor Stinner488fa492011-12-12 00:01:39 +010011444 else {
11445 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11446 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011447 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011448
Victor Stinner488fa492011-12-12 00:01:39 +010011449 /* Concat the two Unicode strings */
11450 res = PyUnicode_New(new_len, maxchar);
11451 if (res == NULL)
11452 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011453 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11454 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011455 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011456 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011457 }
11458 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011459 return;
11460
11461error:
Victor Stinner488fa492011-12-12 00:01:39 +010011462 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011463}
11464
11465void
11466PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11467{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011468 PyUnicode_Append(pleft, right);
11469 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011470}
11471
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011472/*
11473Wraps stringlib_parse_args_finds() and additionally ensures that the
11474first argument is a unicode object.
11475*/
11476
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011477static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011478parse_args_finds_unicode(const char * function_name, PyObject *args,
11479 PyObject **substring,
11480 Py_ssize_t *start, Py_ssize_t *end)
11481{
11482 if(stringlib_parse_args_finds(function_name, args, substring,
11483 start, end)) {
11484 if (ensure_unicode(*substring) < 0)
11485 return 0;
11486 return 1;
11487 }
11488 return 0;
11489}
11490
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011491PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011492 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011494Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011495string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011496interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497
11498static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011499unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011501 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011502 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011503 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011505 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 void *buf1, *buf2;
11507 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011509 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011510 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 kind1 = PyUnicode_KIND(self);
11513 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011514 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011515 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 len1 = PyUnicode_GET_LENGTH(self);
11518 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011520 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011521 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011522
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011523 buf1 = PyUnicode_DATA(self);
11524 buf2 = PyUnicode_DATA(substring);
11525 if (kind2 != kind1) {
11526 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011527 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011528 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011529 }
11530 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011531 case PyUnicode_1BYTE_KIND:
11532 iresult = ucs1lib_count(
11533 ((Py_UCS1*)buf1) + start, end - start,
11534 buf2, len2, PY_SSIZE_T_MAX
11535 );
11536 break;
11537 case PyUnicode_2BYTE_KIND:
11538 iresult = ucs2lib_count(
11539 ((Py_UCS2*)buf1) + start, end - start,
11540 buf2, len2, PY_SSIZE_T_MAX
11541 );
11542 break;
11543 case PyUnicode_4BYTE_KIND:
11544 iresult = ucs4lib_count(
11545 ((Py_UCS4*)buf1) + start, end - start,
11546 buf2, len2, PY_SSIZE_T_MAX
11547 );
11548 break;
11549 default:
11550 assert(0); iresult = 0;
11551 }
11552
11553 result = PyLong_FromSsize_t(iresult);
11554
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011555 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011556 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558 return result;
11559}
11560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011561PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011562 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011564Encode S using the codec registered for encoding. Default encoding\n\
11565is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011566handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011567a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11568'xmlcharrefreplace' as well as any other name registered with\n\
11569codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570
11571static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011572unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011574 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575 char *encoding = NULL;
11576 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011577
Benjamin Peterson308d6372009-09-18 21:42:35 +000011578 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11579 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011581 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011582}
11583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011584PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011585 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586\n\
11587Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011588If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589
11590static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011591unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011593 Py_ssize_t i, j, line_pos, src_len, incr;
11594 Py_UCS4 ch;
11595 PyObject *u;
11596 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011597 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011599 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011600 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601
Ezio Melotti745d54d2013-11-16 19:10:57 +020011602 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11603 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011604 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605
Antoine Pitrou22425222011-10-04 19:10:51 +020011606 if (PyUnicode_READY(self) == -1)
11607 return NULL;
11608
Thomas Wouters7e474022000-07-16 12:04:32 +000011609 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011610 src_len = PyUnicode_GET_LENGTH(self);
11611 i = j = line_pos = 0;
11612 kind = PyUnicode_KIND(self);
11613 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011614 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011615 for (; i < src_len; i++) {
11616 ch = PyUnicode_READ(kind, src_data, i);
11617 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011618 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011619 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011620 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011621 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011622 goto overflow;
11623 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011624 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011625 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011626 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011628 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011629 goto overflow;
11630 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011632 if (ch == '\n' || ch == '\r')
11633 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011634 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011635 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011636 if (!found)
11637 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011638
Guido van Rossumd57fd912000-03-10 22:53:23 +000011639 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011640 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641 if (!u)
11642 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011643 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644
Antoine Pitroue71d5742011-10-04 15:55:09 +020011645 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646
Antoine Pitroue71d5742011-10-04 15:55:09 +020011647 for (; i < src_len; i++) {
11648 ch = PyUnicode_READ(kind, src_data, i);
11649 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011650 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011651 incr = tabsize - (line_pos % tabsize);
11652 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011653 FILL(kind, dest_data, ' ', j, incr);
11654 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011656 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011657 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011658 line_pos++;
11659 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011660 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011661 if (ch == '\n' || ch == '\r')
11662 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011664 }
11665 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011666 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011667
Antoine Pitroue71d5742011-10-04 15:55:09 +020011668 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011669 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11670 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671}
11672
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011673PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011674 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675\n\
11676Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011677such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678arguments start and end are interpreted as in slice notation.\n\
11679\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011680Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681
11682static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011685 /* initialize variables to prevent gcc warning */
11686 PyObject *substring = NULL;
11687 Py_ssize_t start = 0;
11688 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011689 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011691 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011694 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011695 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011697 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011698
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011699 if (result == -2)
11700 return NULL;
11701
Christian Heimes217cfd12007-12-02 14:31:20 +000011702 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703}
11704
11705static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011706unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011708 void *data;
11709 enum PyUnicode_Kind kind;
11710 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011711
Serhiy Storchakaddb536b2017-09-08 10:43:54 +030011712 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011713 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011715 }
Serhiy Storchakaddb536b2017-09-08 10:43:54 +030011716 if (PyUnicode_READY(self) == -1) {
11717 return NULL;
11718 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011719 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11720 PyErr_SetString(PyExc_IndexError, "string index out of range");
11721 return NULL;
11722 }
11723 kind = PyUnicode_KIND(self);
11724 data = PyUnicode_DATA(self);
11725 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011726 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727}
11728
Guido van Rossumc2504932007-09-18 19:42:40 +000011729/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011730 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011731static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011732unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733{
Guido van Rossumc2504932007-09-18 19:42:40 +000011734 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011735 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011736
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011737#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011738 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011739#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011740 if (_PyUnicode_HASH(self) != -1)
11741 return _PyUnicode_HASH(self);
11742 if (PyUnicode_READY(self) == -1)
11743 return -1;
11744 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011745 /*
11746 We make the hash of the empty string be 0, rather than using
11747 (prefix ^ suffix), since this slightly obfuscates the hash secret
11748 */
11749 if (len == 0) {
11750 _PyUnicode_HASH(self) = 0;
11751 return 0;
11752 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011753 x = _Py_HashBytes(PyUnicode_DATA(self),
11754 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011755 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011756 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757}
11758
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011759PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011760 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761\n\
Mariatta577fc042017-04-09 15:17:06 -070011762Return the lowest index in S where substring sub is found, \n\
11763such that sub is contained within S[start:end]. Optional\n\
11764arguments start and end are interpreted as in slice notation.\n\
11765\n\
11766Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011767
11768static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011771 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011772 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011773 PyObject *substring = NULL;
11774 Py_ssize_t start = 0;
11775 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011777 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011780 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011783 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011785 if (result == -2)
11786 return NULL;
11787
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788 if (result < 0) {
11789 PyErr_SetString(PyExc_ValueError, "substring not found");
11790 return NULL;
11791 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011792
Christian Heimes217cfd12007-12-02 14:31:20 +000011793 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794}
11795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011796PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011797 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011799Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011800at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801
11802static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011803unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805 Py_ssize_t i, length;
11806 int kind;
11807 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011808 int cased;
11809
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 if (PyUnicode_READY(self) == -1)
11811 return NULL;
11812 length = PyUnicode_GET_LENGTH(self);
11813 kind = PyUnicode_KIND(self);
11814 data = PyUnicode_DATA(self);
11815
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011817 if (length == 1)
11818 return PyBool_FromLong(
11819 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011821 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011822 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011823 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011824
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 for (i = 0; i < length; i++) {
11827 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011828
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11830 return PyBool_FromLong(0);
11831 else if (!cased && Py_UNICODE_ISLOWER(ch))
11832 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011834 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011835}
11836
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011837PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011838 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011839\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011840Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011841at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842
11843static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011844unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011845{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 Py_ssize_t i, length;
11847 int kind;
11848 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849 int cased;
11850
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011851 if (PyUnicode_READY(self) == -1)
11852 return NULL;
11853 length = PyUnicode_GET_LENGTH(self);
11854 kind = PyUnicode_KIND(self);
11855 data = PyUnicode_DATA(self);
11856
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011858 if (length == 1)
11859 return PyBool_FromLong(
11860 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011862 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011864 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011865
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011867 for (i = 0; i < length; i++) {
11868 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011869
Benjamin Peterson29060642009-01-31 22:14:21 +000011870 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11871 return PyBool_FromLong(0);
11872 else if (!cased && Py_UNICODE_ISUPPER(ch))
11873 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011874 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011875 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876}
11877
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011878PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011879 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011881Return True if S is a titlecased string and there is at least one\n\
11882character in S, i.e. upper- and titlecase characters may only\n\
11883follow uncased characters and lowercase characters only cased ones.\n\
11884Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885
11886static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011887unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 Py_ssize_t i, length;
11890 int kind;
11891 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892 int cased, previous_is_cased;
11893
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011894 if (PyUnicode_READY(self) == -1)
11895 return NULL;
11896 length = PyUnicode_GET_LENGTH(self);
11897 kind = PyUnicode_KIND(self);
11898 data = PyUnicode_DATA(self);
11899
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901 if (length == 1) {
11902 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11903 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11904 (Py_UNICODE_ISUPPER(ch) != 0));
11905 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011907 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011909 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011910
Guido van Rossumd57fd912000-03-10 22:53:23 +000011911 cased = 0;
11912 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011913 for (i = 0; i < length; i++) {
11914 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011915
Benjamin Peterson29060642009-01-31 22:14:21 +000011916 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11917 if (previous_is_cased)
11918 return PyBool_FromLong(0);
11919 previous_is_cased = 1;
11920 cased = 1;
11921 }
11922 else if (Py_UNICODE_ISLOWER(ch)) {
11923 if (!previous_is_cased)
11924 return PyBool_FromLong(0);
11925 previous_is_cased = 1;
11926 cased = 1;
11927 }
11928 else
11929 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011931 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932}
11933
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011934PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011935 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011936\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011937Return True if all characters in S are whitespace\n\
11938and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939
11940static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011941unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011943 Py_ssize_t i, length;
11944 int kind;
11945 void *data;
11946
11947 if (PyUnicode_READY(self) == -1)
11948 return NULL;
11949 length = PyUnicode_GET_LENGTH(self);
11950 kind = PyUnicode_KIND(self);
11951 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011952
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 if (length == 1)
11955 return PyBool_FromLong(
11956 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011957
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011958 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011960 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011962 for (i = 0; i < length; i++) {
11963 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011964 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011965 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011967 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968}
11969
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011970PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011971 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011972\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011973Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011974and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011975
11976static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011977unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011978{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979 Py_ssize_t i, length;
11980 int kind;
11981 void *data;
11982
11983 if (PyUnicode_READY(self) == -1)
11984 return NULL;
11985 length = PyUnicode_GET_LENGTH(self);
11986 kind = PyUnicode_KIND(self);
11987 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011988
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011989 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 if (length == 1)
11991 return PyBool_FromLong(
11992 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011993
11994 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011995 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011996 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011998 for (i = 0; i < length; i++) {
11999 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012000 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012001 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012002 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012003}
12004
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012005PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012006 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012007\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000012008Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012009and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012010
12011static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012012unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012013{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 int kind;
12015 void *data;
12016 Py_ssize_t len, i;
12017
12018 if (PyUnicode_READY(self) == -1)
12019 return NULL;
12020
12021 kind = PyUnicode_KIND(self);
12022 data = PyUnicode_DATA(self);
12023 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012024
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012025 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012026 if (len == 1) {
12027 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12028 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12029 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012030
12031 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012032 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012033 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012034
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012035 for (i = 0; i < len; i++) {
12036 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012037 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000012038 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012039 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012040 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012041}
12042
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012043PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012044 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012045\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000012046Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012047False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012048
12049static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012050unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012051{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012052 Py_ssize_t i, length;
12053 int kind;
12054 void *data;
12055
12056 if (PyUnicode_READY(self) == -1)
12057 return NULL;
12058 length = PyUnicode_GET_LENGTH(self);
12059 kind = PyUnicode_KIND(self);
12060 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012061
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012063 if (length == 1)
12064 return PyBool_FromLong(
12065 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012066
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012067 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012069 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012071 for (i = 0; i < length; i++) {
12072 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012073 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012074 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012075 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012076}
12077
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012078PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012079 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012080\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000012081Return True if all characters in S are digits\n\
12082and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012083
12084static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012085unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012087 Py_ssize_t i, length;
12088 int kind;
12089 void *data;
12090
12091 if (PyUnicode_READY(self) == -1)
12092 return NULL;
12093 length = PyUnicode_GET_LENGTH(self);
12094 kind = PyUnicode_KIND(self);
12095 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096
Guido van Rossumd57fd912000-03-10 22:53:23 +000012097 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012098 if (length == 1) {
12099 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12100 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12101 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012103 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012104 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012105 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012107 for (i = 0; i < length; i++) {
12108 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012109 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012111 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012112}
12113
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012114PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012115 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012116\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000012117Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012118False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119
12120static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012121unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012122{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012123 Py_ssize_t i, length;
12124 int kind;
12125 void *data;
12126
12127 if (PyUnicode_READY(self) == -1)
12128 return NULL;
12129 length = PyUnicode_GET_LENGTH(self);
12130 kind = PyUnicode_KIND(self);
12131 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012134 if (length == 1)
12135 return PyBool_FromLong(
12136 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012138 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012139 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012140 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012142 for (i = 0; i < length; i++) {
12143 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012144 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012146 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147}
12148
Martin v. Löwis47383402007-08-15 07:32:56 +000012149int
12150PyUnicode_IsIdentifier(PyObject *self)
12151{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012152 int kind;
12153 void *data;
12154 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012155 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012156
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012157 if (PyUnicode_READY(self) == -1) {
12158 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012159 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012160 }
12161
12162 /* Special case for empty strings */
12163 if (PyUnicode_GET_LENGTH(self) == 0)
12164 return 0;
12165 kind = PyUnicode_KIND(self);
12166 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012167
12168 /* PEP 3131 says that the first character must be in
12169 XID_Start and subsequent characters in XID_Continue,
12170 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012171 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012172 letters, digits, underscore). However, given the current
12173 definition of XID_Start and XID_Continue, it is sufficient
12174 to check just for these, except that _ must be allowed
12175 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012176 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012177 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012178 return 0;
12179
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012180 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012181 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012182 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012183 return 1;
12184}
12185
12186PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012187 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012188\n\
12189Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012190to the language definition.\n\
12191\n\
12192Use keyword.iskeyword() to test for reserved identifiers\n\
12193such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012194
12195static PyObject*
12196unicode_isidentifier(PyObject *self)
12197{
12198 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12199}
12200
Georg Brandl559e5d72008-06-11 18:37:52 +000012201PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012202 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012203\n\
12204Return True if all characters in S are considered\n\
12205printable in repr() or S is empty, False otherwise.");
12206
12207static PyObject*
12208unicode_isprintable(PyObject *self)
12209{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012210 Py_ssize_t i, length;
12211 int kind;
12212 void *data;
12213
12214 if (PyUnicode_READY(self) == -1)
12215 return NULL;
12216 length = PyUnicode_GET_LENGTH(self);
12217 kind = PyUnicode_KIND(self);
12218 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012219
12220 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221 if (length == 1)
12222 return PyBool_FromLong(
12223 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012224
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012225 for (i = 0; i < length; i++) {
12226 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012227 Py_RETURN_FALSE;
12228 }
12229 }
12230 Py_RETURN_TRUE;
12231}
12232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012233PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012234 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012235\n\
12236Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012237iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238
12239static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012240unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012242 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243}
12244
Martin v. Löwis18e16552006-02-15 17:27:45 +000012245static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012246unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 if (PyUnicode_READY(self) == -1)
12249 return -1;
12250 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251}
12252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012253PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012254 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012256Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012257done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012258
12259static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012260unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012262 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012263 Py_UCS4 fillchar = ' ';
12264
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012265 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012266 return NULL;
12267
Benjamin Petersonbac79492012-01-14 13:34:47 -050012268 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012269 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012270
Victor Stinnerc4b49542011-12-11 22:44:26 +010012271 if (PyUnicode_GET_LENGTH(self) >= width)
12272 return unicode_result_unchanged(self);
12273
12274 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012275}
12276
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012277PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012278 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012280Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281
12282static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012283unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012284{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012285 if (PyUnicode_READY(self) == -1)
12286 return NULL;
12287 if (PyUnicode_IS_ASCII(self))
12288 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012289 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290}
12291
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012292#define LEFTSTRIP 0
12293#define RIGHTSTRIP 1
12294#define BOTHSTRIP 2
12295
12296/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012297static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012298
12299#define STRIPNAME(i) (stripformat[i]+3)
12300
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012301/* externally visible for str.strip(unicode) */
12302PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012303_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012304{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 void *data;
12306 int kind;
12307 Py_ssize_t i, j, len;
12308 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012309 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012311 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12312 return NULL;
12313
12314 kind = PyUnicode_KIND(self);
12315 data = PyUnicode_DATA(self);
12316 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012317 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012318 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12319 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012320 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012321
Benjamin Peterson14339b62009-01-31 16:36:08 +000012322 i = 0;
12323 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012324 while (i < len) {
12325 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12326 if (!BLOOM(sepmask, ch))
12327 break;
12328 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12329 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012330 i++;
12331 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012332 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012333
Benjamin Peterson14339b62009-01-31 16:36:08 +000012334 j = len;
12335 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012336 j--;
12337 while (j >= i) {
12338 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12339 if (!BLOOM(sepmask, ch))
12340 break;
12341 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12342 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012343 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012344 }
12345
Benjamin Peterson29060642009-01-31 22:14:21 +000012346 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012347 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012348
Victor Stinner7931d9a2011-11-04 00:22:48 +010012349 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350}
12351
12352PyObject*
12353PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12354{
12355 unsigned char *data;
12356 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012357 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012358
Victor Stinnerde636f32011-10-01 03:55:54 +020012359 if (PyUnicode_READY(self) == -1)
12360 return NULL;
12361
Victor Stinner684d5fd2012-05-03 02:32:34 +020012362 length = PyUnicode_GET_LENGTH(self);
12363 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012364
Victor Stinner684d5fd2012-05-03 02:32:34 +020012365 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012366 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012367
Victor Stinnerde636f32011-10-01 03:55:54 +020012368 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012369 PyErr_SetString(PyExc_IndexError, "string index out of range");
12370 return NULL;
12371 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012372 if (start >= length || end < start)
12373 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012374
Victor Stinner684d5fd2012-05-03 02:32:34 +020012375 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012376 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012377 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012378 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012379 }
12380 else {
12381 kind = PyUnicode_KIND(self);
12382 data = PyUnicode_1BYTE_DATA(self);
12383 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012384 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012385 length);
12386 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012387}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012388
12389static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012390do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012392 Py_ssize_t len, i, j;
12393
12394 if (PyUnicode_READY(self) == -1)
12395 return NULL;
12396
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012397 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012398
Victor Stinnercc7af722013-04-09 22:39:24 +020012399 if (PyUnicode_IS_ASCII(self)) {
12400 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12401
12402 i = 0;
12403 if (striptype != RIGHTSTRIP) {
12404 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012405 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012406 if (!_Py_ascii_whitespace[ch])
12407 break;
12408 i++;
12409 }
12410 }
12411
12412 j = len;
12413 if (striptype != LEFTSTRIP) {
12414 j--;
12415 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012416 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012417 if (!_Py_ascii_whitespace[ch])
12418 break;
12419 j--;
12420 }
12421 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012422 }
12423 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012424 else {
12425 int kind = PyUnicode_KIND(self);
12426 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012427
Victor Stinnercc7af722013-04-09 22:39:24 +020012428 i = 0;
12429 if (striptype != RIGHTSTRIP) {
12430 while (i < len) {
12431 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12432 if (!Py_UNICODE_ISSPACE(ch))
12433 break;
12434 i++;
12435 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012436 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012437
12438 j = len;
12439 if (striptype != LEFTSTRIP) {
12440 j--;
12441 while (j >= i) {
12442 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12443 if (!Py_UNICODE_ISSPACE(ch))
12444 break;
12445 j--;
12446 }
12447 j++;
12448 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012449 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012450
Victor Stinner7931d9a2011-11-04 00:22:48 +010012451 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012452}
12453
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012454
12455static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012456do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012457{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012458 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012459
Serhiy Storchakac6792272013-10-19 21:03:34 +030012460 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012461 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012462
Benjamin Peterson14339b62009-01-31 16:36:08 +000012463 if (sep != NULL && sep != Py_None) {
12464 if (PyUnicode_Check(sep))
12465 return _PyUnicode_XStrip(self, striptype, sep);
12466 else {
12467 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012468 "%s arg must be None or str",
12469 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012470 return NULL;
12471 }
12472 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012473
Benjamin Peterson14339b62009-01-31 16:36:08 +000012474 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012475}
12476
12477
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012478PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012479 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012480\n\
12481Return a copy of the string S with leading and trailing\n\
12482whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012483If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012484
12485static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012486unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012487{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012488 if (PyTuple_GET_SIZE(args) == 0)
12489 return do_strip(self, BOTHSTRIP); /* Common case */
12490 else
12491 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012492}
12493
12494
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012495PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012496 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012497\n\
12498Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012499If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012500
12501static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012502unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012503{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012504 if (PyTuple_GET_SIZE(args) == 0)
12505 return do_strip(self, LEFTSTRIP); /* Common case */
12506 else
12507 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012508}
12509
12510
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012511PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012512 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012513\n\
12514Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012515If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012516
12517static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012518unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012519{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012520 if (PyTuple_GET_SIZE(args) == 0)
12521 return do_strip(self, RIGHTSTRIP); /* Common case */
12522 else
12523 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012524}
12525
12526
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012528unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012530 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012531 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012532
Serhiy Storchaka05997252013-01-26 12:14:02 +020012533 if (len < 1)
12534 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535
Victor Stinnerc4b49542011-12-11 22:44:26 +010012536 /* no repeat, return original string */
12537 if (len == 1)
12538 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012539
Benjamin Petersonbac79492012-01-14 13:34:47 -050012540 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 return NULL;
12542
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012543 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012544 PyErr_SetString(PyExc_OverflowError,
12545 "repeated string is too long");
12546 return NULL;
12547 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012548 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012549
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012550 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012551 if (!u)
12552 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012553 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 if (PyUnicode_GET_LENGTH(str) == 1) {
12556 const int kind = PyUnicode_KIND(str);
12557 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012558 if (kind == PyUnicode_1BYTE_KIND) {
12559 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012560 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012561 }
12562 else if (kind == PyUnicode_2BYTE_KIND) {
12563 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012564 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012565 ucs2[n] = fill_char;
12566 } else {
12567 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12568 assert(kind == PyUnicode_4BYTE_KIND);
12569 for (n = 0; n < len; ++n)
12570 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 }
12573 else {
12574 /* number of characters copied this far */
12575 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012576 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012577 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012578 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012579 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012580 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012582 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012583 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012584 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012585 }
12586
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012587 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012588 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589}
12590
Alexander Belopolsky40018472011-02-26 01:02:56 +000012591PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012592PyUnicode_Replace(PyObject *str,
12593 PyObject *substr,
12594 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012595 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012597 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12598 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012599 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012600 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012601}
12602
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012603PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012604 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012605\n\
12606Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012607old replaced by new. If the optional argument count is\n\
12608given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609
12610static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012611unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613 PyObject *str1;
12614 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012615 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012616
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012617 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012618 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012619 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012620 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012621 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622}
12623
Alexander Belopolsky40018472011-02-26 01:02:56 +000012624static PyObject *
12625unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012627 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012628 Py_ssize_t isize;
12629 Py_ssize_t osize, squote, dquote, i, o;
12630 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012631 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012632 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012635 return NULL;
12636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012637 isize = PyUnicode_GET_LENGTH(unicode);
12638 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012640 /* Compute length of output, quote characters, and
12641 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012642 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012643 max = 127;
12644 squote = dquote = 0;
12645 ikind = PyUnicode_KIND(unicode);
12646 for (i = 0; i < isize; i++) {
12647 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012648 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012649 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012650 case '\'': squote++; break;
12651 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012652 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012653 incr = 2;
12654 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012655 default:
12656 /* Fast-path ASCII */
12657 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012658 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012659 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012660 ;
12661 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012662 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012663 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012664 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012665 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012666 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012667 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012668 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012669 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012670 if (osize > PY_SSIZE_T_MAX - incr) {
12671 PyErr_SetString(PyExc_OverflowError,
12672 "string is too long to generate repr");
12673 return NULL;
12674 }
12675 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012676 }
12677
12678 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012679 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012680 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012681 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012682 if (dquote)
12683 /* Both squote and dquote present. Use squote,
12684 and escape them */
12685 osize += squote;
12686 else
12687 quote = '"';
12688 }
Victor Stinner55c08782013-04-14 18:45:39 +020012689 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012690
12691 repr = PyUnicode_New(osize, max);
12692 if (repr == NULL)
12693 return NULL;
12694 okind = PyUnicode_KIND(repr);
12695 odata = PyUnicode_DATA(repr);
12696
12697 PyUnicode_WRITE(okind, odata, 0, quote);
12698 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012699 if (unchanged) {
12700 _PyUnicode_FastCopyCharacters(repr, 1,
12701 unicode, 0,
12702 isize);
12703 }
12704 else {
12705 for (i = 0, o = 1; i < isize; i++) {
12706 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012707
Victor Stinner55c08782013-04-14 18:45:39 +020012708 /* Escape quotes and backslashes */
12709 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012710 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012712 continue;
12713 }
12714
12715 /* Map special whitespace to '\t', \n', '\r' */
12716 if (ch == '\t') {
12717 PyUnicode_WRITE(okind, odata, o++, '\\');
12718 PyUnicode_WRITE(okind, odata, o++, 't');
12719 }
12720 else if (ch == '\n') {
12721 PyUnicode_WRITE(okind, odata, o++, '\\');
12722 PyUnicode_WRITE(okind, odata, o++, 'n');
12723 }
12724 else if (ch == '\r') {
12725 PyUnicode_WRITE(okind, odata, o++, '\\');
12726 PyUnicode_WRITE(okind, odata, o++, 'r');
12727 }
12728
12729 /* Map non-printable US ASCII to '\xhh' */
12730 else if (ch < ' ' || ch == 0x7F) {
12731 PyUnicode_WRITE(okind, odata, o++, '\\');
12732 PyUnicode_WRITE(okind, odata, o++, 'x');
12733 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12734 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12735 }
12736
12737 /* Copy ASCII characters as-is */
12738 else if (ch < 0x7F) {
12739 PyUnicode_WRITE(okind, odata, o++, ch);
12740 }
12741
12742 /* Non-ASCII characters */
12743 else {
12744 /* Map Unicode whitespace and control characters
12745 (categories Z* and C* except ASCII space)
12746 */
12747 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12748 PyUnicode_WRITE(okind, odata, o++, '\\');
12749 /* Map 8-bit characters to '\xhh' */
12750 if (ch <= 0xff) {
12751 PyUnicode_WRITE(okind, odata, o++, 'x');
12752 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12753 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12754 }
12755 /* Map 16-bit characters to '\uxxxx' */
12756 else if (ch <= 0xffff) {
12757 PyUnicode_WRITE(okind, odata, o++, 'u');
12758 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12759 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12760 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12761 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12762 }
12763 /* Map 21-bit characters to '\U00xxxxxx' */
12764 else {
12765 PyUnicode_WRITE(okind, odata, o++, 'U');
12766 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12767 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12768 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12769 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12770 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12771 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12772 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12773 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12774 }
12775 }
12776 /* Copy characters as-is */
12777 else {
12778 PyUnicode_WRITE(okind, odata, o++, ch);
12779 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012780 }
12781 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012782 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012783 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012784 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012785 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786}
12787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012788PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012789 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790\n\
12791Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012792such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793arguments start and end are interpreted as in slice notation.\n\
12794\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012795Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796
12797static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012798unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012800 /* initialize variables to prevent gcc warning */
12801 PyObject *substring = NULL;
12802 Py_ssize_t start = 0;
12803 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012804 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012805
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012806 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012808
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012809 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012810 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012811
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012812 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012813
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012814 if (result == -2)
12815 return NULL;
12816
Christian Heimes217cfd12007-12-02 14:31:20 +000012817 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818}
12819
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012820PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012821 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012822\n\
Mariatta577fc042017-04-09 15:17:06 -070012823Return the highest index in S where substring sub is found,\n\
12824such that sub is contained within S[start:end]. Optional\n\
12825arguments start and end are interpreted as in slice notation.\n\
12826\n\
12827Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828
12829static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012830unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012831{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012832 /* initialize variables to prevent gcc warning */
12833 PyObject *substring = NULL;
12834 Py_ssize_t start = 0;
12835 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012836 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012837
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012838 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012839 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012840
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012841 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012842 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012843
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012844 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012846 if (result == -2)
12847 return NULL;
12848
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849 if (result < 0) {
12850 PyErr_SetString(PyExc_ValueError, "substring not found");
12851 return NULL;
12852 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012853
Christian Heimes217cfd12007-12-02 14:31:20 +000012854 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012855}
12856
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012857PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012858 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012859\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012860Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012861done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012862
12863static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012864unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012865{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012866 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012867 Py_UCS4 fillchar = ' ';
12868
Victor Stinnere9a29352011-10-01 02:14:59 +020012869 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012870 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012871
Benjamin Petersonbac79492012-01-14 13:34:47 -050012872 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012873 return NULL;
12874
Victor Stinnerc4b49542011-12-11 22:44:26 +010012875 if (PyUnicode_GET_LENGTH(self) >= width)
12876 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877
Victor Stinnerc4b49542011-12-11 22:44:26 +010012878 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012879}
12880
Alexander Belopolsky40018472011-02-26 01:02:56 +000012881PyObject *
12882PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012883{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012884 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012885 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012887 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012888}
12889
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012890PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012891 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892\n\
12893Return a list of the words in S, using sep as the\n\
12894delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012895splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012896whitespace string is a separator and empty strings are\n\
12897removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012898
12899static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012900unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012901{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012902 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012903 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012904 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012905
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012906 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12907 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012908 return NULL;
12909
12910 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012911 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012912
12913 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012914 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012915
12916 PyErr_Format(PyExc_TypeError,
12917 "must be str or None, not %.100s",
12918 Py_TYPE(substring)->tp_name);
12919 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920}
12921
Thomas Wouters477c8d52006-05-27 19:21:47 +000012922PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012923PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012924{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012925 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012926 int kind1, kind2;
12927 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012928 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012929
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012930 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012931 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012932
Victor Stinner14f8f022011-10-05 20:58:25 +020012933 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012934 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012935 len1 = PyUnicode_GET_LENGTH(str_obj);
12936 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012937 if (kind1 < kind2 || len1 < len2) {
12938 _Py_INCREF_UNICODE_EMPTY();
12939 if (!unicode_empty)
12940 out = NULL;
12941 else {
12942 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12943 Py_DECREF(unicode_empty);
12944 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012945 return out;
12946 }
12947 buf1 = PyUnicode_DATA(str_obj);
12948 buf2 = PyUnicode_DATA(sep_obj);
12949 if (kind2 != kind1) {
12950 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12951 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012952 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012954
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012955 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012956 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012957 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12958 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12959 else
12960 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012961 break;
12962 case PyUnicode_2BYTE_KIND:
12963 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12964 break;
12965 case PyUnicode_4BYTE_KIND:
12966 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12967 break;
12968 default:
12969 assert(0);
12970 out = 0;
12971 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012972
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012973 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012974 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012975
12976 return out;
12977}
12978
12979
12980PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012981PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012982{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012983 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012984 int kind1, kind2;
12985 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012986 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012987
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012988 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012989 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012990
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012991 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012992 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012993 len1 = PyUnicode_GET_LENGTH(str_obj);
12994 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012995 if (kind1 < kind2 || len1 < len2) {
12996 _Py_INCREF_UNICODE_EMPTY();
12997 if (!unicode_empty)
12998 out = NULL;
12999 else {
13000 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
13001 Py_DECREF(unicode_empty);
13002 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013003 return out;
13004 }
13005 buf1 = PyUnicode_DATA(str_obj);
13006 buf2 = PyUnicode_DATA(sep_obj);
13007 if (kind2 != kind1) {
13008 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13009 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013010 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013011 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013012
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013013 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013014 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013015 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13016 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13017 else
13018 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013019 break;
13020 case PyUnicode_2BYTE_KIND:
13021 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13022 break;
13023 case PyUnicode_4BYTE_KIND:
13024 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13025 break;
13026 default:
13027 assert(0);
13028 out = 0;
13029 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013030
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013031 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013032 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013033
13034 return out;
13035}
13036
13037PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013038 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013039\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013040Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013041the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013042found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013043
13044static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013045unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013046{
Victor Stinner9310abb2011-10-05 00:59:23 +020013047 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013048}
13049
13050PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000013051 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013052\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013053Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013054the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013055separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013056
13057static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013058unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013059{
Victor Stinner9310abb2011-10-05 00:59:23 +020013060 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013061}
13062
Alexander Belopolsky40018472011-02-26 01:02:56 +000013063PyObject *
13064PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013065{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013066 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013067 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013068
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013069 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013070}
13071
13072PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013073 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013074\n\
13075Return a list of the words in S, using sep as the\n\
13076delimiter string, starting at the end of the string and\n\
13077working to the front. If maxsplit is given, at most maxsplit\n\
13078splits are done. If sep is not specified, any whitespace string\n\
13079is a separator.");
13080
13081static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013082unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013083{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013084 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013085 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013086 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013087
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013088 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
13089 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013090 return NULL;
13091
13092 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000013093 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013094
13095 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020013096 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013097
13098 PyErr_Format(PyExc_TypeError,
13099 "must be str or None, not %.100s",
13100 Py_TYPE(substring)->tp_name);
13101 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013102}
13103
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013104PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013105 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106\n\
13107Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000013108Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013109is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110
13111static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013112unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013114 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000013115 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013117 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
13118 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119 return NULL;
13120
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013121 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122}
13123
13124static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013125PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013126{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013127 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013128}
13129
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013130PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013131 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132\n\
13133Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013134and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013135
13136static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013137unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013138{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013139 if (PyUnicode_READY(self) == -1)
13140 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013141 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013142}
13143
Larry Hastings61272b72014-01-07 12:41:53 -080013144/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013145
Larry Hastings31826802013-10-19 00:09:25 -070013146@staticmethod
13147str.maketrans as unicode_maketrans
13148
13149 x: object
13150
13151 y: unicode=NULL
13152
13153 z: unicode=NULL
13154
13155 /
13156
13157Return a translation table usable for str.translate().
13158
13159If there is only one argument, it must be a dictionary mapping Unicode
13160ordinals (integers) or characters to Unicode ordinals, strings or None.
13161Character keys will be then converted to ordinals.
13162If there are two arguments, they must be strings of equal length, and
13163in the resulting dictionary, each character in x will be mapped to the
13164character at the same position in y. If there is a third argument, it
13165must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013166[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013167
Larry Hastings31826802013-10-19 00:09:25 -070013168static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013169unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013170/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013171{
Georg Brandlceee0772007-11-27 23:48:05 +000013172 PyObject *new = NULL, *key, *value;
13173 Py_ssize_t i = 0;
13174 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013175
Georg Brandlceee0772007-11-27 23:48:05 +000013176 new = PyDict_New();
13177 if (!new)
13178 return NULL;
13179 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013180 int x_kind, y_kind, z_kind;
13181 void *x_data, *y_data, *z_data;
13182
Georg Brandlceee0772007-11-27 23:48:05 +000013183 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013184 if (!PyUnicode_Check(x)) {
13185 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13186 "be a string if there is a second argument");
13187 goto err;
13188 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013189 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013190 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13191 "arguments must have equal length");
13192 goto err;
13193 }
13194 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013195 x_kind = PyUnicode_KIND(x);
13196 y_kind = PyUnicode_KIND(y);
13197 x_data = PyUnicode_DATA(x);
13198 y_data = PyUnicode_DATA(y);
13199 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13200 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013201 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013202 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013203 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013204 if (!value) {
13205 Py_DECREF(key);
13206 goto err;
13207 }
Georg Brandlceee0772007-11-27 23:48:05 +000013208 res = PyDict_SetItem(new, key, value);
13209 Py_DECREF(key);
13210 Py_DECREF(value);
13211 if (res < 0)
13212 goto err;
13213 }
13214 /* create entries for deleting chars in z */
13215 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013216 z_kind = PyUnicode_KIND(z);
13217 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013218 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013219 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013220 if (!key)
13221 goto err;
13222 res = PyDict_SetItem(new, key, Py_None);
13223 Py_DECREF(key);
13224 if (res < 0)
13225 goto err;
13226 }
13227 }
13228 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013229 int kind;
13230 void *data;
13231
Georg Brandlceee0772007-11-27 23:48:05 +000013232 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013233 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013234 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13235 "to maketrans it must be a dict");
13236 goto err;
13237 }
13238 /* copy entries into the new dict, converting string keys to int keys */
13239 while (PyDict_Next(x, &i, &key, &value)) {
13240 if (PyUnicode_Check(key)) {
13241 /* convert string keys to integer keys */
13242 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013243 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013244 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13245 "table must be of length 1");
13246 goto err;
13247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013248 kind = PyUnicode_KIND(key);
13249 data = PyUnicode_DATA(key);
13250 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013251 if (!newkey)
13252 goto err;
13253 res = PyDict_SetItem(new, newkey, value);
13254 Py_DECREF(newkey);
13255 if (res < 0)
13256 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013257 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013258 /* just keep integer keys */
13259 if (PyDict_SetItem(new, key, value) < 0)
13260 goto err;
13261 } else {
13262 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13263 "be strings or integers");
13264 goto err;
13265 }
13266 }
13267 }
13268 return new;
13269 err:
13270 Py_DECREF(new);
13271 return NULL;
13272}
13273
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013274PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013275 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013276\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013277Return a copy of the string S in which each character has been mapped\n\
13278through the given translation table. The table must implement\n\
13279lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13280mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13281this operation raises LookupError, the character is left untouched.\n\
13282Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013283
13284static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013285unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013286{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013287 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013288}
13289
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013290PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013291 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013292\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013293Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013294
13295static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013296unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013297{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013298 if (PyUnicode_READY(self) == -1)
13299 return NULL;
13300 if (PyUnicode_IS_ASCII(self))
13301 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013302 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013303}
13304
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013305PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013306 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013307\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013308Pad a numeric string S with zeros on the left, to fill a field\n\
13309of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013310
13311static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013312unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013313{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013314 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013315 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013316 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013317 int kind;
13318 void *data;
13319 Py_UCS4 chr;
13320
Martin v. Löwis18e16552006-02-15 17:27:45 +000013321 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013322 return NULL;
13323
Benjamin Petersonbac79492012-01-14 13:34:47 -050013324 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013325 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013326
Victor Stinnerc4b49542011-12-11 22:44:26 +010013327 if (PyUnicode_GET_LENGTH(self) >= width)
13328 return unicode_result_unchanged(self);
13329
13330 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013331
13332 u = pad(self, fill, 0, '0');
13333
Walter Dörwald068325e2002-04-15 13:36:47 +000013334 if (u == NULL)
13335 return NULL;
13336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013337 kind = PyUnicode_KIND(u);
13338 data = PyUnicode_DATA(u);
13339 chr = PyUnicode_READ(kind, data, fill);
13340
13341 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013342 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013343 PyUnicode_WRITE(kind, data, 0, chr);
13344 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345 }
13346
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013347 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013348 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013349}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013350
13351#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013352static PyObject *
13353unicode__decimal2ascii(PyObject *self)
13354{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013355 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013356}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013357#endif
13358
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013359PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013360 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013361\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013362Return True if S starts with the specified prefix, False otherwise.\n\
13363With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013364With optional end, stop comparing S at that position.\n\
13365prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013366
13367static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013368unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013369 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013370{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013371 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013372 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013373 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013374 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013375 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013376
Jesus Ceaac451502011-04-20 17:09:23 +020013377 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013378 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013379 if (PyTuple_Check(subobj)) {
13380 Py_ssize_t i;
13381 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013382 substring = PyTuple_GET_ITEM(subobj, i);
13383 if (!PyUnicode_Check(substring)) {
13384 PyErr_Format(PyExc_TypeError,
13385 "tuple for startswith must only contain str, "
13386 "not %.100s",
13387 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013388 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013389 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013390 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013391 if (result == -1)
13392 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013393 if (result) {
13394 Py_RETURN_TRUE;
13395 }
13396 }
13397 /* nothing matched */
13398 Py_RETURN_FALSE;
13399 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013400 if (!PyUnicode_Check(subobj)) {
13401 PyErr_Format(PyExc_TypeError,
13402 "startswith first arg must be str or "
13403 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013404 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013405 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013406 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013407 if (result == -1)
13408 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013409 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013410}
13411
13412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013413PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013414 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013415\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013416Return True if S ends with the specified suffix, False otherwise.\n\
13417With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013418With optional end, stop comparing S at that position.\n\
13419suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013420
13421static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013422unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013423 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013424{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013425 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013426 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013427 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013428 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013429 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013430
Jesus Ceaac451502011-04-20 17:09:23 +020013431 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013432 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013433 if (PyTuple_Check(subobj)) {
13434 Py_ssize_t i;
13435 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013436 substring = PyTuple_GET_ITEM(subobj, i);
13437 if (!PyUnicode_Check(substring)) {
13438 PyErr_Format(PyExc_TypeError,
13439 "tuple for endswith must only contain str, "
13440 "not %.100s",
13441 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013442 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013443 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013444 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013445 if (result == -1)
13446 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013447 if (result) {
13448 Py_RETURN_TRUE;
13449 }
13450 }
13451 Py_RETURN_FALSE;
13452 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013453 if (!PyUnicode_Check(subobj)) {
13454 PyErr_Format(PyExc_TypeError,
13455 "endswith first arg must be str or "
13456 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013457 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013458 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013459 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013460 if (result == -1)
13461 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013462 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013463}
13464
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013465static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013466_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013467{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013468 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13469 writer->data = PyUnicode_DATA(writer->buffer);
13470
13471 if (!writer->readonly) {
13472 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013473 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013474 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013475 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013476 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13477 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13478 writer->kind = PyUnicode_WCHAR_KIND;
13479 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13480
Victor Stinner8f674cc2013-04-17 23:02:17 +020013481 /* Copy-on-write mode: set buffer size to 0 so
13482 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13483 * next write. */
13484 writer->size = 0;
13485 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013486}
13487
Victor Stinnerd3f08822012-05-29 12:57:52 +020013488void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013489_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013490{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013491 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013492
13493 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013494 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013495
13496 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13497 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13498 writer->kind = PyUnicode_WCHAR_KIND;
13499 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013500}
13501
Victor Stinnerd3f08822012-05-29 12:57:52 +020013502int
13503_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13504 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013505{
13506 Py_ssize_t newlen;
13507 PyObject *newbuffer;
13508
Victor Stinner2740e462016-09-06 16:58:36 -070013509 assert(maxchar <= MAX_UNICODE);
13510
Victor Stinnerca9381e2015-09-22 00:58:32 +020013511 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013512 assert((maxchar > writer->maxchar && length >= 0)
13513 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013514
Victor Stinner202fdca2012-05-07 12:47:02 +020013515 if (length > PY_SSIZE_T_MAX - writer->pos) {
13516 PyErr_NoMemory();
13517 return -1;
13518 }
13519 newlen = writer->pos + length;
13520
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013521 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013522
Victor Stinnerd3f08822012-05-29 12:57:52 +020013523 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013524 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013525 if (writer->overallocate
13526 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13527 /* overallocate to limit the number of realloc() */
13528 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013529 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013530 if (newlen < writer->min_length)
13531 newlen = writer->min_length;
13532
Victor Stinnerd3f08822012-05-29 12:57:52 +020013533 writer->buffer = PyUnicode_New(newlen, maxchar);
13534 if (writer->buffer == NULL)
13535 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013536 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013537 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013538 if (writer->overallocate
13539 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13540 /* overallocate to limit the number of realloc() */
13541 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013542 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013543 if (newlen < writer->min_length)
13544 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013545
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013546 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013547 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013548 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013549 newbuffer = PyUnicode_New(newlen, maxchar);
13550 if (newbuffer == NULL)
13551 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013552 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13553 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013554 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013555 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013556 }
13557 else {
13558 newbuffer = resize_compact(writer->buffer, newlen);
13559 if (newbuffer == NULL)
13560 return -1;
13561 }
13562 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013563 }
13564 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013565 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013566 newbuffer = PyUnicode_New(writer->size, maxchar);
13567 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013568 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013569 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13570 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013571 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013572 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013573 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013574 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013575
13576#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013577}
13578
Victor Stinnerca9381e2015-09-22 00:58:32 +020013579int
13580_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13581 enum PyUnicode_Kind kind)
13582{
13583 Py_UCS4 maxchar;
13584
13585 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13586 assert(writer->kind < kind);
13587
13588 switch (kind)
13589 {
13590 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13591 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13592 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13593 default:
13594 assert(0 && "invalid kind");
13595 return -1;
13596 }
13597
13598 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13599}
13600
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013601static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013602_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013603{
Victor Stinner2740e462016-09-06 16:58:36 -070013604 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013605 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13606 return -1;
13607 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13608 writer->pos++;
13609 return 0;
13610}
13611
13612int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013613_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13614{
13615 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13616}
13617
13618int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013619_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13620{
13621 Py_UCS4 maxchar;
13622 Py_ssize_t len;
13623
13624 if (PyUnicode_READY(str) == -1)
13625 return -1;
13626 len = PyUnicode_GET_LENGTH(str);
13627 if (len == 0)
13628 return 0;
13629 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13630 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013631 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013632 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013633 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013634 Py_INCREF(str);
13635 writer->buffer = str;
13636 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013637 writer->pos += len;
13638 return 0;
13639 }
13640 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13641 return -1;
13642 }
13643 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13644 str, 0, len);
13645 writer->pos += len;
13646 return 0;
13647}
13648
Victor Stinnere215d962012-10-06 23:03:36 +020013649int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013650_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13651 Py_ssize_t start, Py_ssize_t end)
13652{
13653 Py_UCS4 maxchar;
13654 Py_ssize_t len;
13655
13656 if (PyUnicode_READY(str) == -1)
13657 return -1;
13658
13659 assert(0 <= start);
13660 assert(end <= PyUnicode_GET_LENGTH(str));
13661 assert(start <= end);
13662
13663 if (end == 0)
13664 return 0;
13665
13666 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13667 return _PyUnicodeWriter_WriteStr(writer, str);
13668
13669 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13670 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13671 else
13672 maxchar = writer->maxchar;
13673 len = end - start;
13674
13675 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13676 return -1;
13677
13678 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13679 str, start, len);
13680 writer->pos += len;
13681 return 0;
13682}
13683
13684int
Victor Stinner4a587072013-11-19 12:54:53 +010013685_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13686 const char *ascii, Py_ssize_t len)
13687{
13688 if (len == -1)
13689 len = strlen(ascii);
13690
13691 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13692
13693 if (writer->buffer == NULL && !writer->overallocate) {
13694 PyObject *str;
13695
13696 str = _PyUnicode_FromASCII(ascii, len);
13697 if (str == NULL)
13698 return -1;
13699
13700 writer->readonly = 1;
13701 writer->buffer = str;
13702 _PyUnicodeWriter_Update(writer);
13703 writer->pos += len;
13704 return 0;
13705 }
13706
13707 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13708 return -1;
13709
13710 switch (writer->kind)
13711 {
13712 case PyUnicode_1BYTE_KIND:
13713 {
13714 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13715 Py_UCS1 *data = writer->data;
13716
Christian Heimesf051e432016-09-13 20:22:02 +020013717 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013718 break;
13719 }
13720 case PyUnicode_2BYTE_KIND:
13721 {
13722 _PyUnicode_CONVERT_BYTES(
13723 Py_UCS1, Py_UCS2,
13724 ascii, ascii + len,
13725 (Py_UCS2 *)writer->data + writer->pos);
13726 break;
13727 }
13728 case PyUnicode_4BYTE_KIND:
13729 {
13730 _PyUnicode_CONVERT_BYTES(
13731 Py_UCS1, Py_UCS4,
13732 ascii, ascii + len,
13733 (Py_UCS4 *)writer->data + writer->pos);
13734 break;
13735 }
13736 default:
13737 assert(0);
13738 }
13739
13740 writer->pos += len;
13741 return 0;
13742}
13743
13744int
13745_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13746 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013747{
13748 Py_UCS4 maxchar;
13749
13750 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13751 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13752 return -1;
13753 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13754 writer->pos += len;
13755 return 0;
13756}
13757
Victor Stinnerd3f08822012-05-29 12:57:52 +020013758PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013759_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013760{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013761 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013762
Victor Stinnerd3f08822012-05-29 12:57:52 +020013763 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013764 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013765 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013766 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013767
13768 str = writer->buffer;
13769 writer->buffer = NULL;
13770
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013771 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013772 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13773 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013774 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013775
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013776 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13777 PyObject *str2;
13778 str2 = resize_compact(str, writer->pos);
13779 if (str2 == NULL) {
13780 Py_DECREF(str);
13781 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013782 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013783 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013784 }
13785
Victor Stinner15a0bd32013-07-08 22:29:55 +020013786 assert(_PyUnicode_CheckConsistency(str, 1));
13787 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013788}
13789
Victor Stinnerd3f08822012-05-29 12:57:52 +020013790void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013791_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013792{
13793 Py_CLEAR(writer->buffer);
13794}
13795
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013796#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013797
13798PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013799 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013800\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013801Return a formatted version of S, using substitutions from args and kwargs.\n\
13802The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013803
Eric Smith27bbca62010-11-04 17:06:58 +000013804PyDoc_STRVAR(format_map__doc__,
13805 "S.format_map(mapping) -> str\n\
13806\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013807Return a formatted version of S, using substitutions from mapping.\n\
13808The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013809
Eric Smith4a7d76d2008-05-30 18:10:19 +000013810static PyObject *
13811unicode__format__(PyObject* self, PyObject* args)
13812{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013813 PyObject *format_spec;
13814 _PyUnicodeWriter writer;
13815 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013816
13817 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13818 return NULL;
13819
Victor Stinnerd3f08822012-05-29 12:57:52 +020013820 if (PyUnicode_READY(self) == -1)
13821 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013822 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013823 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13824 self, format_spec, 0,
13825 PyUnicode_GET_LENGTH(format_spec));
13826 if (ret == -1) {
13827 _PyUnicodeWriter_Dealloc(&writer);
13828 return NULL;
13829 }
13830 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013831}
13832
Eric Smith8c663262007-08-25 02:26:07 +000013833PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013834 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013835\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013836Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013837
13838static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013839unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013840{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013841 Py_ssize_t size;
13842
13843 /* If it's a compact object, account for base structure +
13844 character data. */
13845 if (PyUnicode_IS_COMPACT_ASCII(v))
13846 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13847 else if (PyUnicode_IS_COMPACT(v))
13848 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013849 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013850 else {
13851 /* If it is a two-block object, account for base object, and
13852 for character block if present. */
13853 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013854 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013855 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013856 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013857 }
13858 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013859 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013860 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013861 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013862 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013863 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013864
13865 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013866}
13867
13868PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013869 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013870
13871static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013872unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013873{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013874 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013875 if (!copy)
13876 return NULL;
13877 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013878}
13879
Guido van Rossumd57fd912000-03-10 22:53:23 +000013880static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013881 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013882 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013883 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13884 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013885 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13886 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013887 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013888 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13889 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13890 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013891 {"expandtabs", (PyCFunction) unicode_expandtabs,
13892 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013893 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013894 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013895 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13896 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13897 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013898 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013899 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13900 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13901 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013902 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013903 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013904 {"splitlines", (PyCFunction) unicode_splitlines,
13905 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013906 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013907 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13908 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13909 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13910 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13911 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13912 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13913 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13914 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13915 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13916 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13917 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13918 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13919 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13920 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013921 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013922 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013923 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013924 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013925 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013926 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013927 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013928 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013929#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013930 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013931 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013932#endif
13933
Benjamin Peterson14339b62009-01-31 16:36:08 +000013934 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013935 {NULL, NULL}
13936};
13937
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013938static PyObject *
13939unicode_mod(PyObject *v, PyObject *w)
13940{
Brian Curtindfc80e32011-08-10 20:28:54 -050013941 if (!PyUnicode_Check(v))
13942 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013943 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013944}
13945
13946static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013947 0, /*nb_add*/
13948 0, /*nb_subtract*/
13949 0, /*nb_multiply*/
13950 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013951};
13952
Guido van Rossumd57fd912000-03-10 22:53:23 +000013953static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013954 (lenfunc) unicode_length, /* sq_length */
13955 PyUnicode_Concat, /* sq_concat */
13956 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13957 (ssizeargfunc) unicode_getitem, /* sq_item */
13958 0, /* sq_slice */
13959 0, /* sq_ass_item */
13960 0, /* sq_ass_slice */
13961 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013962};
13963
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013964static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013965unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013966{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013967 if (PyUnicode_READY(self) == -1)
13968 return NULL;
13969
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013970 if (PyIndex_Check(item)) {
13971 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013972 if (i == -1 && PyErr_Occurred())
13973 return NULL;
13974 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013975 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013976 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013977 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013978 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013979 PyObject *result;
13980 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013981 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013982 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013983
Serhiy Storchakac26b19d2017-04-08 11:18:14 +030013984 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013985 return NULL;
13986 }
Serhiy Storchakac26b19d2017-04-08 11:18:14 +030013987 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13988 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013989
13990 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013991 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013992 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013993 slicelength == PyUnicode_GET_LENGTH(self)) {
13994 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013995 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013996 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013997 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013998 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013999 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014000 src_kind = PyUnicode_KIND(self);
14001 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020014002 if (!PyUnicode_IS_ASCII(self)) {
14003 kind_limit = kind_maxchar_limit(src_kind);
14004 max_char = 0;
14005 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14006 ch = PyUnicode_READ(src_kind, src_data, cur);
14007 if (ch > max_char) {
14008 max_char = ch;
14009 if (max_char >= kind_limit)
14010 break;
14011 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014012 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014013 }
Victor Stinner55c99112011-10-13 01:17:06 +020014014 else
14015 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014016 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014017 if (result == NULL)
14018 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014019 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014020 dest_data = PyUnicode_DATA(result);
14021
14022 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014023 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14024 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014025 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014026 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014027 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014028 } else {
14029 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14030 return NULL;
14031 }
14032}
14033
14034static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014035 (lenfunc)unicode_length, /* mp_length */
14036 (binaryfunc)unicode_subscript, /* mp_subscript */
14037 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014038};
14039
Guido van Rossumd57fd912000-03-10 22:53:23 +000014040
Guido van Rossumd57fd912000-03-10 22:53:23 +000014041/* Helpers for PyUnicode_Format() */
14042
Victor Stinnera47082312012-10-04 02:19:54 +020014043struct unicode_formatter_t {
14044 PyObject *args;
14045 int args_owned;
14046 Py_ssize_t arglen, argidx;
14047 PyObject *dict;
14048
14049 enum PyUnicode_Kind fmtkind;
14050 Py_ssize_t fmtcnt, fmtpos;
14051 void *fmtdata;
14052 PyObject *fmtstr;
14053
14054 _PyUnicodeWriter writer;
14055};
14056
14057struct unicode_format_arg_t {
14058 Py_UCS4 ch;
14059 int flags;
14060 Py_ssize_t width;
14061 int prec;
14062 int sign;
14063};
14064
Guido van Rossumd57fd912000-03-10 22:53:23 +000014065static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014066unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014067{
Victor Stinnera47082312012-10-04 02:19:54 +020014068 Py_ssize_t argidx = ctx->argidx;
14069
14070 if (argidx < ctx->arglen) {
14071 ctx->argidx++;
14072 if (ctx->arglen < 0)
14073 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014074 else
Victor Stinnera47082312012-10-04 02:19:54 +020014075 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014076 }
14077 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014078 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014079 return NULL;
14080}
14081
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014082/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014083
Victor Stinnera47082312012-10-04 02:19:54 +020014084/* Format a float into the writer if the writer is not NULL, or into *p_output
14085 otherwise.
14086
14087 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014088static int
Victor Stinnera47082312012-10-04 02:19:54 +020014089formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14090 PyObject **p_output,
14091 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014092{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014093 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014094 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014095 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014096 int prec;
14097 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014098
Guido van Rossumd57fd912000-03-10 22:53:23 +000014099 x = PyFloat_AsDouble(v);
14100 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014101 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014102
Victor Stinnera47082312012-10-04 02:19:54 +020014103 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014104 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014105 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014106
Victor Stinnera47082312012-10-04 02:19:54 +020014107 if (arg->flags & F_ALT)
14108 dtoa_flags = Py_DTSF_ALT;
14109 else
14110 dtoa_flags = 0;
14111 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014112 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014113 return -1;
14114 len = strlen(p);
14115 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014116 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014117 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014118 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014119 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014120 }
14121 else
14122 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014123 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014124 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014125}
14126
Victor Stinnerd0880d52012-04-27 23:40:13 +020014127/* formatlong() emulates the format codes d, u, o, x and X, and
14128 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14129 * Python's regular ints.
14130 * Return value: a new PyUnicodeObject*, or NULL if error.
14131 * The output string is of the form
14132 * "-"? ("0x" | "0X")? digit+
14133 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14134 * set in flags. The case of hex digits will be correct,
14135 * There will be at least prec digits, zero-filled on the left if
14136 * necessary to get that many.
14137 * val object to be converted
14138 * flags bitmask of format flags; only F_ALT is looked at
14139 * prec minimum number of digits; 0-fill on left if needed
14140 * type a character in [duoxX]; u acts the same as d
14141 *
14142 * CAUTION: o, x and X conversions on regular ints can never
14143 * produce a '-' sign, but can for Python's unbounded ints.
14144 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014145PyObject *
14146_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014147{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014148 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014149 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014150 Py_ssize_t i;
14151 int sign; /* 1 if '-', else 0 */
14152 int len; /* number of characters */
14153 Py_ssize_t llen;
14154 int numdigits; /* len == numnondigits + numdigits */
14155 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014156
Victor Stinnerd0880d52012-04-27 23:40:13 +020014157 /* Avoid exceeding SSIZE_T_MAX */
14158 if (prec > INT_MAX-3) {
14159 PyErr_SetString(PyExc_OverflowError,
14160 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014161 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014162 }
14163
14164 assert(PyLong_Check(val));
14165
14166 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014167 default:
14168 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014169 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014170 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014171 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014172 /* int and int subclasses should print numerically when a numeric */
14173 /* format code is used (see issue18780) */
14174 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014175 break;
14176 case 'o':
14177 numnondigits = 2;
14178 result = PyNumber_ToBase(val, 8);
14179 break;
14180 case 'x':
14181 case 'X':
14182 numnondigits = 2;
14183 result = PyNumber_ToBase(val, 16);
14184 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014185 }
14186 if (!result)
14187 return NULL;
14188
14189 assert(unicode_modifiable(result));
14190 assert(PyUnicode_IS_READY(result));
14191 assert(PyUnicode_IS_ASCII(result));
14192
14193 /* To modify the string in-place, there can only be one reference. */
14194 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014195 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014196 PyErr_BadInternalCall();
14197 return NULL;
14198 }
14199 buf = PyUnicode_DATA(result);
14200 llen = PyUnicode_GET_LENGTH(result);
14201 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014202 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014203 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014204 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014205 return NULL;
14206 }
14207 len = (int)llen;
14208 sign = buf[0] == '-';
14209 numnondigits += sign;
14210 numdigits = len - numnondigits;
14211 assert(numdigits > 0);
14212
14213 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014214 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014215 (type == 'o' || type == 'x' || type == 'X'))) {
14216 assert(buf[sign] == '0');
14217 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14218 buf[sign+1] == 'o');
14219 numnondigits -= 2;
14220 buf += 2;
14221 len -= 2;
14222 if (sign)
14223 buf[0] = '-';
14224 assert(len == numnondigits + numdigits);
14225 assert(numdigits > 0);
14226 }
14227
14228 /* Fill with leading zeroes to meet minimum width. */
14229 if (prec > numdigits) {
14230 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14231 numnondigits + prec);
14232 char *b1;
14233 if (!r1) {
14234 Py_DECREF(result);
14235 return NULL;
14236 }
14237 b1 = PyBytes_AS_STRING(r1);
14238 for (i = 0; i < numnondigits; ++i)
14239 *b1++ = *buf++;
14240 for (i = 0; i < prec - numdigits; i++)
14241 *b1++ = '0';
14242 for (i = 0; i < numdigits; i++)
14243 *b1++ = *buf++;
14244 *b1 = '\0';
14245 Py_DECREF(result);
14246 result = r1;
14247 buf = PyBytes_AS_STRING(result);
14248 len = numnondigits + prec;
14249 }
14250
14251 /* Fix up case for hex conversions. */
14252 if (type == 'X') {
14253 /* Need to convert all lower case letters to upper case.
14254 and need to convert 0x to 0X (and -0x to -0X). */
14255 for (i = 0; i < len; i++)
14256 if (buf[i] >= 'a' && buf[i] <= 'x')
14257 buf[i] -= 'a'-'A';
14258 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014259 if (!PyUnicode_Check(result)
14260 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014261 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014262 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014263 Py_DECREF(result);
14264 result = unicode;
14265 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014266 else if (len != PyUnicode_GET_LENGTH(result)) {
14267 if (PyUnicode_Resize(&result, len) < 0)
14268 Py_CLEAR(result);
14269 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014270 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014271}
14272
Ethan Furmandf3ed242014-01-05 06:50:30 -080014273/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014274 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014275 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014276 * -1 and raise an exception on error */
14277static int
Victor Stinnera47082312012-10-04 02:19:54 +020014278mainformatlong(PyObject *v,
14279 struct unicode_format_arg_t *arg,
14280 PyObject **p_output,
14281 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014282{
14283 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014284 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014285
14286 if (!PyNumber_Check(v))
14287 goto wrongtype;
14288
Ethan Furman9ab74802014-03-21 06:38:46 -070014289 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014290 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014291 if (type == 'o' || type == 'x' || type == 'X') {
14292 iobj = PyNumber_Index(v);
14293 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014294 if (PyErr_ExceptionMatches(PyExc_TypeError))
14295 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014296 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014297 }
14298 }
14299 else {
14300 iobj = PyNumber_Long(v);
14301 if (iobj == NULL ) {
14302 if (PyErr_ExceptionMatches(PyExc_TypeError))
14303 goto wrongtype;
14304 return -1;
14305 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014306 }
14307 assert(PyLong_Check(iobj));
14308 }
14309 else {
14310 iobj = v;
14311 Py_INCREF(iobj);
14312 }
14313
14314 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014315 && arg->width == -1 && arg->prec == -1
14316 && !(arg->flags & (F_SIGN | F_BLANK))
14317 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014318 {
14319 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014320 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014321 int base;
14322
Victor Stinnera47082312012-10-04 02:19:54 +020014323 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014324 {
14325 default:
14326 assert(0 && "'type' not in [diuoxX]");
14327 case 'd':
14328 case 'i':
14329 case 'u':
14330 base = 10;
14331 break;
14332 case 'o':
14333 base = 8;
14334 break;
14335 case 'x':
14336 case 'X':
14337 base = 16;
14338 break;
14339 }
14340
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014341 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14342 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014343 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014344 }
14345 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014346 return 1;
14347 }
14348
Ethan Furmanb95b5612015-01-23 20:05:18 -080014349 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014350 Py_DECREF(iobj);
14351 if (res == NULL)
14352 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014353 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014354 return 0;
14355
14356wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014357 switch(type)
14358 {
14359 case 'o':
14360 case 'x':
14361 case 'X':
14362 PyErr_Format(PyExc_TypeError,
14363 "%%%c format: an integer is required, "
14364 "not %.200s",
14365 type, Py_TYPE(v)->tp_name);
14366 break;
14367 default:
14368 PyErr_Format(PyExc_TypeError,
14369 "%%%c format: a number is required, "
14370 "not %.200s",
14371 type, Py_TYPE(v)->tp_name);
14372 break;
14373 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014374 return -1;
14375}
14376
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014377static Py_UCS4
14378formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014379{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014380 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014381 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014382 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014383 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014384 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014385 goto onError;
14386 }
14387 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014388 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014389 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014390 /* make sure number is a type of integer */
14391 if (!PyLong_Check(v)) {
14392 iobj = PyNumber_Index(v);
14393 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014394 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014395 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014396 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014397 Py_DECREF(iobj);
14398 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014399 else {
14400 x = PyLong_AsLong(v);
14401 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014402 if (x == -1 && PyErr_Occurred())
14403 goto onError;
14404
Victor Stinner8faf8212011-12-08 22:14:11 +010014405 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014406 PyErr_SetString(PyExc_OverflowError,
14407 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014408 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014409 }
14410
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014411 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014412 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014413
Benjamin Peterson29060642009-01-31 22:14:21 +000014414 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014415 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014416 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014417 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014418}
14419
Victor Stinnera47082312012-10-04 02:19:54 +020014420/* Parse options of an argument: flags, width, precision.
14421 Handle also "%(name)" syntax.
14422
14423 Return 0 if the argument has been formatted into arg->str.
14424 Return 1 if the argument has been written into ctx->writer,
14425 Raise an exception and return -1 on error. */
14426static int
14427unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14428 struct unicode_format_arg_t *arg)
14429{
14430#define FORMAT_READ(ctx) \
14431 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14432
14433 PyObject *v;
14434
Victor Stinnera47082312012-10-04 02:19:54 +020014435 if (arg->ch == '(') {
14436 /* Get argument value from a dictionary. Example: "%(name)s". */
14437 Py_ssize_t keystart;
14438 Py_ssize_t keylen;
14439 PyObject *key;
14440 int pcount = 1;
14441
14442 if (ctx->dict == NULL) {
14443 PyErr_SetString(PyExc_TypeError,
14444 "format requires a mapping");
14445 return -1;
14446 }
14447 ++ctx->fmtpos;
14448 --ctx->fmtcnt;
14449 keystart = ctx->fmtpos;
14450 /* Skip over balanced parentheses */
14451 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14452 arg->ch = FORMAT_READ(ctx);
14453 if (arg->ch == ')')
14454 --pcount;
14455 else if (arg->ch == '(')
14456 ++pcount;
14457 ctx->fmtpos++;
14458 }
14459 keylen = ctx->fmtpos - keystart - 1;
14460 if (ctx->fmtcnt < 0 || pcount > 0) {
14461 PyErr_SetString(PyExc_ValueError,
14462 "incomplete format key");
14463 return -1;
14464 }
14465 key = PyUnicode_Substring(ctx->fmtstr,
14466 keystart, keystart + keylen);
14467 if (key == NULL)
14468 return -1;
14469 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014470 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014471 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014472 }
14473 ctx->args = PyObject_GetItem(ctx->dict, key);
14474 Py_DECREF(key);
14475 if (ctx->args == NULL)
14476 return -1;
14477 ctx->args_owned = 1;
14478 ctx->arglen = -1;
14479 ctx->argidx = -2;
14480 }
14481
14482 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014483 while (--ctx->fmtcnt >= 0) {
14484 arg->ch = FORMAT_READ(ctx);
14485 ctx->fmtpos++;
14486 switch (arg->ch) {
14487 case '-': arg->flags |= F_LJUST; continue;
14488 case '+': arg->flags |= F_SIGN; continue;
14489 case ' ': arg->flags |= F_BLANK; continue;
14490 case '#': arg->flags |= F_ALT; continue;
14491 case '0': arg->flags |= F_ZERO; continue;
14492 }
14493 break;
14494 }
14495
14496 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014497 if (arg->ch == '*') {
14498 v = unicode_format_getnextarg(ctx);
14499 if (v == NULL)
14500 return -1;
14501 if (!PyLong_Check(v)) {
14502 PyErr_SetString(PyExc_TypeError,
14503 "* wants int");
14504 return -1;
14505 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014506 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014507 if (arg->width == -1 && PyErr_Occurred())
14508 return -1;
14509 if (arg->width < 0) {
14510 arg->flags |= F_LJUST;
14511 arg->width = -arg->width;
14512 }
14513 if (--ctx->fmtcnt >= 0) {
14514 arg->ch = FORMAT_READ(ctx);
14515 ctx->fmtpos++;
14516 }
14517 }
14518 else if (arg->ch >= '0' && arg->ch <= '9') {
14519 arg->width = arg->ch - '0';
14520 while (--ctx->fmtcnt >= 0) {
14521 arg->ch = FORMAT_READ(ctx);
14522 ctx->fmtpos++;
14523 if (arg->ch < '0' || arg->ch > '9')
14524 break;
14525 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14526 mixing signed and unsigned comparison. Since arg->ch is between
14527 '0' and '9', casting to int is safe. */
14528 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14529 PyErr_SetString(PyExc_ValueError,
14530 "width too big");
14531 return -1;
14532 }
14533 arg->width = arg->width*10 + (arg->ch - '0');
14534 }
14535 }
14536
14537 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014538 if (arg->ch == '.') {
14539 arg->prec = 0;
14540 if (--ctx->fmtcnt >= 0) {
14541 arg->ch = FORMAT_READ(ctx);
14542 ctx->fmtpos++;
14543 }
14544 if (arg->ch == '*') {
14545 v = unicode_format_getnextarg(ctx);
14546 if (v == NULL)
14547 return -1;
14548 if (!PyLong_Check(v)) {
14549 PyErr_SetString(PyExc_TypeError,
14550 "* wants int");
14551 return -1;
14552 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014553 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014554 if (arg->prec == -1 && PyErr_Occurred())
14555 return -1;
14556 if (arg->prec < 0)
14557 arg->prec = 0;
14558 if (--ctx->fmtcnt >= 0) {
14559 arg->ch = FORMAT_READ(ctx);
14560 ctx->fmtpos++;
14561 }
14562 }
14563 else if (arg->ch >= '0' && arg->ch <= '9') {
14564 arg->prec = arg->ch - '0';
14565 while (--ctx->fmtcnt >= 0) {
14566 arg->ch = FORMAT_READ(ctx);
14567 ctx->fmtpos++;
14568 if (arg->ch < '0' || arg->ch > '9')
14569 break;
14570 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14571 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014572 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014573 return -1;
14574 }
14575 arg->prec = arg->prec*10 + (arg->ch - '0');
14576 }
14577 }
14578 }
14579
14580 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14581 if (ctx->fmtcnt >= 0) {
14582 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14583 if (--ctx->fmtcnt >= 0) {
14584 arg->ch = FORMAT_READ(ctx);
14585 ctx->fmtpos++;
14586 }
14587 }
14588 }
14589 if (ctx->fmtcnt < 0) {
14590 PyErr_SetString(PyExc_ValueError,
14591 "incomplete format");
14592 return -1;
14593 }
14594 return 0;
14595
14596#undef FORMAT_READ
14597}
14598
14599/* Format one argument. Supported conversion specifiers:
14600
14601 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014602 - "i", "d", "u": int or float
14603 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014604 - "e", "E", "f", "F", "g", "G": float
14605 - "c": int or str (1 character)
14606
Victor Stinner8dbd4212012-12-04 09:30:24 +010014607 When possible, the output is written directly into the Unicode writer
14608 (ctx->writer). A string is created when padding is required.
14609
Victor Stinnera47082312012-10-04 02:19:54 +020014610 Return 0 if the argument has been formatted into *p_str,
14611 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014612 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014613static int
14614unicode_format_arg_format(struct unicode_formatter_t *ctx,
14615 struct unicode_format_arg_t *arg,
14616 PyObject **p_str)
14617{
14618 PyObject *v;
14619 _PyUnicodeWriter *writer = &ctx->writer;
14620
14621 if (ctx->fmtcnt == 0)
14622 ctx->writer.overallocate = 0;
14623
14624 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014625 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014626 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014627 return 1;
14628 }
14629
14630 v = unicode_format_getnextarg(ctx);
14631 if (v == NULL)
14632 return -1;
14633
Victor Stinnera47082312012-10-04 02:19:54 +020014634
14635 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014636 case 's':
14637 case 'r':
14638 case 'a':
14639 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14640 /* Fast path */
14641 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14642 return -1;
14643 return 1;
14644 }
14645
14646 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14647 *p_str = v;
14648 Py_INCREF(*p_str);
14649 }
14650 else {
14651 if (arg->ch == 's')
14652 *p_str = PyObject_Str(v);
14653 else if (arg->ch == 'r')
14654 *p_str = PyObject_Repr(v);
14655 else
14656 *p_str = PyObject_ASCII(v);
14657 }
14658 break;
14659
14660 case 'i':
14661 case 'd':
14662 case 'u':
14663 case 'o':
14664 case 'x':
14665 case 'X':
14666 {
14667 int ret = mainformatlong(v, arg, p_str, writer);
14668 if (ret != 0)
14669 return ret;
14670 arg->sign = 1;
14671 break;
14672 }
14673
14674 case 'e':
14675 case 'E':
14676 case 'f':
14677 case 'F':
14678 case 'g':
14679 case 'G':
14680 if (arg->width == -1 && arg->prec == -1
14681 && !(arg->flags & (F_SIGN | F_BLANK)))
14682 {
14683 /* Fast path */
14684 if (formatfloat(v, arg, NULL, writer) == -1)
14685 return -1;
14686 return 1;
14687 }
14688
14689 arg->sign = 1;
14690 if (formatfloat(v, arg, p_str, NULL) == -1)
14691 return -1;
14692 break;
14693
14694 case 'c':
14695 {
14696 Py_UCS4 ch = formatchar(v);
14697 if (ch == (Py_UCS4) -1)
14698 return -1;
14699 if (arg->width == -1 && arg->prec == -1) {
14700 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014701 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014702 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014703 return 1;
14704 }
14705 *p_str = PyUnicode_FromOrdinal(ch);
14706 break;
14707 }
14708
14709 default:
14710 PyErr_Format(PyExc_ValueError,
14711 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014712 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014713 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14714 (int)arg->ch,
14715 ctx->fmtpos - 1);
14716 return -1;
14717 }
14718 if (*p_str == NULL)
14719 return -1;
14720 assert (PyUnicode_Check(*p_str));
14721 return 0;
14722}
14723
14724static int
14725unicode_format_arg_output(struct unicode_formatter_t *ctx,
14726 struct unicode_format_arg_t *arg,
14727 PyObject *str)
14728{
14729 Py_ssize_t len;
14730 enum PyUnicode_Kind kind;
14731 void *pbuf;
14732 Py_ssize_t pindex;
14733 Py_UCS4 signchar;
14734 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014735 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014736 Py_ssize_t sublen;
14737 _PyUnicodeWriter *writer = &ctx->writer;
14738 Py_UCS4 fill;
14739
14740 fill = ' ';
14741 if (arg->sign && arg->flags & F_ZERO)
14742 fill = '0';
14743
14744 if (PyUnicode_READY(str) == -1)
14745 return -1;
14746
14747 len = PyUnicode_GET_LENGTH(str);
14748 if ((arg->width == -1 || arg->width <= len)
14749 && (arg->prec == -1 || arg->prec >= len)
14750 && !(arg->flags & (F_SIGN | F_BLANK)))
14751 {
14752 /* Fast path */
14753 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14754 return -1;
14755 return 0;
14756 }
14757
14758 /* Truncate the string for "s", "r" and "a" formats
14759 if the precision is set */
14760 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14761 if (arg->prec >= 0 && len > arg->prec)
14762 len = arg->prec;
14763 }
14764
14765 /* Adjust sign and width */
14766 kind = PyUnicode_KIND(str);
14767 pbuf = PyUnicode_DATA(str);
14768 pindex = 0;
14769 signchar = '\0';
14770 if (arg->sign) {
14771 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14772 if (ch == '-' || ch == '+') {
14773 signchar = ch;
14774 len--;
14775 pindex++;
14776 }
14777 else if (arg->flags & F_SIGN)
14778 signchar = '+';
14779 else if (arg->flags & F_BLANK)
14780 signchar = ' ';
14781 else
14782 arg->sign = 0;
14783 }
14784 if (arg->width < len)
14785 arg->width = len;
14786
14787 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014788 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014789 if (!(arg->flags & F_LJUST)) {
14790 if (arg->sign) {
14791 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014792 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014793 }
14794 else {
14795 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014796 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014797 }
14798 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014799 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14800 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014801 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014802 }
14803
Victor Stinnera47082312012-10-04 02:19:54 +020014804 buflen = arg->width;
14805 if (arg->sign && len == arg->width)
14806 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014807 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014808 return -1;
14809
14810 /* Write the sign if needed */
14811 if (arg->sign) {
14812 if (fill != ' ') {
14813 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14814 writer->pos += 1;
14815 }
14816 if (arg->width > len)
14817 arg->width--;
14818 }
14819
14820 /* Write the numeric prefix for "x", "X" and "o" formats
14821 if the alternate form is used.
14822 For example, write "0x" for the "%#x" format. */
14823 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14824 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14825 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14826 if (fill != ' ') {
14827 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14828 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14829 writer->pos += 2;
14830 pindex += 2;
14831 }
14832 arg->width -= 2;
14833 if (arg->width < 0)
14834 arg->width = 0;
14835 len -= 2;
14836 }
14837
14838 /* Pad left with the fill character if needed */
14839 if (arg->width > len && !(arg->flags & F_LJUST)) {
14840 sublen = arg->width - len;
14841 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14842 writer->pos += sublen;
14843 arg->width = len;
14844 }
14845
14846 /* If padding with spaces: write sign if needed and/or numeric prefix if
14847 the alternate form is used */
14848 if (fill == ' ') {
14849 if (arg->sign) {
14850 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14851 writer->pos += 1;
14852 }
14853 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14854 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14855 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14856 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14857 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14858 writer->pos += 2;
14859 pindex += 2;
14860 }
14861 }
14862
14863 /* Write characters */
14864 if (len) {
14865 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14866 str, pindex, len);
14867 writer->pos += len;
14868 }
14869
14870 /* Pad right with the fill character if needed */
14871 if (arg->width > len) {
14872 sublen = arg->width - len;
14873 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14874 writer->pos += sublen;
14875 }
14876 return 0;
14877}
14878
14879/* Helper of PyUnicode_Format(): format one arg.
14880 Return 0 on success, raise an exception and return -1 on error. */
14881static int
14882unicode_format_arg(struct unicode_formatter_t *ctx)
14883{
14884 struct unicode_format_arg_t arg;
14885 PyObject *str;
14886 int ret;
14887
Victor Stinner8dbd4212012-12-04 09:30:24 +010014888 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14889 arg.flags = 0;
14890 arg.width = -1;
14891 arg.prec = -1;
14892 arg.sign = 0;
14893 str = NULL;
14894
Victor Stinnera47082312012-10-04 02:19:54 +020014895 ret = unicode_format_arg_parse(ctx, &arg);
14896 if (ret == -1)
14897 return -1;
14898
14899 ret = unicode_format_arg_format(ctx, &arg, &str);
14900 if (ret == -1)
14901 return -1;
14902
14903 if (ret != 1) {
14904 ret = unicode_format_arg_output(ctx, &arg, str);
14905 Py_DECREF(str);
14906 if (ret == -1)
14907 return -1;
14908 }
14909
14910 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14911 PyErr_SetString(PyExc_TypeError,
14912 "not all arguments converted during string formatting");
14913 return -1;
14914 }
14915 return 0;
14916}
14917
Alexander Belopolsky40018472011-02-26 01:02:56 +000014918PyObject *
14919PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014920{
Victor Stinnera47082312012-10-04 02:19:54 +020014921 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014922
Guido van Rossumd57fd912000-03-10 22:53:23 +000014923 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014924 PyErr_BadInternalCall();
14925 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014926 }
Victor Stinnera47082312012-10-04 02:19:54 +020014927
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014928 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014929 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014930
14931 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014932 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14933 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14934 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14935 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014936
Victor Stinner8f674cc2013-04-17 23:02:17 +020014937 _PyUnicodeWriter_Init(&ctx.writer);
14938 ctx.writer.min_length = ctx.fmtcnt + 100;
14939 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014940
Guido van Rossumd57fd912000-03-10 22:53:23 +000014941 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014942 ctx.arglen = PyTuple_Size(args);
14943 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014944 }
14945 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014946 ctx.arglen = -1;
14947 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014948 }
Victor Stinnera47082312012-10-04 02:19:54 +020014949 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014950 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014951 ctx.dict = args;
14952 else
14953 ctx.dict = NULL;
14954 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014955
Victor Stinnera47082312012-10-04 02:19:54 +020014956 while (--ctx.fmtcnt >= 0) {
14957 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014958 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014959
14960 nonfmtpos = ctx.fmtpos++;
14961 while (ctx.fmtcnt >= 0 &&
14962 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14963 ctx.fmtpos++;
14964 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014965 }
Victor Stinnera47082312012-10-04 02:19:54 +020014966 if (ctx.fmtcnt < 0) {
14967 ctx.fmtpos--;
14968 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014969 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014970
Victor Stinnercfc4c132013-04-03 01:48:39 +020014971 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14972 nonfmtpos, ctx.fmtpos) < 0)
14973 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014974 }
14975 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014976 ctx.fmtpos++;
14977 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014978 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014979 }
14980 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014981
Victor Stinnera47082312012-10-04 02:19:54 +020014982 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014983 PyErr_SetString(PyExc_TypeError,
14984 "not all arguments converted during string formatting");
14985 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014986 }
14987
Victor Stinnera47082312012-10-04 02:19:54 +020014988 if (ctx.args_owned) {
14989 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014990 }
Victor Stinnera47082312012-10-04 02:19:54 +020014991 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014992
Benjamin Peterson29060642009-01-31 22:14:21 +000014993 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014994 _PyUnicodeWriter_Dealloc(&ctx.writer);
14995 if (ctx.args_owned) {
14996 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014997 }
14998 return NULL;
14999}
15000
Jeremy Hylton938ace62002-07-17 16:30:39 +000015001static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000015002unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
15003
Tim Peters6d6c1a32001-08-02 04:15:00 +000015004static PyObject *
15005unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15006{
Benjamin Peterson29060642009-01-31 22:14:21 +000015007 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015008 static char *kwlist[] = {"object", "encoding", "errors", 0};
15009 char *encoding = NULL;
15010 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000015011
Benjamin Peterson14339b62009-01-31 16:36:08 +000015012 if (type != &PyUnicode_Type)
15013 return unicode_subtype_new(type, args, kwds);
15014 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015015 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015016 return NULL;
15017 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015018 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015019 if (encoding == NULL && errors == NULL)
15020 return PyObject_Str(x);
15021 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015022 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015023}
15024
Guido van Rossume023fe02001-08-30 03:12:59 +000015025static PyObject *
15026unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15027{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015028 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015029 Py_ssize_t length, char_size;
15030 int share_wstr, share_utf8;
15031 unsigned int kind;
15032 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015033
Benjamin Peterson14339b62009-01-31 16:36:08 +000015034 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015035
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015036 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015037 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015038 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015039 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015040 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015041 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015042 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015043 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015044
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015045 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015046 if (self == NULL) {
15047 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015048 return NULL;
15049 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015050 kind = PyUnicode_KIND(unicode);
15051 length = PyUnicode_GET_LENGTH(unicode);
15052
15053 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015054#ifdef Py_DEBUG
15055 _PyUnicode_HASH(self) = -1;
15056#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015057 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015058#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015059 _PyUnicode_STATE(self).interned = 0;
15060 _PyUnicode_STATE(self).kind = kind;
15061 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015062 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015063 _PyUnicode_STATE(self).ready = 1;
15064 _PyUnicode_WSTR(self) = NULL;
15065 _PyUnicode_UTF8_LENGTH(self) = 0;
15066 _PyUnicode_UTF8(self) = NULL;
15067 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015068 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015069
15070 share_utf8 = 0;
15071 share_wstr = 0;
15072 if (kind == PyUnicode_1BYTE_KIND) {
15073 char_size = 1;
15074 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15075 share_utf8 = 1;
15076 }
15077 else if (kind == PyUnicode_2BYTE_KIND) {
15078 char_size = 2;
15079 if (sizeof(wchar_t) == 2)
15080 share_wstr = 1;
15081 }
15082 else {
15083 assert(kind == PyUnicode_4BYTE_KIND);
15084 char_size = 4;
15085 if (sizeof(wchar_t) == 4)
15086 share_wstr = 1;
15087 }
15088
15089 /* Ensure we won't overflow the length. */
15090 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15091 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015092 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015093 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015094 data = PyObject_MALLOC((length + 1) * char_size);
15095 if (data == NULL) {
15096 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015097 goto onError;
15098 }
15099
Victor Stinnerc3c74152011-10-02 20:39:55 +020015100 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015101 if (share_utf8) {
15102 _PyUnicode_UTF8_LENGTH(self) = length;
15103 _PyUnicode_UTF8(self) = data;
15104 }
15105 if (share_wstr) {
15106 _PyUnicode_WSTR_LENGTH(self) = length;
15107 _PyUnicode_WSTR(self) = (wchar_t *)data;
15108 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015109
Christian Heimesf051e432016-09-13 20:22:02 +020015110 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015111 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015112 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015113#ifdef Py_DEBUG
15114 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15115#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015116 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015117 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015118
15119onError:
15120 Py_DECREF(unicode);
15121 Py_DECREF(self);
15122 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015123}
15124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015125PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015126"str(object='') -> str\n\
15127str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015128\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015129Create a new string object from the given object. If encoding or\n\
15130errors is specified, then the object must expose a data buffer\n\
15131that will be decoded using the given encoding and error handler.\n\
15132Otherwise, returns the result of object.__str__() (if defined)\n\
15133or repr(object).\n\
15134encoding defaults to sys.getdefaultencoding().\n\
15135errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015136
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015137static PyObject *unicode_iter(PyObject *seq);
15138
Guido van Rossumd57fd912000-03-10 22:53:23 +000015139PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015140 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015141 "str", /* tp_name */
15142 sizeof(PyUnicodeObject), /* tp_size */
15143 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015144 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015145 (destructor)unicode_dealloc, /* tp_dealloc */
15146 0, /* tp_print */
15147 0, /* tp_getattr */
15148 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015149 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015150 unicode_repr, /* tp_repr */
15151 &unicode_as_number, /* tp_as_number */
15152 &unicode_as_sequence, /* tp_as_sequence */
15153 &unicode_as_mapping, /* tp_as_mapping */
15154 (hashfunc) unicode_hash, /* tp_hash*/
15155 0, /* tp_call*/
15156 (reprfunc) unicode_str, /* tp_str */
15157 PyObject_GenericGetAttr, /* tp_getattro */
15158 0, /* tp_setattro */
15159 0, /* tp_as_buffer */
15160 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015161 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015162 unicode_doc, /* tp_doc */
15163 0, /* tp_traverse */
15164 0, /* tp_clear */
15165 PyUnicode_RichCompare, /* tp_richcompare */
15166 0, /* tp_weaklistoffset */
15167 unicode_iter, /* tp_iter */
15168 0, /* tp_iternext */
15169 unicode_methods, /* tp_methods */
15170 0, /* tp_members */
15171 0, /* tp_getset */
15172 &PyBaseObject_Type, /* tp_base */
15173 0, /* tp_dict */
15174 0, /* tp_descr_get */
15175 0, /* tp_descr_set */
15176 0, /* tp_dictoffset */
15177 0, /* tp_init */
15178 0, /* tp_alloc */
15179 unicode_new, /* tp_new */
15180 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015181};
15182
15183/* Initialize the Unicode implementation */
15184
Victor Stinner3a50e702011-10-18 21:21:00 +020015185int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015186{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015187 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015188 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015189 0x000A, /* LINE FEED */
15190 0x000D, /* CARRIAGE RETURN */
15191 0x001C, /* FILE SEPARATOR */
15192 0x001D, /* GROUP SEPARATOR */
15193 0x001E, /* RECORD SEPARATOR */
15194 0x0085, /* NEXT LINE */
15195 0x2028, /* LINE SEPARATOR */
15196 0x2029, /* PARAGRAPH SEPARATOR */
15197 };
15198
Fred Drakee4315f52000-05-09 19:53:39 +000015199 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015200 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015201 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015202 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015203 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015204
Guido van Rossumcacfc072002-05-24 19:01:59 +000015205 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015206 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015207
15208 /* initialize the linebreak bloom filter */
15209 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015210 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015211 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015212
Christian Heimes26532f72013-07-20 14:57:16 +020015213 if (PyType_Ready(&EncodingMapType) < 0)
15214 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015215
Benjamin Petersonc4311282012-10-30 23:21:10 -040015216 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15217 Py_FatalError("Can't initialize field name iterator type");
15218
15219 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15220 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015221
Victor Stinner3a50e702011-10-18 21:21:00 +020015222 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015223}
15224
15225/* Finalize the Unicode implementation */
15226
Christian Heimesa156e092008-02-16 07:38:31 +000015227int
15228PyUnicode_ClearFreeList(void)
15229{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015230 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015231}
15232
Guido van Rossumd57fd912000-03-10 22:53:23 +000015233void
Thomas Wouters78890102000-07-22 19:25:51 +000015234_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015235{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015236 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015237
Serhiy Storchaka05997252013-01-26 12:14:02 +020015238 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015239
Serhiy Storchaka05997252013-01-26 12:14:02 +020015240 for (i = 0; i < 256; i++)
15241 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015242 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015243 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015244}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015245
Walter Dörwald16807132007-05-25 13:52:07 +000015246void
15247PyUnicode_InternInPlace(PyObject **p)
15248{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015249 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015250 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015251#ifdef Py_DEBUG
15252 assert(s != NULL);
15253 assert(_PyUnicode_CHECK(s));
15254#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015255 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015256 return;
15257#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015258 /* If it's a subclass, we don't really know what putting
15259 it in the interned dict might do. */
15260 if (!PyUnicode_CheckExact(s))
15261 return;
15262 if (PyUnicode_CHECK_INTERNED(s))
15263 return;
15264 if (interned == NULL) {
15265 interned = PyDict_New();
15266 if (interned == NULL) {
15267 PyErr_Clear(); /* Don't leave an exception */
15268 return;
15269 }
15270 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015271 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015272 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015273 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015274 if (t == NULL) {
15275 PyErr_Clear();
15276 return;
15277 }
15278 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015279 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015280 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015281 return;
15282 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015283 /* The two references in interned are not counted by refcnt.
15284 The deallocator will take care of this */
15285 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015286 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015287}
15288
15289void
15290PyUnicode_InternImmortal(PyObject **p)
15291{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015292 PyUnicode_InternInPlace(p);
15293 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015294 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015295 Py_INCREF(*p);
15296 }
Walter Dörwald16807132007-05-25 13:52:07 +000015297}
15298
15299PyObject *
15300PyUnicode_InternFromString(const char *cp)
15301{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015302 PyObject *s = PyUnicode_FromString(cp);
15303 if (s == NULL)
15304 return NULL;
15305 PyUnicode_InternInPlace(&s);
15306 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015307}
15308
Alexander Belopolsky40018472011-02-26 01:02:56 +000015309void
15310_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015311{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015312 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015313 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015314 Py_ssize_t i, n;
15315 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015316
Benjamin Peterson14339b62009-01-31 16:36:08 +000015317 if (interned == NULL || !PyDict_Check(interned))
15318 return;
15319 keys = PyDict_Keys(interned);
15320 if (keys == NULL || !PyList_Check(keys)) {
15321 PyErr_Clear();
15322 return;
15323 }
Walter Dörwald16807132007-05-25 13:52:07 +000015324
Benjamin Peterson14339b62009-01-31 16:36:08 +000015325 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15326 detector, interned unicode strings are not forcibly deallocated;
15327 rather, we give them their stolen references back, and then clear
15328 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015329
Benjamin Peterson14339b62009-01-31 16:36:08 +000015330 n = PyList_GET_SIZE(keys);
15331 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015332 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015333 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015334 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015335 if (PyUnicode_READY(s) == -1) {
15336 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015337 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015338 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015339 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015340 case SSTATE_NOT_INTERNED:
15341 /* XXX Shouldn't happen */
15342 break;
15343 case SSTATE_INTERNED_IMMORTAL:
15344 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015345 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015346 break;
15347 case SSTATE_INTERNED_MORTAL:
15348 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015349 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015350 break;
15351 default:
15352 Py_FatalError("Inconsistent interned string state.");
15353 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015354 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015355 }
15356 fprintf(stderr, "total size of all interned strings: "
15357 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15358 "mortal/immortal\n", mortal_size, immortal_size);
15359 Py_DECREF(keys);
15360 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015361 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015362}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015363
15364
15365/********************* Unicode Iterator **************************/
15366
15367typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015368 PyObject_HEAD
15369 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015370 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015371} unicodeiterobject;
15372
15373static void
15374unicodeiter_dealloc(unicodeiterobject *it)
15375{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015376 _PyObject_GC_UNTRACK(it);
15377 Py_XDECREF(it->it_seq);
15378 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015379}
15380
15381static int
15382unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15383{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015384 Py_VISIT(it->it_seq);
15385 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015386}
15387
15388static PyObject *
15389unicodeiter_next(unicodeiterobject *it)
15390{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015391 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015392
Benjamin Peterson14339b62009-01-31 16:36:08 +000015393 assert(it != NULL);
15394 seq = it->it_seq;
15395 if (seq == NULL)
15396 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015397 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015398
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015399 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15400 int kind = PyUnicode_KIND(seq);
15401 void *data = PyUnicode_DATA(seq);
15402 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15403 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015404 if (item != NULL)
15405 ++it->it_index;
15406 return item;
15407 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015408
Benjamin Peterson14339b62009-01-31 16:36:08 +000015409 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015410 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015411 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015412}
15413
15414static PyObject *
15415unicodeiter_len(unicodeiterobject *it)
15416{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015417 Py_ssize_t len = 0;
15418 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015419 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015420 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015421}
15422
15423PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15424
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015425static PyObject *
15426unicodeiter_reduce(unicodeiterobject *it)
15427{
15428 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015429 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015430 it->it_seq, it->it_index);
15431 } else {
15432 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15433 if (u == NULL)
15434 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015435 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015436 }
15437}
15438
15439PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15440
15441static PyObject *
15442unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15443{
15444 Py_ssize_t index = PyLong_AsSsize_t(state);
15445 if (index == -1 && PyErr_Occurred())
15446 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015447 if (it->it_seq != NULL) {
15448 if (index < 0)
15449 index = 0;
15450 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15451 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15452 it->it_index = index;
15453 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015454 Py_RETURN_NONE;
15455}
15456
15457PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15458
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015459static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015460 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015461 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015462 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15463 reduce_doc},
15464 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15465 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015466 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015467};
15468
15469PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015470 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15471 "str_iterator", /* tp_name */
15472 sizeof(unicodeiterobject), /* tp_basicsize */
15473 0, /* tp_itemsize */
15474 /* methods */
15475 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15476 0, /* tp_print */
15477 0, /* tp_getattr */
15478 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015479 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015480 0, /* tp_repr */
15481 0, /* tp_as_number */
15482 0, /* tp_as_sequence */
15483 0, /* tp_as_mapping */
15484 0, /* tp_hash */
15485 0, /* tp_call */
15486 0, /* tp_str */
15487 PyObject_GenericGetAttr, /* tp_getattro */
15488 0, /* tp_setattro */
15489 0, /* tp_as_buffer */
15490 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15491 0, /* tp_doc */
15492 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15493 0, /* tp_clear */
15494 0, /* tp_richcompare */
15495 0, /* tp_weaklistoffset */
15496 PyObject_SelfIter, /* tp_iter */
15497 (iternextfunc)unicodeiter_next, /* tp_iternext */
15498 unicodeiter_methods, /* tp_methods */
15499 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015500};
15501
15502static PyObject *
15503unicode_iter(PyObject *seq)
15504{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015505 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015506
Benjamin Peterson14339b62009-01-31 16:36:08 +000015507 if (!PyUnicode_Check(seq)) {
15508 PyErr_BadInternalCall();
15509 return NULL;
15510 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015511 if (PyUnicode_READY(seq) == -1)
15512 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015513 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15514 if (it == NULL)
15515 return NULL;
15516 it->it_index = 0;
15517 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015518 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015519 _PyObject_GC_TRACK(it);
15520 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015521}
15522
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015523
15524size_t
15525Py_UNICODE_strlen(const Py_UNICODE *u)
15526{
15527 int res = 0;
15528 while(*u++)
15529 res++;
15530 return res;
15531}
15532
15533Py_UNICODE*
15534Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15535{
15536 Py_UNICODE *u = s1;
15537 while ((*u++ = *s2++));
15538 return s1;
15539}
15540
15541Py_UNICODE*
15542Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15543{
15544 Py_UNICODE *u = s1;
15545 while ((*u++ = *s2++))
15546 if (n-- == 0)
15547 break;
15548 return s1;
15549}
15550
15551Py_UNICODE*
15552Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15553{
15554 Py_UNICODE *u1 = s1;
15555 u1 += Py_UNICODE_strlen(u1);
15556 Py_UNICODE_strcpy(u1, s2);
15557 return s1;
15558}
15559
15560int
15561Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15562{
15563 while (*s1 && *s2 && *s1 == *s2)
15564 s1++, s2++;
15565 if (*s1 && *s2)
15566 return (*s1 < *s2) ? -1 : +1;
15567 if (*s1)
15568 return 1;
15569 if (*s2)
15570 return -1;
15571 return 0;
15572}
15573
15574int
15575Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15576{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015577 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015578 for (; n != 0; n--) {
15579 u1 = *s1;
15580 u2 = *s2;
15581 if (u1 != u2)
15582 return (u1 < u2) ? -1 : +1;
15583 if (u1 == '\0')
15584 return 0;
15585 s1++;
15586 s2++;
15587 }
15588 return 0;
15589}
15590
15591Py_UNICODE*
15592Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15593{
15594 const Py_UNICODE *p;
15595 for (p = s; *p; p++)
15596 if (*p == c)
15597 return (Py_UNICODE*)p;
15598 return NULL;
15599}
15600
15601Py_UNICODE*
15602Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15603{
15604 const Py_UNICODE *p;
15605 p = s + Py_UNICODE_strlen(s);
15606 while (p != s) {
15607 p--;
15608 if (*p == c)
15609 return (Py_UNICODE*)p;
15610 }
15611 return NULL;
15612}
Victor Stinner331ea922010-08-10 16:37:20 +000015613
Victor Stinner71133ff2010-09-01 23:43:53 +000015614Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015615PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015616{
Victor Stinner577db2c2011-10-11 22:12:48 +020015617 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015618 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015620 if (!PyUnicode_Check(unicode)) {
15621 PyErr_BadArgument();
15622 return NULL;
15623 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015624 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015625 if (u == NULL)
15626 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015627 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015628 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015629 PyErr_NoMemory();
15630 return NULL;
15631 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015632 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015633 size *= sizeof(Py_UNICODE);
15634 copy = PyMem_Malloc(size);
15635 if (copy == NULL) {
15636 PyErr_NoMemory();
15637 return NULL;
15638 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015639 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015640 return copy;
15641}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015642
Georg Brandl66c221e2010-10-14 07:04:07 +000015643/* A _string module, to export formatter_parser and formatter_field_name_split
15644 to the string.Formatter class implemented in Python. */
15645
15646static PyMethodDef _string_methods[] = {
15647 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15648 METH_O, PyDoc_STR("split the argument as a field name")},
15649 {"formatter_parser", (PyCFunction) formatter_parser,
15650 METH_O, PyDoc_STR("parse the argument as a format string")},
15651 {NULL, NULL}
15652};
15653
15654static struct PyModuleDef _string_module = {
15655 PyModuleDef_HEAD_INIT,
15656 "_string",
15657 PyDoc_STR("string helper module"),
15658 0,
15659 _string_methods,
15660 NULL,
15661 NULL,
15662 NULL,
15663 NULL
15664};
15665
15666PyMODINIT_FUNC
15667PyInit__string(void)
15668{
15669 return PyModule_Create(&_string_module);
15670}
15671
15672
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015673#ifdef __cplusplus
15674}
15675#endif