blob: 1650370baccae9ea65413e775a3ef5a4781f6f25 [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
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004213 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4214 PyErr_BadArgument();
4215 return (Py_UCS4)-1;
4216 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004217 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004218 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004219 return (Py_UCS4)-1;
4220 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004221 data = PyUnicode_DATA(unicode);
4222 kind = PyUnicode_KIND(unicode);
4223 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004224}
4225
4226int
4227PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4228{
4229 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004230 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004231 return -1;
4232 }
Victor Stinner488fa492011-12-12 00:01:39 +01004233 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004234 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004235 PyErr_SetString(PyExc_IndexError, "string index out of range");
4236 return -1;
4237 }
Victor Stinner488fa492011-12-12 00:01:39 +01004238 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004239 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004240 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4241 PyErr_SetString(PyExc_ValueError, "character out of range");
4242 return -1;
4243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004244 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4245 index, ch);
4246 return 0;
4247}
4248
Alexander Belopolsky40018472011-02-26 01:02:56 +00004249const char *
4250PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004251{
Victor Stinner42cb4622010-09-01 19:39:01 +00004252 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004253}
4254
Victor Stinner554f3f02010-06-16 23:33:54 +00004255/* create or adjust a UnicodeDecodeError */
4256static void
4257make_decode_exception(PyObject **exceptionObject,
4258 const char *encoding,
4259 const char *input, Py_ssize_t length,
4260 Py_ssize_t startpos, Py_ssize_t endpos,
4261 const char *reason)
4262{
4263 if (*exceptionObject == NULL) {
4264 *exceptionObject = PyUnicodeDecodeError_Create(
4265 encoding, input, length, startpos, endpos, reason);
4266 }
4267 else {
4268 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4269 goto onError;
4270 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4271 goto onError;
4272 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4273 goto onError;
4274 }
4275 return;
4276
4277onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004278 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004279}
4280
Steve Dowercc16be82016-09-08 10:35:16 -07004281#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004282/* error handling callback helper:
4283 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004284 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004285 and adjust various state variables.
4286 return 0 on success, -1 on error
4287*/
4288
Alexander Belopolsky40018472011-02-26 01:02:56 +00004289static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004290unicode_decode_call_errorhandler_wchar(
4291 const char *errors, PyObject **errorHandler,
4292 const char *encoding, const char *reason,
4293 const char **input, const char **inend, Py_ssize_t *startinpos,
4294 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4295 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004296{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004297 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004298
4299 PyObject *restuple = NULL;
4300 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004301 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004302 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004303 Py_ssize_t requiredsize;
4304 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004305 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004306 wchar_t *repwstr;
4307 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004308
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004309 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4310 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004311
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004312 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004313 *errorHandler = PyCodec_LookupError(errors);
4314 if (*errorHandler == NULL)
4315 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004316 }
4317
Victor Stinner554f3f02010-06-16 23:33:54 +00004318 make_decode_exception(exceptionObject,
4319 encoding,
4320 *input, *inend - *input,
4321 *startinpos, *endinpos,
4322 reason);
4323 if (*exceptionObject == NULL)
4324 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004325
4326 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4327 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004328 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004329 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004330 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004331 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004332 }
4333 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004334 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004335
4336 /* Copy back the bytes variables, which might have been modified by the
4337 callback */
4338 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4339 if (!inputobj)
4340 goto onError;
4341 if (!PyBytes_Check(inputobj)) {
4342 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4343 }
4344 *input = PyBytes_AS_STRING(inputobj);
4345 insize = PyBytes_GET_SIZE(inputobj);
4346 *inend = *input + insize;
4347 /* we can DECREF safely, as the exception has another reference,
4348 so the object won't go away. */
4349 Py_DECREF(inputobj);
4350
4351 if (newpos<0)
4352 newpos = insize+newpos;
4353 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004354 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004355 goto onError;
4356 }
4357
4358 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4359 if (repwstr == NULL)
4360 goto onError;
4361 /* need more space? (at least enough for what we
4362 have+the replacement+the rest of the string (starting
4363 at the new input position), so we won't have to check space
4364 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004365 requiredsize = *outpos;
4366 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4367 goto overflow;
4368 requiredsize += repwlen;
4369 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4370 goto overflow;
4371 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004372 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004373 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004374 requiredsize = 2*outsize;
4375 if (unicode_resize(output, requiredsize) < 0)
4376 goto onError;
4377 }
4378 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4379 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004380 *endinpos = newpos;
4381 *inptr = *input + newpos;
4382
4383 /* we made it! */
4384 Py_XDECREF(restuple);
4385 return 0;
4386
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004387 overflow:
4388 PyErr_SetString(PyExc_OverflowError,
4389 "decoded result is too long for a Python string");
4390
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004391 onError:
4392 Py_XDECREF(restuple);
4393 return -1;
4394}
Steve Dowercc16be82016-09-08 10:35:16 -07004395#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004396
4397static int
4398unicode_decode_call_errorhandler_writer(
4399 const char *errors, PyObject **errorHandler,
4400 const char *encoding, const char *reason,
4401 const char **input, const char **inend, Py_ssize_t *startinpos,
4402 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4403 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4404{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004405 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004406
4407 PyObject *restuple = NULL;
4408 PyObject *repunicode = NULL;
4409 Py_ssize_t insize;
4410 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004411 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004412 PyObject *inputobj = NULL;
4413
4414 if (*errorHandler == NULL) {
4415 *errorHandler = PyCodec_LookupError(errors);
4416 if (*errorHandler == NULL)
4417 goto onError;
4418 }
4419
4420 make_decode_exception(exceptionObject,
4421 encoding,
4422 *input, *inend - *input,
4423 *startinpos, *endinpos,
4424 reason);
4425 if (*exceptionObject == NULL)
4426 goto onError;
4427
4428 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4429 if (restuple == NULL)
4430 goto onError;
4431 if (!PyTuple_Check(restuple)) {
4432 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4433 goto onError;
4434 }
4435 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004436 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004437
4438 /* Copy back the bytes variables, which might have been modified by the
4439 callback */
4440 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4441 if (!inputobj)
4442 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004443 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004444 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004445 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004446 *input = PyBytes_AS_STRING(inputobj);
4447 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004448 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004449 /* we can DECREF safely, as the exception has another reference,
4450 so the object won't go away. */
4451 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004452
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004453 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004454 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004455 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004456 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004457 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004458 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004459
Victor Stinner8f674cc2013-04-17 23:02:17 +02004460 if (PyUnicode_READY(repunicode) < 0)
4461 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004462 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004463 if (replen > 1) {
4464 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004465 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004466 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4467 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4468 goto onError;
4469 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004470 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004471 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004472
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004473 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004474 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004475
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004476 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004477 Py_XDECREF(restuple);
4478 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004479
Benjamin Peterson29060642009-01-31 22:14:21 +00004480 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004481 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004482 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004483}
4484
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004485/* --- UTF-7 Codec -------------------------------------------------------- */
4486
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487/* See RFC2152 for details. We encode conservatively and decode liberally. */
4488
4489/* Three simple macros defining base-64. */
4490
4491/* Is c a base-64 character? */
4492
4493#define IS_BASE64(c) \
4494 (((c) >= 'A' && (c) <= 'Z') || \
4495 ((c) >= 'a' && (c) <= 'z') || \
4496 ((c) >= '0' && (c) <= '9') || \
4497 (c) == '+' || (c) == '/')
4498
4499/* given that c is a base-64 character, what is its base-64 value? */
4500
4501#define FROM_BASE64(c) \
4502 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4503 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4504 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4505 (c) == '+' ? 62 : 63)
4506
4507/* What is the base-64 character of the bottom 6 bits of n? */
4508
4509#define TO_BASE64(n) \
4510 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4511
4512/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4513 * decoded as itself. We are permissive on decoding; the only ASCII
4514 * byte not decoding to itself is the + which begins a base64
4515 * string. */
4516
4517#define DECODE_DIRECT(c) \
4518 ((c) <= 127 && (c) != '+')
4519
4520/* The UTF-7 encoder treats ASCII characters differently according to
4521 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4522 * the above). See RFC2152. This array identifies these different
4523 * sets:
4524 * 0 : "Set D"
4525 * alphanumeric and '(),-./:?
4526 * 1 : "Set O"
4527 * !"#$%&*;<=>@[]^_`{|}
4528 * 2 : "whitespace"
4529 * ht nl cr sp
4530 * 3 : special (must be base64 encoded)
4531 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4532 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004533
Tim Petersced69f82003-09-16 20:30:58 +00004534static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535char utf7_category[128] = {
4536/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4537 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4538/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4539 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4540/* sp ! " # $ % & ' ( ) * + , - . / */
4541 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4542/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4543 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4544/* @ A B C D E F G H I J K L M N O */
4545 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4546/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4547 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4548/* ` a b c d e f g h i j k l m n o */
4549 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4550/* p q r s t u v w x y z { | } ~ del */
4551 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004552};
4553
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554/* ENCODE_DIRECT: this character should be encoded as itself. The
4555 * answer depends on whether we are encoding set O as itself, and also
4556 * on whether we are encoding whitespace as itself. RFC2152 makes it
4557 * clear that the answers to these questions vary between
4558 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004559
Antoine Pitrou244651a2009-05-04 18:56:13 +00004560#define ENCODE_DIRECT(c, directO, directWS) \
4561 ((c) < 128 && (c) > 0 && \
4562 ((utf7_category[(c)] == 0) || \
4563 (directWS && (utf7_category[(c)] == 2)) || \
4564 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004565
Alexander Belopolsky40018472011-02-26 01:02:56 +00004566PyObject *
4567PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004568 Py_ssize_t size,
4569 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004570{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004571 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4572}
4573
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574/* The decoder. The only state we preserve is our read position,
4575 * i.e. how many characters we have consumed. So if we end in the
4576 * middle of a shift sequence we have to back off the read position
4577 * and the output to the beginning of the sequence, otherwise we lose
4578 * all the shift state (seen bits, number of bits seen, high
4579 * surrogate). */
4580
Alexander Belopolsky40018472011-02-26 01:02:56 +00004581PyObject *
4582PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004583 Py_ssize_t size,
4584 const char *errors,
4585 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004586{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004587 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004588 Py_ssize_t startinpos;
4589 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004590 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004591 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004592 const char *errmsg = "";
4593 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004594 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004595 unsigned int base64bits = 0;
4596 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004597 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004598 PyObject *errorHandler = NULL;
4599 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004600
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004601 if (size == 0) {
4602 if (consumed)
4603 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004604 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004605 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004606
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004607 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004608 _PyUnicodeWriter_Init(&writer);
4609 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004610
4611 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004612 e = s + size;
4613
4614 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004615 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004616 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004617 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004618
Antoine Pitrou244651a2009-05-04 18:56:13 +00004619 if (inShift) { /* in a base-64 section */
4620 if (IS_BASE64(ch)) { /* consume a base-64 character */
4621 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4622 base64bits += 6;
4623 s++;
4624 if (base64bits >= 16) {
4625 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004626 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004627 base64bits -= 16;
4628 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004629 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004630 if (surrogate) {
4631 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004632 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4633 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004634 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004635 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004636 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004637 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004638 }
4639 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004640 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004641 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004642 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004643 }
4644 }
Victor Stinner551ac952011-11-29 22:58:13 +01004645 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004646 /* first surrogate */
4647 surrogate = outCh;
4648 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004649 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004650 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004651 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004652 }
4653 }
4654 }
4655 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004656 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004657 if (base64bits > 0) { /* left-over bits */
4658 if (base64bits >= 6) {
4659 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004660 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004661 errmsg = "partial character in shift sequence";
4662 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004663 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004664 else {
4665 /* Some bits remain; they should be zero */
4666 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004667 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004668 errmsg = "non-zero padding bits in shift sequence";
4669 goto utf7Error;
4670 }
4671 }
4672 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004673 if (surrogate && DECODE_DIRECT(ch)) {
4674 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4675 goto onError;
4676 }
4677 surrogate = 0;
4678 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004679 /* '-' is absorbed; other terminating
4680 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004681 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004682 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004683 }
4684 }
4685 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004686 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004687 s++; /* consume '+' */
4688 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004689 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004690 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004691 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004692 }
4693 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004694 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004695 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004696 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004697 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004698 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004699 }
4700 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004701 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004702 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004703 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004704 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004705 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004706 else {
4707 startinpos = s-starts;
4708 s++;
4709 errmsg = "unexpected special character";
4710 goto utf7Error;
4711 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004712 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004713utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004714 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004715 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004716 errors, &errorHandler,
4717 "utf7", errmsg,
4718 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004719 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004720 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004721 }
4722
Antoine Pitrou244651a2009-05-04 18:56:13 +00004723 /* end of string */
4724
4725 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4726 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004727 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004728 if (surrogate ||
4729 (base64bits >= 6) ||
4730 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004731 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004732 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004733 errors, &errorHandler,
4734 "utf7", "unterminated shift sequence",
4735 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004736 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004737 goto onError;
4738 if (s < e)
4739 goto restart;
4740 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004741 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004742
4743 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004744 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004745 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004746 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004747 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004748 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004749 writer.kind, writer.data, shiftOutStart);
4750 Py_XDECREF(errorHandler);
4751 Py_XDECREF(exc);
4752 _PyUnicodeWriter_Dealloc(&writer);
4753 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004754 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004755 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004756 }
4757 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004758 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004759 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004760 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004761
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004762 Py_XDECREF(errorHandler);
4763 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004764 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004765
Benjamin Peterson29060642009-01-31 22:14:21 +00004766 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004767 Py_XDECREF(errorHandler);
4768 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004769 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004770 return NULL;
4771}
4772
4773
Alexander Belopolsky40018472011-02-26 01:02:56 +00004774PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004775_PyUnicode_EncodeUTF7(PyObject *str,
4776 int base64SetO,
4777 int base64WhiteSpace,
4778 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004779{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004780 int kind;
4781 void *data;
4782 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004783 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004784 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004785 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004786 unsigned int base64bits = 0;
4787 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004788 char * out;
4789 char * start;
4790
Benjamin Petersonbac79492012-01-14 13:34:47 -05004791 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004792 return NULL;
4793 kind = PyUnicode_KIND(str);
4794 data = PyUnicode_DATA(str);
4795 len = PyUnicode_GET_LENGTH(str);
4796
4797 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004798 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004799
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004800 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004801 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004802 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004803 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004804 if (v == NULL)
4805 return NULL;
4806
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004807 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004808 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004809 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004810
Antoine Pitrou244651a2009-05-04 18:56:13 +00004811 if (inShift) {
4812 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4813 /* shifting out */
4814 if (base64bits) { /* output remaining bits */
4815 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4816 base64buffer = 0;
4817 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004818 }
4819 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004820 /* Characters not in the BASE64 set implicitly unshift the sequence
4821 so no '-' is required, except if the character is itself a '-' */
4822 if (IS_BASE64(ch) || ch == '-') {
4823 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004824 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004825 *out++ = (char) ch;
4826 }
4827 else {
4828 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004829 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004830 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004831 else { /* not in a shift sequence */
4832 if (ch == '+') {
4833 *out++ = '+';
4834 *out++ = '-';
4835 }
4836 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4837 *out++ = (char) ch;
4838 }
4839 else {
4840 *out++ = '+';
4841 inShift = 1;
4842 goto encode_char;
4843 }
4844 }
4845 continue;
4846encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004847 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004848 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004849
Antoine Pitrou244651a2009-05-04 18:56:13 +00004850 /* code first surrogate */
4851 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004852 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004853 while (base64bits >= 6) {
4854 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4855 base64bits -= 6;
4856 }
4857 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004858 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004859 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004860 base64bits += 16;
4861 base64buffer = (base64buffer << 16) | ch;
4862 while (base64bits >= 6) {
4863 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4864 base64bits -= 6;
4865 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004866 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004867 if (base64bits)
4868 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4869 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004870 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004871 if (_PyBytes_Resize(&v, out - start) < 0)
4872 return NULL;
4873 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004874}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004875PyObject *
4876PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4877 Py_ssize_t size,
4878 int base64SetO,
4879 int base64WhiteSpace,
4880 const char *errors)
4881{
4882 PyObject *result;
4883 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4884 if (tmp == NULL)
4885 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004886 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004887 base64WhiteSpace, errors);
4888 Py_DECREF(tmp);
4889 return result;
4890}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004891
Antoine Pitrou244651a2009-05-04 18:56:13 +00004892#undef IS_BASE64
4893#undef FROM_BASE64
4894#undef TO_BASE64
4895#undef DECODE_DIRECT
4896#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004897
Guido van Rossumd57fd912000-03-10 22:53:23 +00004898/* --- UTF-8 Codec -------------------------------------------------------- */
4899
Alexander Belopolsky40018472011-02-26 01:02:56 +00004900PyObject *
4901PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004902 Py_ssize_t size,
4903 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004904{
Walter Dörwald69652032004-09-07 20:24:22 +00004905 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4906}
4907
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004908#include "stringlib/asciilib.h"
4909#include "stringlib/codecs.h"
4910#include "stringlib/undef.h"
4911
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004912#include "stringlib/ucs1lib.h"
4913#include "stringlib/codecs.h"
4914#include "stringlib/undef.h"
4915
4916#include "stringlib/ucs2lib.h"
4917#include "stringlib/codecs.h"
4918#include "stringlib/undef.h"
4919
4920#include "stringlib/ucs4lib.h"
4921#include "stringlib/codecs.h"
4922#include "stringlib/undef.h"
4923
Antoine Pitrouab868312009-01-10 15:40:25 +00004924/* Mask to quickly check whether a C 'long' contains a
4925 non-ASCII, UTF8-encoded char. */
4926#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004927# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004928#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004929# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004930#else
4931# error C 'long' size should be either 4 or 8!
4932#endif
4933
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004934static Py_ssize_t
4935ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004936{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004937 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004938 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004939
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004940 /*
4941 * Issue #17237: m68k is a bit different from most architectures in
4942 * that objects do not use "natural alignment" - for example, int and
4943 * long are only aligned at 2-byte boundaries. Therefore the assert()
4944 * won't work; also, tests have shown that skipping the "optimised
4945 * version" will even speed up m68k.
4946 */
4947#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004948#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004949 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4950 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004951 /* Fast path, see in STRINGLIB(utf8_decode) for
4952 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004953 /* Help allocation */
4954 const char *_p = p;
4955 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004956 while (_p < aligned_end) {
4957 unsigned long value = *(const unsigned long *) _p;
4958 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004959 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004960 *((unsigned long *)q) = value;
4961 _p += SIZEOF_LONG;
4962 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004963 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004964 p = _p;
4965 while (p < end) {
4966 if ((unsigned char)*p & 0x80)
4967 break;
4968 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004969 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004970 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004971 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004972#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004973#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004974 while (p < end) {
4975 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4976 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004977 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004978 /* Help allocation */
4979 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004980 while (_p < aligned_end) {
4981 unsigned long value = *(unsigned long *) _p;
4982 if (value & ASCII_CHAR_MASK)
4983 break;
4984 _p += SIZEOF_LONG;
4985 }
4986 p = _p;
4987 if (_p == end)
4988 break;
4989 }
4990 if ((unsigned char)*p & 0x80)
4991 break;
4992 ++p;
4993 }
4994 memcpy(dest, start, p - start);
4995 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004996}
Antoine Pitrouab868312009-01-10 15:40:25 +00004997
Victor Stinner785938e2011-12-11 20:09:03 +01004998PyObject *
4999PyUnicode_DecodeUTF8Stateful(const char *s,
5000 Py_ssize_t size,
5001 const char *errors,
5002 Py_ssize_t *consumed)
5003{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005004 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01005005 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005006 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005007
5008 Py_ssize_t startinpos;
5009 Py_ssize_t endinpos;
5010 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02005011 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005012 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02005013 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01005014
5015 if (size == 0) {
5016 if (consumed)
5017 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005018 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01005019 }
5020
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005021 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
5022 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01005023 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005024 *consumed = 1;
5025 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01005026 }
5027
Victor Stinner8f674cc2013-04-17 23:02:17 +02005028 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005029 writer.min_length = size;
5030 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005031 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01005032
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005033 writer.pos = ascii_decode(s, end, writer.data);
5034 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005035 while (s < end) {
5036 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005037 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02005038
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005039 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005040 if (PyUnicode_IS_ASCII(writer.buffer))
5041 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005042 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005043 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005044 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005045 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005046 } else {
5047 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005048 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005049 }
5050
5051 switch (ch) {
5052 case 0:
5053 if (s == end || consumed)
5054 goto End;
5055 errmsg = "unexpected end of data";
5056 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005057 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005058 break;
5059 case 1:
5060 errmsg = "invalid start byte";
5061 startinpos = s - starts;
5062 endinpos = startinpos + 1;
5063 break;
5064 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005065 case 3:
5066 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005067 errmsg = "invalid continuation byte";
5068 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005069 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005070 break;
5071 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005072 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005073 goto onError;
5074 continue;
5075 }
5076
Victor Stinner1d65d912015-10-05 13:43:50 +02005077 if (error_handler == _Py_ERROR_UNKNOWN)
5078 error_handler = get_error_handler(errors);
5079
5080 switch (error_handler) {
5081 case _Py_ERROR_IGNORE:
5082 s += (endinpos - startinpos);
5083 break;
5084
5085 case _Py_ERROR_REPLACE:
5086 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5087 goto onError;
5088 s += (endinpos - startinpos);
5089 break;
5090
5091 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005092 {
5093 Py_ssize_t i;
5094
Victor Stinner1d65d912015-10-05 13:43:50 +02005095 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5096 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005097 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005098 ch = (Py_UCS4)(unsigned char)(starts[i]);
5099 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5100 ch + 0xdc00);
5101 writer.pos++;
5102 }
5103 s += (endinpos - startinpos);
5104 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005105 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005106
5107 default:
5108 if (unicode_decode_call_errorhandler_writer(
5109 errors, &error_handler_obj,
5110 "utf-8", errmsg,
5111 &starts, &end, &startinpos, &endinpos, &exc, &s,
5112 &writer))
5113 goto onError;
5114 }
Victor Stinner785938e2011-12-11 20:09:03 +01005115 }
5116
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005117End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005118 if (consumed)
5119 *consumed = s - starts;
5120
Victor Stinner1d65d912015-10-05 13:43:50 +02005121 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005122 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005123 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005124
5125onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005126 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005127 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005128 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005129 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005130}
5131
Xavier de Gaye76febd02016-12-15 20:59:58 +01005132#if defined(__APPLE__) || defined(__ANDROID__)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005133
5134/* Simplified UTF-8 decoder using surrogateescape error handler,
Xavier de Gaye76febd02016-12-15 20:59:58 +01005135 used to decode the command line arguments on Mac OS X and Android.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005136
5137 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005138 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005139
5140wchar_t*
5141_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5142{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005143 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005144 wchar_t *unicode;
5145 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005146
5147 /* Note: size will always be longer than the resulting Unicode
5148 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005149 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005150 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005151 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005152 if (!unicode)
5153 return NULL;
5154
5155 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005156 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005157 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005158 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005159 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005160#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005161 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005162#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005163 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005164#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005165 if (ch > 0xFF) {
5166#if SIZEOF_WCHAR_T == 4
5167 assert(0);
5168#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005169 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005170 /* compute and append the two surrogates: */
5171 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5172 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5173#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005174 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005175 else {
5176 if (!ch && s == e)
5177 break;
5178 /* surrogateescape */
5179 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5180 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005181 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005182 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005183 return unicode;
5184}
5185
Xavier de Gaye76febd02016-12-15 20:59:58 +01005186#endif /* __APPLE__ or __ANDROID__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005187
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005188/* Primary internal function which creates utf8 encoded bytes objects.
5189
5190 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005191 and allocate exactly as much space needed at the end. Else allocate the
5192 maximum possible needed (4 result bytes per Unicode character), and return
5193 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005194*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005195PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005196_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005197{
Victor Stinner6099a032011-12-18 14:22:26 +01005198 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005199 void *data;
5200 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005202 if (!PyUnicode_Check(unicode)) {
5203 PyErr_BadArgument();
5204 return NULL;
5205 }
5206
5207 if (PyUnicode_READY(unicode) == -1)
5208 return NULL;
5209
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005210 if (PyUnicode_UTF8(unicode))
5211 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5212 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005213
5214 kind = PyUnicode_KIND(unicode);
5215 data = PyUnicode_DATA(unicode);
5216 size = PyUnicode_GET_LENGTH(unicode);
5217
Benjamin Petersonead6b532011-12-20 17:23:42 -06005218 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005219 default:
5220 assert(0);
5221 case PyUnicode_1BYTE_KIND:
5222 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5223 assert(!PyUnicode_IS_ASCII(unicode));
5224 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5225 case PyUnicode_2BYTE_KIND:
5226 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5227 case PyUnicode_4BYTE_KIND:
5228 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005229 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005230}
5231
Alexander Belopolsky40018472011-02-26 01:02:56 +00005232PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005233PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5234 Py_ssize_t size,
5235 const char *errors)
5236{
5237 PyObject *v, *unicode;
5238
5239 unicode = PyUnicode_FromUnicode(s, size);
5240 if (unicode == NULL)
5241 return NULL;
5242 v = _PyUnicode_AsUTF8String(unicode, errors);
5243 Py_DECREF(unicode);
5244 return v;
5245}
5246
5247PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005248PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005249{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005250 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005251}
5252
Walter Dörwald41980ca2007-08-16 21:55:45 +00005253/* --- UTF-32 Codec ------------------------------------------------------- */
5254
5255PyObject *
5256PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005257 Py_ssize_t size,
5258 const char *errors,
5259 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005260{
5261 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5262}
5263
5264PyObject *
5265PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005266 Py_ssize_t size,
5267 const char *errors,
5268 int *byteorder,
5269 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005270{
5271 const char *starts = s;
5272 Py_ssize_t startinpos;
5273 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005274 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005275 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005276 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005277 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005278 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005279 PyObject *errorHandler = NULL;
5280 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005281
Walter Dörwald41980ca2007-08-16 21:55:45 +00005282 q = (unsigned char *)s;
5283 e = q + size;
5284
5285 if (byteorder)
5286 bo = *byteorder;
5287
5288 /* Check for BOM marks (U+FEFF) in the input and adjust current
5289 byte order setting accordingly. In native mode, the leading BOM
5290 mark is skipped, in all other modes, it is copied to the output
5291 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005292 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005293 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005294 if (bom == 0x0000FEFF) {
5295 bo = -1;
5296 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005297 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005298 else if (bom == 0xFFFE0000) {
5299 bo = 1;
5300 q += 4;
5301 }
5302 if (byteorder)
5303 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005304 }
5305
Victor Stinnere64322e2012-10-30 23:12:47 +01005306 if (q == e) {
5307 if (consumed)
5308 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005309 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005310 }
5311
Victor Stinnere64322e2012-10-30 23:12:47 +01005312#ifdef WORDS_BIGENDIAN
5313 le = bo < 0;
5314#else
5315 le = bo <= 0;
5316#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005317 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005318
Victor Stinner8f674cc2013-04-17 23:02:17 +02005319 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005320 writer.min_length = (e - q + 3) / 4;
5321 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005322 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005323
Victor Stinnere64322e2012-10-30 23:12:47 +01005324 while (1) {
5325 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005326 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005327
Victor Stinnere64322e2012-10-30 23:12:47 +01005328 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005329 enum PyUnicode_Kind kind = writer.kind;
5330 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005331 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005332 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005333 if (le) {
5334 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005335 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005336 if (ch > maxch)
5337 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005338 if (kind != PyUnicode_1BYTE_KIND &&
5339 Py_UNICODE_IS_SURROGATE(ch))
5340 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005341 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005342 q += 4;
5343 } while (q <= last);
5344 }
5345 else {
5346 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005347 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005348 if (ch > maxch)
5349 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005350 if (kind != PyUnicode_1BYTE_KIND &&
5351 Py_UNICODE_IS_SURROGATE(ch))
5352 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005353 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005354 q += 4;
5355 } while (q <= last);
5356 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005357 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005358 }
5359
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005360 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005361 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005362 startinpos = ((const char *)q) - starts;
5363 endinpos = startinpos + 4;
5364 }
5365 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005366 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005367 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005368 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005369 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005370 startinpos = ((const char *)q) - starts;
5371 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005372 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005373 else {
5374 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005375 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005376 goto onError;
5377 q += 4;
5378 continue;
5379 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005380 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005381 startinpos = ((const char *)q) - starts;
5382 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005383 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005384
5385 /* The remaining input chars are ignored if the callback
5386 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005387 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005388 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005389 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005390 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005391 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005392 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005393 }
5394
Walter Dörwald41980ca2007-08-16 21:55:45 +00005395 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005396 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005397
Walter Dörwald41980ca2007-08-16 21:55:45 +00005398 Py_XDECREF(errorHandler);
5399 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005400 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005401
Benjamin Peterson29060642009-01-31 22:14:21 +00005402 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005403 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005404 Py_XDECREF(errorHandler);
5405 Py_XDECREF(exc);
5406 return NULL;
5407}
5408
5409PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005410_PyUnicode_EncodeUTF32(PyObject *str,
5411 const char *errors,
5412 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005413{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005414 enum PyUnicode_Kind kind;
5415 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005416 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005417 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005418 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005419#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005420 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005421#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005422 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005423#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005424 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005425 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005426 PyObject *errorHandler = NULL;
5427 PyObject *exc = NULL;
5428 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005429
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005430 if (!PyUnicode_Check(str)) {
5431 PyErr_BadArgument();
5432 return NULL;
5433 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005434 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005435 return NULL;
5436 kind = PyUnicode_KIND(str);
5437 data = PyUnicode_DATA(str);
5438 len = PyUnicode_GET_LENGTH(str);
5439
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005440 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005441 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005442 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005443 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005444 if (v == NULL)
5445 return NULL;
5446
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005447 /* output buffer is 4-bytes aligned */
5448 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005449 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005450 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005451 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005452 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005453 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005454
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005455 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005456 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005457 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005458 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005459 else
5460 encoding = "utf-32";
5461
5462 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005463 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5464 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005465 }
5466
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005467 pos = 0;
5468 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005470
5471 if (kind == PyUnicode_2BYTE_KIND) {
5472 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5473 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005474 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005475 else {
5476 assert(kind == PyUnicode_4BYTE_KIND);
5477 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5478 &out, native_ordering);
5479 }
5480 if (pos == len)
5481 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005482
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005483 rep = unicode_encode_call_errorhandler(
5484 errors, &errorHandler,
5485 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005486 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005487 if (!rep)
5488 goto error;
5489
5490 if (PyBytes_Check(rep)) {
5491 repsize = PyBytes_GET_SIZE(rep);
5492 if (repsize & 3) {
5493 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005494 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005495 "surrogates not allowed");
5496 goto error;
5497 }
5498 moreunits = repsize / 4;
5499 }
5500 else {
5501 assert(PyUnicode_Check(rep));
5502 if (PyUnicode_READY(rep) < 0)
5503 goto error;
5504 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5505 if (!PyUnicode_IS_ASCII(rep)) {
5506 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005507 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005508 "surrogates not allowed");
5509 goto error;
5510 }
5511 }
5512
5513 /* four bytes are reserved for each surrogate */
5514 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005515 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka82a90752017-07-11 07:27:56 +03005516 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005517 /* integer overflow */
5518 PyErr_NoMemory();
5519 goto error;
5520 }
Serhiy Storchaka82a90752017-07-11 07:27:56 +03005521 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005522 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005523 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005524 }
5525
5526 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005527 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005528 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005529 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005530 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005531 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5532 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005533 }
5534
5535 Py_CLEAR(rep);
5536 }
5537
5538 /* Cut back to size actually needed. This is necessary for, for example,
5539 encoding of a string containing isolated surrogates and the 'ignore'
5540 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005541 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005542 if (nsize != PyBytes_GET_SIZE(v))
5543 _PyBytes_Resize(&v, nsize);
5544 Py_XDECREF(errorHandler);
5545 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005546 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005547 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005548 error:
5549 Py_XDECREF(rep);
5550 Py_XDECREF(errorHandler);
5551 Py_XDECREF(exc);
5552 Py_XDECREF(v);
5553 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005554}
5555
Alexander Belopolsky40018472011-02-26 01:02:56 +00005556PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005557PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5558 Py_ssize_t size,
5559 const char *errors,
5560 int byteorder)
5561{
5562 PyObject *result;
5563 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5564 if (tmp == NULL)
5565 return NULL;
5566 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5567 Py_DECREF(tmp);
5568 return result;
5569}
5570
5571PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005572PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005573{
Victor Stinnerb960b342011-11-20 19:12:52 +01005574 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005575}
5576
Guido van Rossumd57fd912000-03-10 22:53:23 +00005577/* --- UTF-16 Codec ------------------------------------------------------- */
5578
Tim Peters772747b2001-08-09 22:21:55 +00005579PyObject *
5580PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005581 Py_ssize_t size,
5582 const char *errors,
5583 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005584{
Walter Dörwald69652032004-09-07 20:24:22 +00005585 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5586}
5587
5588PyObject *
5589PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005590 Py_ssize_t size,
5591 const char *errors,
5592 int *byteorder,
5593 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005594{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005595 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005596 Py_ssize_t startinpos;
5597 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005598 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005599 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005600 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005601 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005602 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005603 PyObject *errorHandler = NULL;
5604 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005605 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005606
Tim Peters772747b2001-08-09 22:21:55 +00005607 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005608 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005609
5610 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005611 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005612
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005613 /* Check for BOM marks (U+FEFF) in the input and adjust current
5614 byte order setting accordingly. In native mode, the leading BOM
5615 mark is skipped, in all other modes, it is copied to the output
5616 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005617 if (bo == 0 && size >= 2) {
5618 const Py_UCS4 bom = (q[1] << 8) | q[0];
5619 if (bom == 0xFEFF) {
5620 q += 2;
5621 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005622 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005623 else if (bom == 0xFFFE) {
5624 q += 2;
5625 bo = 1;
5626 }
5627 if (byteorder)
5628 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005629 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630
Antoine Pitrou63065d72012-05-15 23:48:04 +02005631 if (q == e) {
5632 if (consumed)
5633 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005634 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005635 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005636
Christian Heimes743e0cd2012-10-17 23:52:17 +02005637#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005638 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005639 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005640#else
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-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005643#endif
Tim Peters772747b2001-08-09 22:21:55 +00005644
Antoine Pitrou63065d72012-05-15 23:48:04 +02005645 /* Note: size will always be longer than the resulting Unicode
5646 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005647 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005648 writer.min_length = (e - q + 1) / 2;
5649 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005650 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005651
Antoine Pitrou63065d72012-05-15 23:48:04 +02005652 while (1) {
5653 Py_UCS4 ch = 0;
5654 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005655 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005656 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005657 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005658 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005659 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005660 native_ordering);
5661 else
5662 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005663 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005664 native_ordering);
5665 } else if (kind == PyUnicode_2BYTE_KIND) {
5666 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005667 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005668 native_ordering);
5669 } else {
5670 assert(kind == PyUnicode_4BYTE_KIND);
5671 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005672 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005673 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005674 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005675 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005676
Antoine Pitrou63065d72012-05-15 23:48:04 +02005677 switch (ch)
5678 {
5679 case 0:
5680 /* remaining byte at the end? (size should be even) */
5681 if (q == e || consumed)
5682 goto End;
5683 errmsg = "truncated data";
5684 startinpos = ((const char *)q) - starts;
5685 endinpos = ((const char *)e) - starts;
5686 break;
5687 /* The remaining input chars are ignored if the callback
5688 chooses to skip the input */
5689 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005690 q -= 2;
5691 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005692 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005693 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005694 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005695 endinpos = ((const char *)e) - starts;
5696 break;
5697 case 2:
5698 errmsg = "illegal encoding";
5699 startinpos = ((const char *)q) - 2 - starts;
5700 endinpos = startinpos + 2;
5701 break;
5702 case 3:
5703 errmsg = "illegal UTF-16 surrogate";
5704 startinpos = ((const char *)q) - 4 - starts;
5705 endinpos = startinpos + 2;
5706 break;
5707 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005708 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005709 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005710 continue;
5711 }
5712
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005713 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005714 errors,
5715 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005716 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005717 &starts,
5718 (const char **)&e,
5719 &startinpos,
5720 &endinpos,
5721 &exc,
5722 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005723 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005724 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725 }
5726
Antoine Pitrou63065d72012-05-15 23:48:04 +02005727End:
Walter Dörwald69652032004-09-07 20:24:22 +00005728 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005729 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005730
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005731 Py_XDECREF(errorHandler);
5732 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005733 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005734
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005736 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005737 Py_XDECREF(errorHandler);
5738 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005739 return NULL;
5740}
5741
Tim Peters772747b2001-08-09 22:21:55 +00005742PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005743_PyUnicode_EncodeUTF16(PyObject *str,
5744 const char *errors,
5745 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005746{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005747 enum PyUnicode_Kind kind;
5748 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005749 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005750 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005751 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005752 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005753#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005754 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005755#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005756 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005757#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005758 const char *encoding;
5759 Py_ssize_t nsize, pos;
5760 PyObject *errorHandler = NULL;
5761 PyObject *exc = NULL;
5762 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005763
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005764 if (!PyUnicode_Check(str)) {
5765 PyErr_BadArgument();
5766 return NULL;
5767 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005768 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005769 return NULL;
5770 kind = PyUnicode_KIND(str);
5771 data = PyUnicode_DATA(str);
5772 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005773
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005774 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005775 if (kind == PyUnicode_4BYTE_KIND) {
5776 const Py_UCS4 *in = (const Py_UCS4 *)data;
5777 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005778 while (in < end) {
5779 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005780 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005781 }
5782 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005783 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005784 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005785 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005786 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005787 nsize = len + pairs + (byteorder == 0);
5788 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005789 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005790 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005791 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005792
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005793 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005794 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005795 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005796 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005797 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005798 }
5799 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005800 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005801 }
Tim Peters772747b2001-08-09 22:21:55 +00005802
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005803 if (kind == PyUnicode_1BYTE_KIND) {
5804 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5805 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005806 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005807
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005808 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005809 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005810 }
5811 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005812 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005813 }
5814 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005815 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005816 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005817
5818 pos = 0;
5819 while (pos < len) {
5820 Py_ssize_t repsize, moreunits;
5821
5822 if (kind == PyUnicode_2BYTE_KIND) {
5823 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5824 &out, native_ordering);
5825 }
5826 else {
5827 assert(kind == PyUnicode_4BYTE_KIND);
5828 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5829 &out, native_ordering);
5830 }
5831 if (pos == len)
5832 break;
5833
5834 rep = unicode_encode_call_errorhandler(
5835 errors, &errorHandler,
5836 encoding, "surrogates not allowed",
5837 str, &exc, pos, pos + 1, &pos);
5838 if (!rep)
5839 goto error;
5840
5841 if (PyBytes_Check(rep)) {
5842 repsize = PyBytes_GET_SIZE(rep);
5843 if (repsize & 1) {
5844 raise_encode_exception(&exc, encoding,
5845 str, pos - 1, pos,
5846 "surrogates not allowed");
5847 goto error;
5848 }
5849 moreunits = repsize / 2;
5850 }
5851 else {
5852 assert(PyUnicode_Check(rep));
5853 if (PyUnicode_READY(rep) < 0)
5854 goto error;
5855 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5856 if (!PyUnicode_IS_ASCII(rep)) {
5857 raise_encode_exception(&exc, encoding,
5858 str, pos - 1, pos,
5859 "surrogates not allowed");
5860 goto error;
5861 }
5862 }
5863
5864 /* two bytes are reserved for each surrogate */
5865 if (moreunits > 1) {
5866 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka82a90752017-07-11 07:27:56 +03005867 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005868 /* integer overflow */
5869 PyErr_NoMemory();
5870 goto error;
5871 }
Serhiy Storchaka82a90752017-07-11 07:27:56 +03005872 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005873 goto error;
5874 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5875 }
5876
5877 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005878 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005879 out += moreunits;
5880 } else /* rep is unicode */ {
5881 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5882 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5883 &out, native_ordering);
5884 }
5885
5886 Py_CLEAR(rep);
5887 }
5888
5889 /* Cut back to size actually needed. This is necessary for, for example,
5890 encoding of a string containing isolated surrogates and the 'ignore' handler
5891 is used. */
5892 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5893 if (nsize != PyBytes_GET_SIZE(v))
5894 _PyBytes_Resize(&v, nsize);
5895 Py_XDECREF(errorHandler);
5896 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005897 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005898 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005899 error:
5900 Py_XDECREF(rep);
5901 Py_XDECREF(errorHandler);
5902 Py_XDECREF(exc);
5903 Py_XDECREF(v);
5904 return NULL;
5905#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005906}
5907
Alexander Belopolsky40018472011-02-26 01:02:56 +00005908PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005909PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5910 Py_ssize_t size,
5911 const char *errors,
5912 int byteorder)
5913{
5914 PyObject *result;
5915 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5916 if (tmp == NULL)
5917 return NULL;
5918 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5919 Py_DECREF(tmp);
5920 return result;
5921}
5922
5923PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005924PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005926 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927}
5928
5929/* --- Unicode Escape Codec ----------------------------------------------- */
5930
Fredrik Lundh06d12682001-01-24 07:59:11 +00005931static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005932
Alexander Belopolsky40018472011-02-26 01:02:56 +00005933PyObject *
Eric V. Smith56466482016-10-31 14:46:26 -04005934_PyUnicode_DecodeUnicodeEscape(const char *s,
5935 Py_ssize_t size,
5936 const char *errors,
5937 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005939 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005940 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005942 PyObject *errorHandler = NULL;
5943 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005944
Eric V. Smith56466482016-10-31 14:46:26 -04005945 // so we can remember if we've seen an invalid escape char or not
5946 *first_invalid_escape = NULL;
5947
Victor Stinner62ec3312016-09-06 17:04:34 -07005948 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005949 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005950 }
5951 /* Escaped strings will always be longer than the resulting
5952 Unicode string, so we start with size here and then reduce the
5953 length after conversion to the true value.
5954 (but if the error callback returns a long replacement string
5955 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005956 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005957 writer.min_length = size;
5958 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5959 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005960 }
5961
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962 end = s + size;
5963 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005964 unsigned char c = (unsigned char) *s++;
5965 Py_UCS4 ch;
5966 int count;
5967 Py_ssize_t startinpos;
5968 Py_ssize_t endinpos;
5969 const char *message;
5970
5971#define WRITE_ASCII_CHAR(ch) \
5972 do { \
5973 assert(ch <= 127); \
5974 assert(writer.pos < writer.size); \
5975 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5976 } while(0)
5977
5978#define WRITE_CHAR(ch) \
5979 do { \
5980 if (ch <= writer.maxchar) { \
5981 assert(writer.pos < writer.size); \
5982 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5983 } \
5984 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5985 goto onError; \
5986 } \
5987 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005988
5989 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005990 if (c != '\\') {
5991 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992 continue;
5993 }
5994
Victor Stinner62ec3312016-09-06 17:04:34 -07005995 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005996 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005997 if (s >= end) {
5998 message = "\\ at end of string";
5999 goto error;
6000 }
6001 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006002
Victor Stinner62ec3312016-09-06 17:04:34 -07006003 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006004 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006005
Benjamin Peterson29060642009-01-31 22:14:21 +00006006 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006007 case '\n': continue;
6008 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6009 case '\'': WRITE_ASCII_CHAR('\''); continue;
6010 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6011 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006012 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006013 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6014 case 't': WRITE_ASCII_CHAR('\t'); continue;
6015 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6016 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006017 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006018 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006019 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006020 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021
Benjamin Peterson29060642009-01-31 22:14:21 +00006022 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006023 case '0': case '1': case '2': case '3':
6024 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006025 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006026 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006027 ch = (ch<<3) + *s++ - '0';
6028 if (s < end && '0' <= *s && *s <= '7') {
6029 ch = (ch<<3) + *s++ - '0';
6030 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006031 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006032 WRITE_CHAR(ch);
6033 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006034
Benjamin Peterson29060642009-01-31 22:14:21 +00006035 /* hex escapes */
6036 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006038 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006039 message = "truncated \\xXX escape";
6040 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006041
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006044 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006045 message = "truncated \\uXXXX escape";
6046 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047
Benjamin Peterson29060642009-01-31 22:14:21 +00006048 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006049 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006050 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006051 message = "truncated \\UXXXXXXXX escape";
6052 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006053 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006054 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006055 ch <<= 4;
6056 if (c >= '0' && c <= '9') {
6057 ch += c - '0';
6058 }
6059 else if (c >= 'a' && c <= 'f') {
6060 ch += c - ('a' - 10);
6061 }
6062 else if (c >= 'A' && c <= 'F') {
6063 ch += c - ('A' - 10);
6064 }
6065 else {
6066 break;
6067 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006068 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006069 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006070 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006071 }
6072
6073 /* when we get here, ch is a 32-bit unicode character */
6074 if (ch > MAX_UNICODE) {
6075 message = "illegal Unicode character";
6076 goto error;
6077 }
6078
6079 WRITE_CHAR(ch);
6080 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006081
Benjamin Peterson29060642009-01-31 22:14:21 +00006082 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006083 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006084 if (ucnhash_CAPI == NULL) {
6085 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006086 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6087 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006088 if (ucnhash_CAPI == NULL) {
6089 PyErr_SetString(
6090 PyExc_UnicodeError,
6091 "\\N escapes not supported (can't load unicodedata module)"
6092 );
6093 goto onError;
6094 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006095 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006096
6097 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006098 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006099 const char *start = ++s;
6100 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006101 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006102 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006103 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006104 namelen = s - start;
6105 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006106 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006107 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006108 ch = 0xffffffff; /* in case 'getcode' messes up */
6109 if (namelen <= INT_MAX &&
6110 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6111 &ch, 0)) {
6112 assert(ch <= MAX_UNICODE);
6113 WRITE_CHAR(ch);
6114 continue;
6115 }
6116 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006117 }
6118 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006119 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006120
6121 default:
Eric V. Smith56466482016-10-31 14:46:26 -04006122 if (*first_invalid_escape == NULL) {
6123 *first_invalid_escape = s-1; /* Back up one char, since we've
6124 already incremented s. */
6125 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006126 WRITE_ASCII_CHAR('\\');
6127 WRITE_CHAR(c);
6128 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006129 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006130
6131 error:
6132 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006133 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006134 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006135 errors, &errorHandler,
6136 "unicodeescape", message,
6137 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006138 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006139 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006140 }
6141 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6142 goto onError;
6143 }
6144
6145#undef WRITE_ASCII_CHAR
6146#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006147 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006148
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006149 Py_XDECREF(errorHandler);
6150 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006151 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006152
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006154 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006155 Py_XDECREF(errorHandler);
6156 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006157 return NULL;
6158}
6159
Eric V. Smith56466482016-10-31 14:46:26 -04006160PyObject *
6161PyUnicode_DecodeUnicodeEscape(const char *s,
6162 Py_ssize_t size,
6163 const char *errors)
6164{
6165 const char *first_invalid_escape;
6166 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6167 &first_invalid_escape);
6168 if (result == NULL)
6169 return NULL;
6170 if (first_invalid_escape != NULL) {
6171 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6172 "invalid escape sequence '\\%c'",
6173 *first_invalid_escape) < 0) {
6174 Py_DECREF(result);
6175 return NULL;
6176 }
6177 }
6178 return result;
6179}
6180
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006181/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006182
Alexander Belopolsky40018472011-02-26 01:02:56 +00006183PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006184PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006185{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006186 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006187 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006189 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006190 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006191 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192
Ezio Melottie7f90372012-10-05 03:33:31 +03006193 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006194 escape.
6195
Ezio Melottie7f90372012-10-05 03:33:31 +03006196 For UCS1 strings it's '\xxx', 4 bytes per source character.
6197 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6198 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006199 */
6200
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006201 if (!PyUnicode_Check(unicode)) {
6202 PyErr_BadArgument();
6203 return NULL;
6204 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006205 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006206 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006207 }
Victor Stinner358af132015-10-12 22:36:57 +02006208
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006209 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006210 if (len == 0) {
6211 return PyBytes_FromStringAndSize(NULL, 0);
6212 }
6213
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006214 kind = PyUnicode_KIND(unicode);
6215 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006216 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6217 bytes, and 1 byte characters 4. */
6218 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006219 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006220 return PyErr_NoMemory();
6221 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006222 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006223 if (repr == NULL) {
6224 return NULL;
6225 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006226
Victor Stinner62ec3312016-09-06 17:04:34 -07006227 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006228 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006229 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006230
Victor Stinner62ec3312016-09-06 17:04:34 -07006231 /* U+0000-U+00ff range */
6232 if (ch < 0x100) {
6233 if (ch >= ' ' && ch < 127) {
6234 if (ch != '\\') {
6235 /* Copy printable US ASCII as-is */
6236 *p++ = (char) ch;
6237 }
6238 /* Escape backslashes */
6239 else {
6240 *p++ = '\\';
6241 *p++ = '\\';
6242 }
6243 }
Victor Stinner358af132015-10-12 22:36:57 +02006244
Victor Stinner62ec3312016-09-06 17:04:34 -07006245 /* Map special whitespace to '\t', \n', '\r' */
6246 else if (ch == '\t') {
6247 *p++ = '\\';
6248 *p++ = 't';
6249 }
6250 else if (ch == '\n') {
6251 *p++ = '\\';
6252 *p++ = 'n';
6253 }
6254 else if (ch == '\r') {
6255 *p++ = '\\';
6256 *p++ = 'r';
6257 }
6258
6259 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6260 else {
6261 *p++ = '\\';
6262 *p++ = 'x';
6263 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6264 *p++ = Py_hexdigits[ch & 0x000F];
6265 }
Tim Petersced69f82003-09-16 20:30:58 +00006266 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006267 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006268 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006269 *p++ = '\\';
6270 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006271 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6272 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6273 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6274 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006275 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006276 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6277 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006278
Victor Stinner62ec3312016-09-06 17:04:34 -07006279 /* Make sure that the first two digits are zero */
6280 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006281 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006282 *p++ = 'U';
6283 *p++ = '0';
6284 *p++ = '0';
6285 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6286 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6287 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6288 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6289 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6290 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006291 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006292 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006293
Victor Stinner62ec3312016-09-06 17:04:34 -07006294 assert(p - PyBytes_AS_STRING(repr) > 0);
6295 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6296 return NULL;
6297 }
6298 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006299}
6300
Alexander Belopolsky40018472011-02-26 01:02:56 +00006301PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006302PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6303 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006304{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006305 PyObject *result;
6306 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006307 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006308 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006309 }
6310
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006311 result = PyUnicode_AsUnicodeEscapeString(tmp);
6312 Py_DECREF(tmp);
6313 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314}
6315
6316/* --- Raw Unicode Escape Codec ------------------------------------------- */
6317
Alexander Belopolsky40018472011-02-26 01:02:56 +00006318PyObject *
6319PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006320 Py_ssize_t size,
6321 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006322{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006323 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006324 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006325 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006326 PyObject *errorHandler = NULL;
6327 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006328
Victor Stinner62ec3312016-09-06 17:04:34 -07006329 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006330 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006331 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006332
Guido van Rossumd57fd912000-03-10 22:53:23 +00006333 /* Escaped strings will always be longer than the resulting
6334 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006335 length after conversion to the true value. (But decoding error
6336 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006337 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006338 writer.min_length = size;
6339 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6340 goto onError;
6341 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006342
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343 end = s + size;
6344 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006345 unsigned char c = (unsigned char) *s++;
6346 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006347 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006348 Py_ssize_t startinpos;
6349 Py_ssize_t endinpos;
6350 const char *message;
6351
6352#define WRITE_CHAR(ch) \
6353 do { \
6354 if (ch <= writer.maxchar) { \
6355 assert(writer.pos < writer.size); \
6356 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6357 } \
6358 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6359 goto onError; \
6360 } \
6361 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006362
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006364 if (c != '\\' || s >= end) {
6365 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006366 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006367 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006368
Victor Stinner62ec3312016-09-06 17:04:34 -07006369 c = (unsigned char) *s++;
6370 if (c == 'u') {
6371 count = 4;
6372 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006373 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006374 else if (c == 'U') {
6375 count = 8;
6376 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006377 }
6378 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006379 assert(writer.pos < writer.size);
6380 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6381 WRITE_CHAR(c);
6382 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006383 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006384 startinpos = s - starts - 2;
6385
6386 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6387 for (ch = 0; count && s < end; ++s, --count) {
6388 c = (unsigned char)*s;
6389 ch <<= 4;
6390 if (c >= '0' && c <= '9') {
6391 ch += c - '0';
6392 }
6393 else if (c >= 'a' && c <= 'f') {
6394 ch += c - ('a' - 10);
6395 }
6396 else if (c >= 'A' && c <= 'F') {
6397 ch += c - ('A' - 10);
6398 }
6399 else {
6400 break;
6401 }
6402 }
6403 if (!count) {
6404 if (ch <= MAX_UNICODE) {
6405 WRITE_CHAR(ch);
6406 continue;
6407 }
6408 message = "\\Uxxxxxxxx out of range";
6409 }
6410
6411 endinpos = s-starts;
6412 writer.min_length = end - s + writer.pos;
6413 if (unicode_decode_call_errorhandler_writer(
6414 errors, &errorHandler,
6415 "rawunicodeescape", message,
6416 &starts, &end, &startinpos, &endinpos, &exc, &s,
6417 &writer)) {
6418 goto onError;
6419 }
6420 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6421 goto onError;
6422 }
6423
6424#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006425 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426 Py_XDECREF(errorHandler);
6427 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006428 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006429
Benjamin Peterson29060642009-01-31 22:14:21 +00006430 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006431 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006432 Py_XDECREF(errorHandler);
6433 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006434 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006435
Guido van Rossumd57fd912000-03-10 22:53:23 +00006436}
6437
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006438
Alexander Belopolsky40018472011-02-26 01:02:56 +00006439PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006440PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006441{
Victor Stinner62ec3312016-09-06 17:04:34 -07006442 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006443 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006444 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006445 int kind;
6446 void *data;
6447 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006448
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006449 if (!PyUnicode_Check(unicode)) {
6450 PyErr_BadArgument();
6451 return NULL;
6452 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006453 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006454 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006455 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006456 kind = PyUnicode_KIND(unicode);
6457 data = PyUnicode_DATA(unicode);
6458 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006459 if (kind == PyUnicode_1BYTE_KIND) {
6460 return PyBytes_FromStringAndSize(data, len);
6461 }
Victor Stinner0e368262011-11-10 20:12:49 +01006462
Victor Stinner62ec3312016-09-06 17:04:34 -07006463 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6464 bytes, and 1 byte characters 4. */
6465 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006466
Victor Stinner62ec3312016-09-06 17:04:34 -07006467 if (len > PY_SSIZE_T_MAX / expandsize) {
6468 return PyErr_NoMemory();
6469 }
6470 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6471 if (repr == NULL) {
6472 return NULL;
6473 }
6474 if (len == 0) {
6475 return repr;
6476 }
6477
6478 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006479 for (pos = 0; pos < len; pos++) {
6480 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006481
Victor Stinner62ec3312016-09-06 17:04:34 -07006482 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6483 if (ch < 0x100) {
6484 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006485 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006486 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6487 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006488 *p++ = '\\';
6489 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006490 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6491 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6492 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6493 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006494 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006495 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6496 else {
6497 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6498 *p++ = '\\';
6499 *p++ = 'U';
6500 *p++ = '0';
6501 *p++ = '0';
6502 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6503 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6504 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6505 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6506 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6507 *p++ = Py_hexdigits[ch & 15];
6508 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006509 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006510
Victor Stinner62ec3312016-09-06 17:04:34 -07006511 assert(p > PyBytes_AS_STRING(repr));
6512 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6513 return NULL;
6514 }
6515 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006516}
6517
Alexander Belopolsky40018472011-02-26 01:02:56 +00006518PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006519PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6520 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006521{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006522 PyObject *result;
6523 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6524 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006525 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006526 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6527 Py_DECREF(tmp);
6528 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006529}
6530
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006531/* --- Unicode Internal Codec ------------------------------------------- */
6532
Alexander Belopolsky40018472011-02-26 01:02:56 +00006533PyObject *
6534_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006535 Py_ssize_t size,
6536 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006537{
6538 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006539 Py_ssize_t startinpos;
6540 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006541 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006542 const char *end;
6543 const char *reason;
6544 PyObject *errorHandler = NULL;
6545 PyObject *exc = NULL;
6546
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006547 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006548 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006549 1))
6550 return NULL;
6551
Serhiy Storchaka82a90752017-07-11 07:27:56 +03006552 if (size < 0) {
6553 PyErr_BadInternalCall();
6554 return NULL;
6555 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006556 if (size == 0)
6557 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006558
Victor Stinner8f674cc2013-04-17 23:02:17 +02006559 _PyUnicodeWriter_Init(&writer);
6560 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6561 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006562 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006563 }
6564 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006565
Victor Stinner8f674cc2013-04-17 23:02:17 +02006566 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006567 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006568 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006569 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006570 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006571 endinpos = end-starts;
6572 reason = "truncated input";
6573 goto error;
6574 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006575 /* We copy the raw representation one byte at a time because the
6576 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006577 ((char *) &uch)[0] = s[0];
6578 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006579#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006580 ((char *) &uch)[2] = s[2];
6581 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006582#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006583 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006584#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006585 /* We have to sanity check the raw data, otherwise doom looms for
6586 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006587 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006588 endinpos = s - starts + Py_UNICODE_SIZE;
6589 reason = "illegal code point (> 0x10FFFF)";
6590 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006591 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006592#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006593 s += Py_UNICODE_SIZE;
6594#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006595 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006596 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006597 Py_UNICODE uch2;
6598 ((char *) &uch2)[0] = s[0];
6599 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006600 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006601 {
Victor Stinner551ac952011-11-29 22:58:13 +01006602 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006603 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006604 }
6605 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006606#endif
6607
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006608 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006609 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006610 continue;
6611
6612 error:
6613 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006614 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006615 errors, &errorHandler,
6616 "unicode_internal", reason,
6617 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006618 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006619 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006620 }
6621
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006622 Py_XDECREF(errorHandler);
6623 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006624 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006625
Benjamin Peterson29060642009-01-31 22:14:21 +00006626 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006627 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006628 Py_XDECREF(errorHandler);
6629 Py_XDECREF(exc);
6630 return NULL;
6631}
6632
Guido van Rossumd57fd912000-03-10 22:53:23 +00006633/* --- Latin-1 Codec ------------------------------------------------------ */
6634
Alexander Belopolsky40018472011-02-26 01:02:56 +00006635PyObject *
6636PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006637 Py_ssize_t size,
6638 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006639{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006640 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006641 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006642}
6643
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006645static void
6646make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006647 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006648 PyObject *unicode,
6649 Py_ssize_t startpos, Py_ssize_t endpos,
6650 const char *reason)
6651{
6652 if (*exceptionObject == NULL) {
6653 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006654 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006655 encoding, unicode, startpos, endpos, reason);
6656 }
6657 else {
6658 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6659 goto onError;
6660 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6661 goto onError;
6662 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6663 goto onError;
6664 return;
6665 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006666 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006667 }
6668}
6669
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006670/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006671static void
6672raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006673 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006674 PyObject *unicode,
6675 Py_ssize_t startpos, Py_ssize_t endpos,
6676 const char *reason)
6677{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006678 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006679 encoding, unicode, startpos, endpos, reason);
6680 if (*exceptionObject != NULL)
6681 PyCodec_StrictErrors(*exceptionObject);
6682}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006683
6684/* error handling callback helper:
6685 build arguments, call the callback and check the arguments,
6686 put the result into newpos and return the replacement string, which
6687 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006688static PyObject *
6689unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006690 PyObject **errorHandler,
6691 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006692 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006693 Py_ssize_t startpos, Py_ssize_t endpos,
6694 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006695{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006696 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006697 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006698 PyObject *restuple;
6699 PyObject *resunicode;
6700
6701 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006702 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006703 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006704 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006705 }
6706
Benjamin Petersonbac79492012-01-14 13:34:47 -05006707 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006708 return NULL;
6709 len = PyUnicode_GET_LENGTH(unicode);
6710
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006711 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006712 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006713 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006714 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006715
6716 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006717 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006718 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006719 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006720 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006721 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 Py_DECREF(restuple);
6723 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006724 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006725 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 &resunicode, newpos)) {
6727 Py_DECREF(restuple);
6728 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006729 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006730 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6731 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6732 Py_DECREF(restuple);
6733 return NULL;
6734 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006735 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006736 *newpos = len + *newpos;
6737 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006738 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 Py_DECREF(restuple);
6740 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006741 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006742 Py_INCREF(resunicode);
6743 Py_DECREF(restuple);
6744 return resunicode;
6745}
6746
Alexander Belopolsky40018472011-02-26 01:02:56 +00006747static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006748unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006749 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006750 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006751{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006752 /* input state */
6753 Py_ssize_t pos=0, size;
6754 int kind;
6755 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006756 /* pointer into the output */
6757 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006758 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6759 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006760 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006761 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006762 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006763 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006764 /* output object */
6765 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006766
Benjamin Petersonbac79492012-01-14 13:34:47 -05006767 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006768 return NULL;
6769 size = PyUnicode_GET_LENGTH(unicode);
6770 kind = PyUnicode_KIND(unicode);
6771 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006772 /* allocate enough for a simple encoding without
6773 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006774 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006775 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006776
6777 _PyBytesWriter_Init(&writer);
6778 str = _PyBytesWriter_Alloc(&writer, size);
6779 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006780 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006781
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006782 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006783 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006784
Benjamin Peterson29060642009-01-31 22:14:21 +00006785 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006786 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006787 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006788 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006789 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006790 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006791 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006792 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006794 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006795 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006797
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006798 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006799 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006800
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006801 /* Only overallocate the buffer if it's not the last write */
6802 writer.overallocate = (collend < size);
6803
Benjamin Peterson29060642009-01-31 22:14:21 +00006804 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006805 if (error_handler == _Py_ERROR_UNKNOWN)
6806 error_handler = get_error_handler(errors);
6807
6808 switch (error_handler) {
6809 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006810 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006811 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006812
6813 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006814 memset(str, '?', collend - collstart);
6815 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006816 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006817 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006818 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006819 break;
Victor Stinner50149202015-09-22 00:26:54 +02006820
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006821 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006822 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006823 writer.min_size -= (collend - collstart);
6824 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006825 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006826 if (str == NULL)
6827 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006828 pos = collend;
6829 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006830
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006831 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006832 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006833 writer.min_size -= (collend - collstart);
6834 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006835 unicode, collstart, collend);
6836 if (str == NULL)
6837 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006838 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006839 break;
Victor Stinner50149202015-09-22 00:26:54 +02006840
Victor Stinnerc3713e92015-09-29 12:32:13 +02006841 case _Py_ERROR_SURROGATEESCAPE:
6842 for (i = collstart; i < collend; ++i) {
6843 ch = PyUnicode_READ(kind, data, i);
6844 if (ch < 0xdc80 || 0xdcff < ch) {
6845 /* Not a UTF-8b surrogate */
6846 break;
6847 }
6848 *str++ = (char)(ch - 0xdc00);
6849 ++pos;
6850 }
6851 if (i >= collend)
6852 break;
6853 collstart = pos;
6854 assert(collstart != collend);
6855 /* fallback to general error handling */
6856
Benjamin Peterson29060642009-01-31 22:14:21 +00006857 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006858 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6859 encoding, reason, unicode, &exc,
6860 collstart, collend, &newpos);
6861 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006862 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006863
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006864 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006865 writer.min_size -= 1;
6866
Victor Stinner6bd525b2015-10-09 13:10:05 +02006867 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006868 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006869 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006870 PyBytes_AS_STRING(rep),
6871 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006872 if (str == NULL)
6873 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006874 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006875 else {
6876 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006877
Victor Stinner6bd525b2015-10-09 13:10:05 +02006878 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006879 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006880
6881 if (PyUnicode_IS_ASCII(rep)) {
6882 /* Fast path: all characters are smaller than limit */
6883 assert(limit >= 128);
6884 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6885 str = _PyBytesWriter_WriteBytes(&writer, str,
6886 PyUnicode_DATA(rep),
6887 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006888 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006889 else {
6890 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6891
6892 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6893 if (str == NULL)
6894 goto onError;
6895
6896 /* check if there is anything unencodable in the
6897 replacement and copy it to the output */
6898 for (i = 0; repsize-->0; ++i, ++str) {
6899 ch = PyUnicode_READ_CHAR(rep, i);
6900 if (ch >= limit) {
6901 raise_encode_exception(&exc, encoding, unicode,
6902 pos, pos+1, reason);
6903 goto onError;
6904 }
6905 *str = (char)ch;
6906 }
6907 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006908 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006909 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006910 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006911 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006912
6913 /* If overallocation was disabled, ensure that it was the last
6914 write. Otherwise, we missed an optimization */
6915 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006916 }
6917 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006918
Victor Stinner50149202015-09-22 00:26:54 +02006919 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006920 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006921 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006922
6923 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006924 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006925 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006926 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006927 Py_XDECREF(exc);
6928 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006929}
6930
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006931/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006932PyObject *
6933PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006934 Py_ssize_t size,
6935 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006936{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006937 PyObject *result;
6938 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6939 if (unicode == NULL)
6940 return NULL;
6941 result = unicode_encode_ucs1(unicode, errors, 256);
6942 Py_DECREF(unicode);
6943 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006944}
6945
Alexander Belopolsky40018472011-02-26 01:02:56 +00006946PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006947_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006948{
6949 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006950 PyErr_BadArgument();
6951 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006953 if (PyUnicode_READY(unicode) == -1)
6954 return NULL;
6955 /* Fast path: if it is a one-byte string, construct
6956 bytes object directly. */
6957 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6958 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6959 PyUnicode_GET_LENGTH(unicode));
6960 /* Non-Latin-1 characters present. Defer to above function to
6961 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006962 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006963}
6964
6965PyObject*
6966PyUnicode_AsLatin1String(PyObject *unicode)
6967{
6968 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006969}
6970
6971/* --- 7-bit ASCII Codec -------------------------------------------------- */
6972
Alexander Belopolsky40018472011-02-26 01:02:56 +00006973PyObject *
6974PyUnicode_DecodeASCII(const char *s,
6975 Py_ssize_t size,
6976 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006977{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006978 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006979 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006980 int kind;
6981 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006982 Py_ssize_t startinpos;
6983 Py_ssize_t endinpos;
6984 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006985 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006986 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006987 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006988 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006989
Guido van Rossumd57fd912000-03-10 22:53:23 +00006990 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006991 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006992
Guido van Rossumd57fd912000-03-10 22:53:23 +00006993 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006994 if (size == 1 && (unsigned char)s[0] < 128)
6995 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006996
Victor Stinner8f674cc2013-04-17 23:02:17 +02006997 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006998 writer.min_length = size;
6999 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02007000 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007001
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007002 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007003 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007004 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007005 writer.pos = outpos;
7006 if (writer.pos == size)
7007 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007008
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007009 s += writer.pos;
7010 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007011 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02007012 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00007013 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007014 PyUnicode_WRITE(kind, data, writer.pos, c);
7015 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007016 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007017 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00007018 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007019
7020 /* byte outsize range 0x00..0x7f: call the error handler */
7021
7022 if (error_handler == _Py_ERROR_UNKNOWN)
7023 error_handler = get_error_handler(errors);
7024
7025 switch (error_handler)
7026 {
7027 case _Py_ERROR_REPLACE:
7028 case _Py_ERROR_SURROGATEESCAPE:
7029 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02007030 but we may switch to UCS2 at the first write */
7031 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7032 goto onError;
7033 kind = writer.kind;
7034 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007035
7036 if (error_handler == _Py_ERROR_REPLACE)
7037 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7038 else
7039 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7040 writer.pos++;
7041 ++s;
7042 break;
7043
7044 case _Py_ERROR_IGNORE:
7045 ++s;
7046 break;
7047
7048 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007049 startinpos = s-starts;
7050 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007051 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007052 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007053 "ascii", "ordinal not in range(128)",
7054 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007055 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007056 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007057 kind = writer.kind;
7058 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007059 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007060 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007061 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007062 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007063 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007064
Benjamin Peterson29060642009-01-31 22:14:21 +00007065 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007066 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007067 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007068 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007069 return NULL;
7070}
7071
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007072/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007073PyObject *
7074PyUnicode_EncodeASCII(const Py_UNICODE *p,
7075 Py_ssize_t size,
7076 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007077{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007078 PyObject *result;
7079 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7080 if (unicode == NULL)
7081 return NULL;
7082 result = unicode_encode_ucs1(unicode, errors, 128);
7083 Py_DECREF(unicode);
7084 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007085}
7086
Alexander Belopolsky40018472011-02-26 01:02:56 +00007087PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007088_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007089{
7090 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007091 PyErr_BadArgument();
7092 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007093 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007094 if (PyUnicode_READY(unicode) == -1)
7095 return NULL;
7096 /* Fast path: if it is an ASCII-only string, construct bytes object
7097 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007098 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007099 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7100 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007101 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007102}
7103
7104PyObject *
7105PyUnicode_AsASCIIString(PyObject *unicode)
7106{
7107 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007108}
7109
Steve Dowercc16be82016-09-08 10:35:16 -07007110#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007111
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007112/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007113
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007114#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007115#define NEED_RETRY
7116#endif
7117
Victor Stinner3a50e702011-10-18 21:21:00 +02007118#ifndef WC_ERR_INVALID_CHARS
7119# define WC_ERR_INVALID_CHARS 0x0080
7120#endif
7121
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007122static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007123code_page_name(UINT code_page, PyObject **obj)
7124{
7125 *obj = NULL;
7126 if (code_page == CP_ACP)
7127 return "mbcs";
7128 if (code_page == CP_UTF7)
7129 return "CP_UTF7";
7130 if (code_page == CP_UTF8)
7131 return "CP_UTF8";
7132
7133 *obj = PyBytes_FromFormat("cp%u", code_page);
7134 if (*obj == NULL)
7135 return NULL;
7136 return PyBytes_AS_STRING(*obj);
7137}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007138
Victor Stinner3a50e702011-10-18 21:21:00 +02007139static DWORD
7140decode_code_page_flags(UINT code_page)
7141{
7142 if (code_page == CP_UTF7) {
7143 /* The CP_UTF7 decoder only supports flags=0 */
7144 return 0;
7145 }
7146 else
7147 return MB_ERR_INVALID_CHARS;
7148}
7149
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007150/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007151 * Decode a byte string from a Windows code page into unicode object in strict
7152 * mode.
7153 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007154 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7155 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007156 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007157static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007158decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007159 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007160 const char *in,
7161 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007162{
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007164 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007165 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007166
7167 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007168 assert(insize > 0);
7169 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7170 if (outsize <= 0)
7171 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007172
7173 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007174 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007175 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007176 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007177 if (*v == NULL)
7178 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007180 }
7181 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007182 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007183 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007184 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007185 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007186 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007187 }
7188
7189 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007190 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7191 if (outsize <= 0)
7192 goto error;
7193 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007194
Victor Stinner3a50e702011-10-18 21:21:00 +02007195error:
7196 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7197 return -2;
7198 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007199 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007200}
7201
Victor Stinner3a50e702011-10-18 21:21:00 +02007202/*
7203 * Decode a byte string from a code page into unicode object with an error
7204 * handler.
7205 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007206 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 * UnicodeDecodeError exception and returns -1 on error.
7208 */
7209static int
7210decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007211 PyObject **v,
7212 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007213 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007214{
7215 const char *startin = in;
7216 const char *endin = in + size;
7217 const DWORD flags = decode_code_page_flags(code_page);
7218 /* Ideally, we should get reason from FormatMessage. This is the Windows
7219 2000 English version of the message. */
7220 const char *reason = "No mapping for the Unicode character exists "
7221 "in the target code page.";
7222 /* each step cannot decode more than 1 character, but a character can be
7223 represented as a surrogate pair */
7224 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007225 int insize;
7226 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 PyObject *errorHandler = NULL;
7228 PyObject *exc = NULL;
7229 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007230 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 DWORD err;
7232 int ret = -1;
7233
7234 assert(size > 0);
7235
7236 encoding = code_page_name(code_page, &encoding_obj);
7237 if (encoding == NULL)
7238 return -1;
7239
Victor Stinner7d00cc12014-03-17 23:08:06 +01007240 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7242 UnicodeDecodeError. */
7243 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7244 if (exc != NULL) {
7245 PyCodec_StrictErrors(exc);
7246 Py_CLEAR(exc);
7247 }
7248 goto error;
7249 }
7250
7251 if (*v == NULL) {
7252 /* Create unicode object */
7253 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7254 PyErr_NoMemory();
7255 goto error;
7256 }
Victor Stinnerab595942011-12-17 04:59:06 +01007257 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007258 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 if (*v == NULL)
7260 goto error;
7261 startout = PyUnicode_AS_UNICODE(*v);
7262 }
7263 else {
7264 /* Extend unicode object */
7265 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7266 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7267 PyErr_NoMemory();
7268 goto error;
7269 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007270 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007271 goto error;
7272 startout = PyUnicode_AS_UNICODE(*v) + n;
7273 }
7274
7275 /* Decode the byte string character per character */
7276 out = startout;
7277 while (in < endin)
7278 {
7279 /* Decode a character */
7280 insize = 1;
7281 do
7282 {
7283 outsize = MultiByteToWideChar(code_page, flags,
7284 in, insize,
7285 buffer, Py_ARRAY_LENGTH(buffer));
7286 if (outsize > 0)
7287 break;
7288 err = GetLastError();
7289 if (err != ERROR_NO_UNICODE_TRANSLATION
7290 && err != ERROR_INSUFFICIENT_BUFFER)
7291 {
7292 PyErr_SetFromWindowsErr(0);
7293 goto error;
7294 }
7295 insize++;
7296 }
7297 /* 4=maximum length of a UTF-8 sequence */
7298 while (insize <= 4 && (in + insize) <= endin);
7299
7300 if (outsize <= 0) {
7301 Py_ssize_t startinpos, endinpos, outpos;
7302
Victor Stinner7d00cc12014-03-17 23:08:06 +01007303 /* last character in partial decode? */
7304 if (in + insize >= endin && !final)
7305 break;
7306
Victor Stinner3a50e702011-10-18 21:21:00 +02007307 startinpos = in - startin;
7308 endinpos = startinpos + 1;
7309 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007310 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007311 errors, &errorHandler,
7312 encoding, reason,
7313 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007314 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007315 {
7316 goto error;
7317 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007318 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007319 }
7320 else {
7321 in += insize;
7322 memcpy(out, buffer, outsize * sizeof(wchar_t));
7323 out += outsize;
7324 }
7325 }
7326
7327 /* write a NUL character at the end */
7328 *out = 0;
7329
7330 /* Extend unicode object */
7331 outsize = out - startout;
7332 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007333 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007334 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007335 /* (in - startin) <= size and size is an int */
7336 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007337
7338error:
7339 Py_XDECREF(encoding_obj);
7340 Py_XDECREF(errorHandler);
7341 Py_XDECREF(exc);
7342 return ret;
7343}
7344
Victor Stinner3a50e702011-10-18 21:21:00 +02007345static PyObject *
7346decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007347 const char *s, Py_ssize_t size,
7348 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007349{
Victor Stinner76a31a62011-11-04 00:05:13 +01007350 PyObject *v = NULL;
7351 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007352
Victor Stinner3a50e702011-10-18 21:21:00 +02007353 if (code_page < 0) {
7354 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7355 return NULL;
7356 }
Serhiy Storchaka82a90752017-07-11 07:27:56 +03007357 if (size < 0) {
7358 PyErr_BadInternalCall();
7359 return NULL;
7360 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007361
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007362 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007363 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007364
Victor Stinner76a31a62011-11-04 00:05:13 +01007365 do
7366 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007367#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007368 if (size > INT_MAX) {
7369 chunk_size = INT_MAX;
7370 final = 0;
7371 done = 0;
7372 }
7373 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007374#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007375 {
7376 chunk_size = (int)size;
7377 final = (consumed == NULL);
7378 done = 1;
7379 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007380
Victor Stinner76a31a62011-11-04 00:05:13 +01007381 if (chunk_size == 0 && done) {
7382 if (v != NULL)
7383 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007384 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007385 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007386
Victor Stinner76a31a62011-11-04 00:05:13 +01007387 converted = decode_code_page_strict(code_page, &v,
7388 s, chunk_size);
7389 if (converted == -2)
7390 converted = decode_code_page_errors(code_page, &v,
7391 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007392 errors, final);
7393 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007394
7395 if (converted < 0) {
7396 Py_XDECREF(v);
7397 return NULL;
7398 }
7399
7400 if (consumed)
7401 *consumed += converted;
7402
7403 s += converted;
7404 size -= converted;
7405 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007406
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007407 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007408}
7409
Alexander Belopolsky40018472011-02-26 01:02:56 +00007410PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007411PyUnicode_DecodeCodePageStateful(int code_page,
7412 const char *s,
7413 Py_ssize_t size,
7414 const char *errors,
7415 Py_ssize_t *consumed)
7416{
7417 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7418}
7419
7420PyObject *
7421PyUnicode_DecodeMBCSStateful(const char *s,
7422 Py_ssize_t size,
7423 const char *errors,
7424 Py_ssize_t *consumed)
7425{
7426 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7427}
7428
7429PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007430PyUnicode_DecodeMBCS(const char *s,
7431 Py_ssize_t size,
7432 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007433{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007434 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7435}
7436
Victor Stinner3a50e702011-10-18 21:21:00 +02007437static DWORD
7438encode_code_page_flags(UINT code_page, const char *errors)
7439{
7440 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007441 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007442 }
7443 else if (code_page == CP_UTF7) {
7444 /* CP_UTF7 only supports flags=0 */
7445 return 0;
7446 }
7447 else {
7448 if (errors != NULL && strcmp(errors, "replace") == 0)
7449 return 0;
7450 else
7451 return WC_NO_BEST_FIT_CHARS;
7452 }
7453}
7454
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007455/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 * Encode a Unicode string to a Windows code page into a byte string in strict
7457 * mode.
7458 *
7459 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007460 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007461 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007462static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007463encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007464 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007465 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007466{
Victor Stinner554f3f02010-06-16 23:33:54 +00007467 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007468 BOOL *pusedDefaultChar = &usedDefaultChar;
7469 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007470 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007471 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007472 const DWORD flags = encode_code_page_flags(code_page, NULL);
7473 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007474 /* Create a substring so that we can get the UTF-16 representation
7475 of just the slice under consideration. */
7476 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007477
Martin v. Löwis3d325192011-11-04 18:23:06 +01007478 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007479
Victor Stinner3a50e702011-10-18 21:21:00 +02007480 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007481 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007482 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007483 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007484
Victor Stinner2fc507f2011-11-04 20:06:39 +01007485 substring = PyUnicode_Substring(unicode, offset, offset+len);
7486 if (substring == NULL)
7487 return -1;
7488 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7489 if (p == NULL) {
7490 Py_DECREF(substring);
7491 return -1;
7492 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007493 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007494
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007495 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007496 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007497 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007498 NULL, 0,
7499 NULL, pusedDefaultChar);
7500 if (outsize <= 0)
7501 goto error;
7502 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007503 if (pusedDefaultChar && *pusedDefaultChar) {
7504 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007506 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007507
Victor Stinner3a50e702011-10-18 21:21:00 +02007508 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007509 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007510 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007511 if (*outbytes == NULL) {
7512 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007513 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007514 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007515 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007516 }
7517 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007518 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007519 const Py_ssize_t n = PyBytes_Size(*outbytes);
7520 if (outsize > PY_SSIZE_T_MAX - n) {
7521 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007522 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007523 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007524 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007525 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7526 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007527 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007528 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007529 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007530 }
7531
7532 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007533 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007534 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007535 out, outsize,
7536 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007537 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007538 if (outsize <= 0)
7539 goto error;
7540 if (pusedDefaultChar && *pusedDefaultChar)
7541 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007542 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007543
Victor Stinner3a50e702011-10-18 21:21:00 +02007544error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007545 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007546 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7547 return -2;
7548 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007549 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007550}
7551
Victor Stinner3a50e702011-10-18 21:21:00 +02007552/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007553 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007554 * error handler.
7555 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007556 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007557 * -1 on other error.
7558 */
7559static int
7560encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007561 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007562 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007563{
Victor Stinner3a50e702011-10-18 21:21:00 +02007564 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007565 Py_ssize_t pos = unicode_offset;
7566 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007567 /* Ideally, we should get reason from FormatMessage. This is the Windows
7568 2000 English version of the message. */
7569 const char *reason = "invalid character";
7570 /* 4=maximum length of a UTF-8 sequence */
7571 char buffer[4];
7572 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7573 Py_ssize_t outsize;
7574 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007575 PyObject *errorHandler = NULL;
7576 PyObject *exc = NULL;
7577 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007578 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007579 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007580 PyObject *rep;
7581 int ret = -1;
7582
7583 assert(insize > 0);
7584
7585 encoding = code_page_name(code_page, &encoding_obj);
7586 if (encoding == NULL)
7587 return -1;
7588
7589 if (errors == NULL || strcmp(errors, "strict") == 0) {
7590 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7591 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007592 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007593 if (exc != NULL) {
7594 PyCodec_StrictErrors(exc);
7595 Py_DECREF(exc);
7596 }
7597 Py_XDECREF(encoding_obj);
7598 return -1;
7599 }
7600
7601 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7602 pusedDefaultChar = &usedDefaultChar;
7603 else
7604 pusedDefaultChar = NULL;
7605
7606 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7607 PyErr_NoMemory();
7608 goto error;
7609 }
7610 outsize = insize * Py_ARRAY_LENGTH(buffer);
7611
7612 if (*outbytes == NULL) {
7613 /* Create string object */
7614 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7615 if (*outbytes == NULL)
7616 goto error;
7617 out = PyBytes_AS_STRING(*outbytes);
7618 }
7619 else {
7620 /* Extend string object */
7621 Py_ssize_t n = PyBytes_Size(*outbytes);
7622 if (n > PY_SSIZE_T_MAX - outsize) {
7623 PyErr_NoMemory();
7624 goto error;
7625 }
7626 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7627 goto error;
7628 out = PyBytes_AS_STRING(*outbytes) + n;
7629 }
7630
7631 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007632 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007633 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007634 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7635 wchar_t chars[2];
7636 int charsize;
7637 if (ch < 0x10000) {
7638 chars[0] = (wchar_t)ch;
7639 charsize = 1;
7640 }
7641 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007642 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7643 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007644 charsize = 2;
7645 }
7646
Victor Stinner3a50e702011-10-18 21:21:00 +02007647 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007648 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007649 buffer, Py_ARRAY_LENGTH(buffer),
7650 NULL, pusedDefaultChar);
7651 if (outsize > 0) {
7652 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7653 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007654 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007655 memcpy(out, buffer, outsize);
7656 out += outsize;
7657 continue;
7658 }
7659 }
7660 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7661 PyErr_SetFromWindowsErr(0);
7662 goto error;
7663 }
7664
Victor Stinner3a50e702011-10-18 21:21:00 +02007665 rep = unicode_encode_call_errorhandler(
7666 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007667 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007668 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007669 if (rep == NULL)
7670 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007671 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007672
7673 if (PyBytes_Check(rep)) {
7674 outsize = PyBytes_GET_SIZE(rep);
7675 if (outsize != 1) {
7676 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7677 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7678 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7679 Py_DECREF(rep);
7680 goto error;
7681 }
7682 out = PyBytes_AS_STRING(*outbytes) + offset;
7683 }
7684 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7685 out += outsize;
7686 }
7687 else {
7688 Py_ssize_t i;
7689 enum PyUnicode_Kind kind;
7690 void *data;
7691
Benjamin Petersonbac79492012-01-14 13:34:47 -05007692 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007693 Py_DECREF(rep);
7694 goto error;
7695 }
7696
7697 outsize = PyUnicode_GET_LENGTH(rep);
7698 if (outsize != 1) {
7699 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7700 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7701 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7702 Py_DECREF(rep);
7703 goto error;
7704 }
7705 out = PyBytes_AS_STRING(*outbytes) + offset;
7706 }
7707 kind = PyUnicode_KIND(rep);
7708 data = PyUnicode_DATA(rep);
7709 for (i=0; i < outsize; i++) {
7710 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7711 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007712 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007713 encoding, unicode,
7714 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007715 "unable to encode error handler result to ASCII");
7716 Py_DECREF(rep);
7717 goto error;
7718 }
7719 *out = (unsigned char)ch;
7720 out++;
7721 }
7722 }
7723 Py_DECREF(rep);
7724 }
7725 /* write a NUL byte */
7726 *out = 0;
7727 outsize = out - PyBytes_AS_STRING(*outbytes);
7728 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7729 if (_PyBytes_Resize(outbytes, outsize) < 0)
7730 goto error;
7731 ret = 0;
7732
7733error:
7734 Py_XDECREF(encoding_obj);
7735 Py_XDECREF(errorHandler);
7736 Py_XDECREF(exc);
7737 return ret;
7738}
7739
Victor Stinner3a50e702011-10-18 21:21:00 +02007740static PyObject *
7741encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007742 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007743 const char *errors)
7744{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007745 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007746 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007747 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007748 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007749
Victor Stinner29dacf22015-01-26 16:41:32 +01007750 if (!PyUnicode_Check(unicode)) {
7751 PyErr_BadArgument();
7752 return NULL;
7753 }
7754
Benjamin Petersonbac79492012-01-14 13:34:47 -05007755 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007756 return NULL;
7757 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007758
Victor Stinner3a50e702011-10-18 21:21:00 +02007759 if (code_page < 0) {
7760 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7761 return NULL;
7762 }
7763
Martin v. Löwis3d325192011-11-04 18:23:06 +01007764 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007765 return PyBytes_FromStringAndSize(NULL, 0);
7766
Victor Stinner7581cef2011-11-03 22:32:33 +01007767 offset = 0;
7768 do
7769 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007770#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007771 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007772 chunks. */
7773 if (len > INT_MAX/2) {
7774 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007775 done = 0;
7776 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007777 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007778#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007779 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007780 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007781 done = 1;
7782 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007783
Victor Stinner76a31a62011-11-04 00:05:13 +01007784 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007785 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007786 errors);
7787 if (ret == -2)
7788 ret = encode_code_page_errors(code_page, &outbytes,
7789 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007790 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007791 if (ret < 0) {
7792 Py_XDECREF(outbytes);
7793 return NULL;
7794 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007795
Victor Stinner7581cef2011-11-03 22:32:33 +01007796 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007797 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007798 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007799
Victor Stinner3a50e702011-10-18 21:21:00 +02007800 return outbytes;
7801}
7802
7803PyObject *
7804PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7805 Py_ssize_t size,
7806 const char *errors)
7807{
Victor Stinner7581cef2011-11-03 22:32:33 +01007808 PyObject *unicode, *res;
7809 unicode = PyUnicode_FromUnicode(p, size);
7810 if (unicode == NULL)
7811 return NULL;
7812 res = encode_code_page(CP_ACP, unicode, errors);
7813 Py_DECREF(unicode);
7814 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007815}
7816
7817PyObject *
7818PyUnicode_EncodeCodePage(int code_page,
7819 PyObject *unicode,
7820 const char *errors)
7821{
Victor Stinner7581cef2011-11-03 22:32:33 +01007822 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007823}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007824
Alexander Belopolsky40018472011-02-26 01:02:56 +00007825PyObject *
7826PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007827{
Victor Stinner7581cef2011-11-03 22:32:33 +01007828 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007829}
7830
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007831#undef NEED_RETRY
7832
Steve Dowercc16be82016-09-08 10:35:16 -07007833#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007834
Guido van Rossumd57fd912000-03-10 22:53:23 +00007835/* --- Character Mapping Codec -------------------------------------------- */
7836
Victor Stinnerfb161b12013-04-18 01:44:27 +02007837static int
7838charmap_decode_string(const char *s,
7839 Py_ssize_t size,
7840 PyObject *mapping,
7841 const char *errors,
7842 _PyUnicodeWriter *writer)
7843{
7844 const char *starts = s;
7845 const char *e;
7846 Py_ssize_t startinpos, endinpos;
7847 PyObject *errorHandler = NULL, *exc = NULL;
7848 Py_ssize_t maplen;
7849 enum PyUnicode_Kind mapkind;
7850 void *mapdata;
7851 Py_UCS4 x;
7852 unsigned char ch;
7853
7854 if (PyUnicode_READY(mapping) == -1)
7855 return -1;
7856
7857 maplen = PyUnicode_GET_LENGTH(mapping);
7858 mapdata = PyUnicode_DATA(mapping);
7859 mapkind = PyUnicode_KIND(mapping);
7860
7861 e = s + size;
7862
7863 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7864 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7865 * is disabled in encoding aliases, latin1 is preferred because
7866 * its implementation is faster. */
7867 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7868 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7869 Py_UCS4 maxchar = writer->maxchar;
7870
7871 assert (writer->kind == PyUnicode_1BYTE_KIND);
7872 while (s < e) {
7873 ch = *s;
7874 x = mapdata_ucs1[ch];
7875 if (x > maxchar) {
7876 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7877 goto onError;
7878 maxchar = writer->maxchar;
7879 outdata = (Py_UCS1 *)writer->data;
7880 }
7881 outdata[writer->pos] = x;
7882 writer->pos++;
7883 ++s;
7884 }
7885 return 0;
7886 }
7887
7888 while (s < e) {
7889 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7890 enum PyUnicode_Kind outkind = writer->kind;
7891 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7892 if (outkind == PyUnicode_1BYTE_KIND) {
7893 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7894 Py_UCS4 maxchar = writer->maxchar;
7895 while (s < e) {
7896 ch = *s;
7897 x = mapdata_ucs2[ch];
7898 if (x > maxchar)
7899 goto Error;
7900 outdata[writer->pos] = x;
7901 writer->pos++;
7902 ++s;
7903 }
7904 break;
7905 }
7906 else if (outkind == PyUnicode_2BYTE_KIND) {
7907 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7908 while (s < e) {
7909 ch = *s;
7910 x = mapdata_ucs2[ch];
7911 if (x == 0xFFFE)
7912 goto Error;
7913 outdata[writer->pos] = x;
7914 writer->pos++;
7915 ++s;
7916 }
7917 break;
7918 }
7919 }
7920 ch = *s;
7921
7922 if (ch < maplen)
7923 x = PyUnicode_READ(mapkind, mapdata, ch);
7924 else
7925 x = 0xfffe; /* invalid value */
7926Error:
7927 if (x == 0xfffe)
7928 {
7929 /* undefined mapping */
7930 startinpos = s-starts;
7931 endinpos = startinpos+1;
7932 if (unicode_decode_call_errorhandler_writer(
7933 errors, &errorHandler,
7934 "charmap", "character maps to <undefined>",
7935 &starts, &e, &startinpos, &endinpos, &exc, &s,
7936 writer)) {
7937 goto onError;
7938 }
7939 continue;
7940 }
7941
7942 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7943 goto onError;
7944 ++s;
7945 }
7946 Py_XDECREF(errorHandler);
7947 Py_XDECREF(exc);
7948 return 0;
7949
7950onError:
7951 Py_XDECREF(errorHandler);
7952 Py_XDECREF(exc);
7953 return -1;
7954}
7955
7956static int
7957charmap_decode_mapping(const char *s,
7958 Py_ssize_t size,
7959 PyObject *mapping,
7960 const char *errors,
7961 _PyUnicodeWriter *writer)
7962{
7963 const char *starts = s;
7964 const char *e;
7965 Py_ssize_t startinpos, endinpos;
7966 PyObject *errorHandler = NULL, *exc = NULL;
7967 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007968 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007969
7970 e = s + size;
7971
7972 while (s < e) {
7973 ch = *s;
7974
7975 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7976 key = PyLong_FromLong((long)ch);
7977 if (key == NULL)
7978 goto onError;
7979
7980 item = PyObject_GetItem(mapping, key);
7981 Py_DECREF(key);
7982 if (item == NULL) {
7983 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7984 /* No mapping found means: mapping is undefined. */
7985 PyErr_Clear();
7986 goto Undefined;
7987 } else
7988 goto onError;
7989 }
7990
7991 /* Apply mapping */
7992 if (item == Py_None)
7993 goto Undefined;
7994 if (PyLong_Check(item)) {
7995 long value = PyLong_AS_LONG(item);
7996 if (value == 0xFFFE)
7997 goto Undefined;
7998 if (value < 0 || value > MAX_UNICODE) {
7999 PyErr_Format(PyExc_TypeError,
8000 "character mapping must be in range(0x%lx)",
8001 (unsigned long)MAX_UNICODE + 1);
8002 goto onError;
8003 }
8004
8005 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8006 goto onError;
8007 }
8008 else if (PyUnicode_Check(item)) {
8009 if (PyUnicode_READY(item) == -1)
8010 goto onError;
8011 if (PyUnicode_GET_LENGTH(item) == 1) {
8012 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8013 if (value == 0xFFFE)
8014 goto Undefined;
8015 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8016 goto onError;
8017 }
8018 else {
8019 writer->overallocate = 1;
8020 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8021 goto onError;
8022 }
8023 }
8024 else {
8025 /* wrong return value */
8026 PyErr_SetString(PyExc_TypeError,
8027 "character mapping must return integer, None or str");
8028 goto onError;
8029 }
8030 Py_CLEAR(item);
8031 ++s;
8032 continue;
8033
8034Undefined:
8035 /* undefined mapping */
8036 Py_CLEAR(item);
8037 startinpos = s-starts;
8038 endinpos = startinpos+1;
8039 if (unicode_decode_call_errorhandler_writer(
8040 errors, &errorHandler,
8041 "charmap", "character maps to <undefined>",
8042 &starts, &e, &startinpos, &endinpos, &exc, &s,
8043 writer)) {
8044 goto onError;
8045 }
8046 }
8047 Py_XDECREF(errorHandler);
8048 Py_XDECREF(exc);
8049 return 0;
8050
8051onError:
8052 Py_XDECREF(item);
8053 Py_XDECREF(errorHandler);
8054 Py_XDECREF(exc);
8055 return -1;
8056}
8057
Alexander Belopolsky40018472011-02-26 01:02:56 +00008058PyObject *
8059PyUnicode_DecodeCharmap(const char *s,
8060 Py_ssize_t size,
8061 PyObject *mapping,
8062 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008063{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008064 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008065
Guido van Rossumd57fd912000-03-10 22:53:23 +00008066 /* Default to Latin-1 */
8067 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008068 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008069
Guido van Rossumd57fd912000-03-10 22:53:23 +00008070 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008071 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008072 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008073 writer.min_length = size;
8074 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008075 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008076
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008077 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008078 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8079 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008080 }
8081 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008082 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8083 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008084 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008085 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008086
Benjamin Peterson29060642009-01-31 22:14:21 +00008087 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008088 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008089 return NULL;
8090}
8091
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092/* Charmap encoding: the lookup table */
8093
Alexander Belopolsky40018472011-02-26 01:02:56 +00008094struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 PyObject_HEAD
8096 unsigned char level1[32];
8097 int count2, count3;
8098 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008099};
8100
8101static PyObject*
8102encoding_map_size(PyObject *obj, PyObject* args)
8103{
8104 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008105 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008106 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008107}
8108
8109static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008110 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008111 PyDoc_STR("Return the size (in bytes) of this object") },
8112 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113};
8114
8115static void
8116encoding_map_dealloc(PyObject* o)
8117{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008118 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008119}
8120
8121static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008122 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008123 "EncodingMap", /*tp_name*/
8124 sizeof(struct encoding_map), /*tp_basicsize*/
8125 0, /*tp_itemsize*/
8126 /* methods */
8127 encoding_map_dealloc, /*tp_dealloc*/
8128 0, /*tp_print*/
8129 0, /*tp_getattr*/
8130 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008131 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008132 0, /*tp_repr*/
8133 0, /*tp_as_number*/
8134 0, /*tp_as_sequence*/
8135 0, /*tp_as_mapping*/
8136 0, /*tp_hash*/
8137 0, /*tp_call*/
8138 0, /*tp_str*/
8139 0, /*tp_getattro*/
8140 0, /*tp_setattro*/
8141 0, /*tp_as_buffer*/
8142 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8143 0, /*tp_doc*/
8144 0, /*tp_traverse*/
8145 0, /*tp_clear*/
8146 0, /*tp_richcompare*/
8147 0, /*tp_weaklistoffset*/
8148 0, /*tp_iter*/
8149 0, /*tp_iternext*/
8150 encoding_map_methods, /*tp_methods*/
8151 0, /*tp_members*/
8152 0, /*tp_getset*/
8153 0, /*tp_base*/
8154 0, /*tp_dict*/
8155 0, /*tp_descr_get*/
8156 0, /*tp_descr_set*/
8157 0, /*tp_dictoffset*/
8158 0, /*tp_init*/
8159 0, /*tp_alloc*/
8160 0, /*tp_new*/
8161 0, /*tp_free*/
8162 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008163};
8164
8165PyObject*
8166PyUnicode_BuildEncodingMap(PyObject* string)
8167{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008168 PyObject *result;
8169 struct encoding_map *mresult;
8170 int i;
8171 int need_dict = 0;
8172 unsigned char level1[32];
8173 unsigned char level2[512];
8174 unsigned char *mlevel1, *mlevel2, *mlevel3;
8175 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008176 int kind;
8177 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008178 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008179 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008180
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008181 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008182 PyErr_BadArgument();
8183 return NULL;
8184 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008185 kind = PyUnicode_KIND(string);
8186 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008187 length = PyUnicode_GET_LENGTH(string);
8188 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008189 memset(level1, 0xFF, sizeof level1);
8190 memset(level2, 0xFF, sizeof level2);
8191
8192 /* If there isn't a one-to-one mapping of NULL to \0,
8193 or if there are non-BMP characters, we need to use
8194 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008195 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008196 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008197 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008198 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008199 ch = PyUnicode_READ(kind, data, i);
8200 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008201 need_dict = 1;
8202 break;
8203 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008204 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008205 /* unmapped character */
8206 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008207 l1 = ch >> 11;
8208 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008209 if (level1[l1] == 0xFF)
8210 level1[l1] = count2++;
8211 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008212 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008213 }
8214
8215 if (count2 >= 0xFF || count3 >= 0xFF)
8216 need_dict = 1;
8217
8218 if (need_dict) {
8219 PyObject *result = PyDict_New();
8220 PyObject *key, *value;
8221 if (!result)
8222 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008223 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008224 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008225 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008226 if (!key || !value)
8227 goto failed1;
8228 if (PyDict_SetItem(result, key, value) == -1)
8229 goto failed1;
8230 Py_DECREF(key);
8231 Py_DECREF(value);
8232 }
8233 return result;
8234 failed1:
8235 Py_XDECREF(key);
8236 Py_XDECREF(value);
8237 Py_DECREF(result);
8238 return NULL;
8239 }
8240
8241 /* Create a three-level trie */
8242 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8243 16*count2 + 128*count3 - 1);
8244 if (!result)
8245 return PyErr_NoMemory();
8246 PyObject_Init(result, &EncodingMapType);
8247 mresult = (struct encoding_map*)result;
8248 mresult->count2 = count2;
8249 mresult->count3 = count3;
8250 mlevel1 = mresult->level1;
8251 mlevel2 = mresult->level23;
8252 mlevel3 = mresult->level23 + 16*count2;
8253 memcpy(mlevel1, level1, 32);
8254 memset(mlevel2, 0xFF, 16*count2);
8255 memset(mlevel3, 0, 128*count3);
8256 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008257 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008258 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008259 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8260 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008261 /* unmapped character */
8262 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008263 o1 = ch>>11;
8264 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008265 i2 = 16*mlevel1[o1] + o2;
8266 if (mlevel2[i2] == 0xFF)
8267 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008268 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008269 i3 = 128*mlevel2[i2] + o3;
8270 mlevel3[i3] = i;
8271 }
8272 return result;
8273}
8274
8275static int
Victor Stinner22168992011-11-20 17:09:18 +01008276encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008277{
8278 struct encoding_map *map = (struct encoding_map*)mapping;
8279 int l1 = c>>11;
8280 int l2 = (c>>7) & 0xF;
8281 int l3 = c & 0x7F;
8282 int i;
8283
Victor Stinner22168992011-11-20 17:09:18 +01008284 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008285 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008286 if (c == 0)
8287 return 0;
8288 /* level 1*/
8289 i = map->level1[l1];
8290 if (i == 0xFF) {
8291 return -1;
8292 }
8293 /* level 2*/
8294 i = map->level23[16*i+l2];
8295 if (i == 0xFF) {
8296 return -1;
8297 }
8298 /* level 3 */
8299 i = map->level23[16*map->count2 + 128*i + l3];
8300 if (i == 0) {
8301 return -1;
8302 }
8303 return i;
8304}
8305
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008306/* Lookup the character ch in the mapping. If the character
8307 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008308 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008309static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008310charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008311{
Christian Heimes217cfd12007-12-02 14:31:20 +00008312 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008313 PyObject *x;
8314
8315 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317 x = PyObject_GetItem(mapping, w);
8318 Py_DECREF(w);
8319 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8321 /* No mapping found means: mapping is undefined. */
8322 PyErr_Clear();
8323 x = Py_None;
8324 Py_INCREF(x);
8325 return x;
8326 } else
8327 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008328 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008329 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008331 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008332 long value = PyLong_AS_LONG(x);
8333 if (value < 0 || value > 255) {
8334 PyErr_SetString(PyExc_TypeError,
8335 "character mapping must be in range(256)");
8336 Py_DECREF(x);
8337 return NULL;
8338 }
8339 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008340 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008341 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008342 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008343 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 /* wrong return value */
8345 PyErr_Format(PyExc_TypeError,
8346 "character mapping must return integer, bytes or None, not %.400s",
8347 x->ob_type->tp_name);
8348 Py_DECREF(x);
8349 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008350 }
8351}
8352
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008353static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008354charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008355{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008356 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8357 /* exponentially overallocate to minimize reallocations */
8358 if (requiredsize < 2*outsize)
8359 requiredsize = 2*outsize;
8360 if (_PyBytes_Resize(outobj, requiredsize))
8361 return -1;
8362 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008363}
8364
Benjamin Peterson14339b62009-01-31 16:36:08 +00008365typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008367} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008369 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008370 space is available. Return a new reference to the object that
8371 was put in the output buffer, or Py_None, if the mapping was undefined
8372 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008373 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008374static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008375charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008376 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008378 PyObject *rep;
8379 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008380 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381
Christian Heimes90aa7642007-12-19 02:45:37 +00008382 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008383 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008385 if (res == -1)
8386 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 if (outsize<requiredsize)
8388 if (charmapencode_resize(outobj, outpos, requiredsize))
8389 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008390 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 outstart[(*outpos)++] = (char)res;
8392 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008393 }
8394
8395 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008396 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008398 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008399 Py_DECREF(rep);
8400 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008401 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 if (PyLong_Check(rep)) {
8403 Py_ssize_t requiredsize = *outpos+1;
8404 if (outsize<requiredsize)
8405 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8406 Py_DECREF(rep);
8407 return enc_EXCEPTION;
8408 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008409 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008411 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008412 else {
8413 const char *repchars = PyBytes_AS_STRING(rep);
8414 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8415 Py_ssize_t requiredsize = *outpos+repsize;
8416 if (outsize<requiredsize)
8417 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8418 Py_DECREF(rep);
8419 return enc_EXCEPTION;
8420 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008421 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008422 memcpy(outstart + *outpos, repchars, repsize);
8423 *outpos += repsize;
8424 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008426 Py_DECREF(rep);
8427 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428}
8429
8430/* handle an error in PyUnicode_EncodeCharmap
8431 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008432static int
8433charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008434 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008435 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008436 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008437 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438{
8439 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008440 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008441 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008442 enum PyUnicode_Kind kind;
8443 void *data;
8444 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008445 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008446 Py_ssize_t collstartpos = *inpos;
8447 Py_ssize_t collendpos = *inpos+1;
8448 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008449 char *encoding = "charmap";
8450 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008451 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008452 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008453 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008454
Benjamin Petersonbac79492012-01-14 13:34:47 -05008455 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008456 return -1;
8457 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008458 /* find all unencodable characters */
8459 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008460 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008461 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008462 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008463 val = encoding_map_lookup(ch, mapping);
8464 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 break;
8466 ++collendpos;
8467 continue;
8468 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008469
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008470 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8471 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 if (rep==NULL)
8473 return -1;
8474 else if (rep!=Py_None) {
8475 Py_DECREF(rep);
8476 break;
8477 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008478 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008479 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008480 }
8481 /* cache callback name lookup
8482 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008483 if (*error_handler == _Py_ERROR_UNKNOWN)
8484 *error_handler = get_error_handler(errors);
8485
8486 switch (*error_handler) {
8487 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008488 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008489 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008490
8491 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008492 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 x = charmapencode_output('?', mapping, res, respos);
8494 if (x==enc_EXCEPTION) {
8495 return -1;
8496 }
8497 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008498 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 return -1;
8500 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008501 }
8502 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008503 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008504 *inpos = collendpos;
8505 break;
Victor Stinner50149202015-09-22 00:26:54 +02008506
8507 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008508 /* generate replacement (temporarily (mis)uses p) */
8509 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 char buffer[2+29+1+1];
8511 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008512 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 for (cp = buffer; *cp; ++cp) {
8514 x = charmapencode_output(*cp, mapping, res, respos);
8515 if (x==enc_EXCEPTION)
8516 return -1;
8517 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008518 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 return -1;
8520 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008521 }
8522 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008523 *inpos = collendpos;
8524 break;
Victor Stinner50149202015-09-22 00:26:54 +02008525
Benjamin Peterson14339b62009-01-31 16:36:08 +00008526 default:
Victor Stinner50149202015-09-22 00:26:54 +02008527 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008528 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008530 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008531 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008532 if (PyBytes_Check(repunicode)) {
8533 /* Directly copy bytes result to output. */
8534 Py_ssize_t outsize = PyBytes_Size(*res);
8535 Py_ssize_t requiredsize;
8536 repsize = PyBytes_Size(repunicode);
8537 requiredsize = *respos + repsize;
8538 if (requiredsize > outsize)
8539 /* Make room for all additional bytes. */
8540 if (charmapencode_resize(res, respos, requiredsize)) {
8541 Py_DECREF(repunicode);
8542 return -1;
8543 }
8544 memcpy(PyBytes_AsString(*res) + *respos,
8545 PyBytes_AsString(repunicode), repsize);
8546 *respos += repsize;
8547 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008548 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008549 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008550 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008551 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008552 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008553 Py_DECREF(repunicode);
8554 return -1;
8555 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008556 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008557 data = PyUnicode_DATA(repunicode);
8558 kind = PyUnicode_KIND(repunicode);
8559 for (index = 0; index < repsize; index++) {
8560 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8561 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008563 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008564 return -1;
8565 }
8566 else if (x==enc_FAILED) {
8567 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008568 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008569 return -1;
8570 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008571 }
8572 *inpos = newpos;
8573 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574 }
8575 return 0;
8576}
8577
Alexander Belopolsky40018472011-02-26 01:02:56 +00008578PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008579_PyUnicode_EncodeCharmap(PyObject *unicode,
8580 PyObject *mapping,
8581 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008582{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583 /* output object */
8584 PyObject *res = NULL;
8585 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008586 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008587 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008589 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008590 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008592 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008593 void *data;
8594 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008595
Benjamin Petersonbac79492012-01-14 13:34:47 -05008596 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008597 return NULL;
8598 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008599 data = PyUnicode_DATA(unicode);
8600 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008601
Guido van Rossumd57fd912000-03-10 22:53:23 +00008602 /* Default to Latin-1 */
8603 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008604 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008605
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008606 /* allocate enough for a simple encoding without
8607 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008608 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008609 if (res == NULL)
8610 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008611 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008613
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008614 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008615 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008617 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008618 if (x==enc_EXCEPTION) /* error */
8619 goto onError;
8620 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008621 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008622 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008623 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008624 &res, &respos)) {
8625 goto onError;
8626 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008627 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008628 else
8629 /* done with this character => adjust input position */
8630 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008631 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008632
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008633 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008634 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008635 if (_PyBytes_Resize(&res, respos) < 0)
8636 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008637
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008639 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640 return res;
8641
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008643 Py_XDECREF(res);
8644 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008645 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008646 return NULL;
8647}
8648
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008649/* Deprecated */
8650PyObject *
8651PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8652 Py_ssize_t size,
8653 PyObject *mapping,
8654 const char *errors)
8655{
8656 PyObject *result;
8657 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8658 if (unicode == NULL)
8659 return NULL;
8660 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8661 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008662 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008663}
8664
Alexander Belopolsky40018472011-02-26 01:02:56 +00008665PyObject *
8666PyUnicode_AsCharmapString(PyObject *unicode,
8667 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008668{
8669 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008670 PyErr_BadArgument();
8671 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008672 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008673 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008674}
8675
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008676/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008677static void
8678make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008680 Py_ssize_t startpos, Py_ssize_t endpos,
8681 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008682{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008683 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 *exceptionObject = _PyUnicodeTranslateError_Create(
8685 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008686 }
8687 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8689 goto onError;
8690 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8691 goto onError;
8692 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8693 goto onError;
8694 return;
8695 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008696 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008697 }
8698}
8699
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008700/* error handling callback helper:
8701 build arguments, call the callback and check the arguments,
8702 put the result into newpos and return the replacement string, which
8703 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008704static PyObject *
8705unicode_translate_call_errorhandler(const char *errors,
8706 PyObject **errorHandler,
8707 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008708 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008709 Py_ssize_t startpos, Py_ssize_t endpos,
8710 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008711{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008712 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008713
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008714 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008715 PyObject *restuple;
8716 PyObject *resunicode;
8717
8718 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008720 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008722 }
8723
8724 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008725 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008726 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008727 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008728
8729 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008731 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008733 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008734 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008735 Py_DECREF(restuple);
8736 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008737 }
8738 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008739 &resunicode, &i_newpos)) {
8740 Py_DECREF(restuple);
8741 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008742 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008743 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008745 else
8746 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008747 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008748 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 Py_DECREF(restuple);
8750 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008751 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008752 Py_INCREF(resunicode);
8753 Py_DECREF(restuple);
8754 return resunicode;
8755}
8756
8757/* Lookup the character ch in the mapping and put the result in result,
8758 which must be decrefed by the caller.
8759 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008760static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008761charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008762{
Christian Heimes217cfd12007-12-02 14:31:20 +00008763 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008764 PyObject *x;
8765
8766 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008767 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008768 x = PyObject_GetItem(mapping, w);
8769 Py_DECREF(w);
8770 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008771 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8772 /* No mapping found means: use 1:1 mapping. */
8773 PyErr_Clear();
8774 *result = NULL;
8775 return 0;
8776 } else
8777 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008778 }
8779 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008780 *result = x;
8781 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008782 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008783 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008784 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008785 if (value < 0 || value > MAX_UNICODE) {
8786 PyErr_Format(PyExc_ValueError,
8787 "character mapping must be in range(0x%x)",
8788 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008789 Py_DECREF(x);
8790 return -1;
8791 }
8792 *result = x;
8793 return 0;
8794 }
8795 else if (PyUnicode_Check(x)) {
8796 *result = x;
8797 return 0;
8798 }
8799 else {
8800 /* wrong return value */
8801 PyErr_SetString(PyExc_TypeError,
8802 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008803 Py_DECREF(x);
8804 return -1;
8805 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008806}
Victor Stinner1194ea02014-04-04 19:37:40 +02008807
8808/* lookup the character, write the result into the writer.
8809 Return 1 if the result was written into the writer, return 0 if the mapping
8810 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008811static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008812charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8813 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008814{
Victor Stinner1194ea02014-04-04 19:37:40 +02008815 PyObject *item;
8816
8817 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008818 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008819
8820 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008821 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008822 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008824 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008825 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008826 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008827
8828 if (item == Py_None) {
8829 Py_DECREF(item);
8830 return 0;
8831 }
8832
8833 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008834 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8835 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8836 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008837 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8838 Py_DECREF(item);
8839 return -1;
8840 }
8841 Py_DECREF(item);
8842 return 1;
8843 }
8844
8845 if (!PyUnicode_Check(item)) {
8846 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008847 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008848 }
8849
8850 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8851 Py_DECREF(item);
8852 return -1;
8853 }
8854
8855 Py_DECREF(item);
8856 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008857}
8858
Victor Stinner89a76ab2014-04-05 11:44:04 +02008859static int
8860unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8861 Py_UCS1 *translate)
8862{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008863 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008864 int ret = 0;
8865
Victor Stinner89a76ab2014-04-05 11:44:04 +02008866 if (charmaptranslate_lookup(ch, mapping, &item)) {
8867 return -1;
8868 }
8869
8870 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008871 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008872 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008873 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008874 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008875 /* not found => default to 1:1 mapping */
8876 translate[ch] = ch;
8877 return 1;
8878 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008879 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008880 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008881 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8882 used it */
8883 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008884 /* invalid character or character outside ASCII:
8885 skip the fast translate */
8886 goto exit;
8887 }
8888 translate[ch] = (Py_UCS1)replace;
8889 }
8890 else if (PyUnicode_Check(item)) {
8891 Py_UCS4 replace;
8892
8893 if (PyUnicode_READY(item) == -1) {
8894 Py_DECREF(item);
8895 return -1;
8896 }
8897 if (PyUnicode_GET_LENGTH(item) != 1)
8898 goto exit;
8899
8900 replace = PyUnicode_READ_CHAR(item, 0);
8901 if (replace > 127)
8902 goto exit;
8903 translate[ch] = (Py_UCS1)replace;
8904 }
8905 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008906 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008907 goto exit;
8908 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008909 ret = 1;
8910
Benjamin Peterson1365de72014-04-07 20:15:41 -04008911 exit:
8912 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008913 return ret;
8914}
8915
8916/* Fast path for ascii => ascii translation. Return 1 if the whole string
8917 was translated into writer, return 0 if the input string was partially
8918 translated into writer, raise an exception and return -1 on error. */
8919static int
8920unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008921 _PyUnicodeWriter *writer, int ignore,
8922 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008923{
Victor Stinner872b2912014-04-05 14:27:07 +02008924 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008925 Py_ssize_t len;
8926 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008927 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008928
Victor Stinner89a76ab2014-04-05 11:44:04 +02008929 len = PyUnicode_GET_LENGTH(input);
8930
Victor Stinner872b2912014-04-05 14:27:07 +02008931 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008932
8933 in = PyUnicode_1BYTE_DATA(input);
8934 end = in + len;
8935
8936 assert(PyUnicode_IS_ASCII(writer->buffer));
8937 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8938 out = PyUnicode_1BYTE_DATA(writer->buffer);
8939
Victor Stinner872b2912014-04-05 14:27:07 +02008940 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008941 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008942 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008943 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008944 int translate = unicode_fast_translate_lookup(mapping, ch,
8945 ascii_table);
8946 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008947 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008948 if (translate == 0)
8949 goto exit;
8950 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008951 }
Victor Stinner872b2912014-04-05 14:27:07 +02008952 if (ch2 == 0xfe) {
8953 if (ignore)
8954 continue;
8955 goto exit;
8956 }
8957 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008958 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008959 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008960 }
Victor Stinner872b2912014-04-05 14:27:07 +02008961 res = 1;
8962
8963exit:
8964 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008965 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008966 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008967}
8968
Victor Stinner3222da22015-10-01 22:07:32 +02008969static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008970_PyUnicode_TranslateCharmap(PyObject *input,
8971 PyObject *mapping,
8972 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008973{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008974 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008975 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008976 Py_ssize_t size, i;
8977 int kind;
8978 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008979 _PyUnicodeWriter writer;
8980 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008981 char *reason = "character maps to <undefined>";
8982 PyObject *errorHandler = NULL;
8983 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008984 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008985 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008986
Guido van Rossumd57fd912000-03-10 22:53:23 +00008987 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008988 PyErr_BadArgument();
8989 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008990 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008992 if (PyUnicode_READY(input) == -1)
8993 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008994 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008995 kind = PyUnicode_KIND(input);
8996 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008997
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008998 if (size == 0)
8999 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009000
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009001 /* allocate enough for a simple 1:1 translation without
9002 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02009003 _PyUnicodeWriter_Init(&writer);
9004 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009005 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009006
Victor Stinner872b2912014-04-05 14:27:07 +02009007 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9008
Victor Stinner33798672016-03-01 21:59:58 +01009009 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009010 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01009011 if (PyUnicode_IS_ASCII(input)) {
9012 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9013 if (res < 0) {
9014 _PyUnicodeWriter_Dealloc(&writer);
9015 return NULL;
9016 }
9017 if (res == 1)
9018 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009019 }
Victor Stinner33798672016-03-01 21:59:58 +01009020 else {
9021 i = 0;
9022 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009024 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009025 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009026 int translate;
9027 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9028 Py_ssize_t newpos;
9029 /* startpos for collecting untranslatable chars */
9030 Py_ssize_t collstart;
9031 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009032 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009033
Victor Stinner1194ea02014-04-04 19:37:40 +02009034 ch = PyUnicode_READ(kind, data, i);
9035 translate = charmaptranslate_output(ch, mapping, &writer);
9036 if (translate < 0)
9037 goto onError;
9038
9039 if (translate != 0) {
9040 /* it worked => adjust input pointer */
9041 ++i;
9042 continue;
9043 }
9044
9045 /* untranslatable character */
9046 collstart = i;
9047 collend = i+1;
9048
9049 /* find all untranslatable characters */
9050 while (collend < size) {
9051 PyObject *x;
9052 ch = PyUnicode_READ(kind, data, collend);
9053 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009054 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009055 Py_XDECREF(x);
9056 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009057 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009058 ++collend;
9059 }
9060
9061 if (ignore) {
9062 i = collend;
9063 }
9064 else {
9065 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9066 reason, input, &exc,
9067 collstart, collend, &newpos);
9068 if (repunicode == NULL)
9069 goto onError;
9070 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009071 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009072 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009073 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009074 Py_DECREF(repunicode);
9075 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009076 }
9077 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009078 Py_XDECREF(exc);
9079 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009080 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009081
Benjamin Peterson29060642009-01-31 22:14:21 +00009082 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009083 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009084 Py_XDECREF(exc);
9085 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009086 return NULL;
9087}
9088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089/* Deprecated. Use PyUnicode_Translate instead. */
9090PyObject *
9091PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9092 Py_ssize_t size,
9093 PyObject *mapping,
9094 const char *errors)
9095{
Christian Heimes5f520f42012-09-11 14:03:25 +02009096 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009097 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9098 if (!unicode)
9099 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009100 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9101 Py_DECREF(unicode);
9102 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009103}
9104
Alexander Belopolsky40018472011-02-26 01:02:56 +00009105PyObject *
9106PyUnicode_Translate(PyObject *str,
9107 PyObject *mapping,
9108 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009109{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009110 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009111 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009112 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009113}
Tim Petersced69f82003-09-16 20:30:58 +00009114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009115static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009116fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009117{
9118 /* No need to call PyUnicode_READY(self) because this function is only
9119 called as a callback from fixup() which does it already. */
9120 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9121 const int kind = PyUnicode_KIND(self);
9122 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009123 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009124 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009125 Py_ssize_t i;
9126
9127 for (i = 0; i < len; ++i) {
9128 ch = PyUnicode_READ(kind, data, i);
9129 fixed = 0;
9130 if (ch > 127) {
9131 if (Py_UNICODE_ISSPACE(ch))
9132 fixed = ' ';
9133 else {
9134 const int decimal = Py_UNICODE_TODECIMAL(ch);
9135 if (decimal >= 0)
9136 fixed = '0' + decimal;
9137 }
9138 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009139 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009140 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009141 PyUnicode_WRITE(kind, data, i, fixed);
9142 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009143 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009144 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009145 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009146 }
9147
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009148 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009149}
9150
9151PyObject *
9152_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9153{
9154 if (!PyUnicode_Check(unicode)) {
9155 PyErr_BadInternalCall();
9156 return NULL;
9157 }
9158 if (PyUnicode_READY(unicode) == -1)
9159 return NULL;
9160 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9161 /* If the string is already ASCII, just return the same string */
9162 Py_INCREF(unicode);
9163 return unicode;
9164 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009165 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009166}
9167
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009168PyObject *
9169PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9170 Py_ssize_t length)
9171{
Victor Stinnerf0124502011-11-21 23:12:56 +01009172 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009173 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009174 Py_UCS4 maxchar;
9175 enum PyUnicode_Kind kind;
9176 void *data;
9177
Victor Stinner99d7ad02012-02-22 13:37:39 +01009178 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009179 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009180 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009181 if (ch > 127) {
9182 int decimal = Py_UNICODE_TODECIMAL(ch);
9183 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009184 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009185 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009186 }
9187 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009188
9189 /* Copy to a new string */
9190 decimal = PyUnicode_New(length, maxchar);
9191 if (decimal == NULL)
9192 return decimal;
9193 kind = PyUnicode_KIND(decimal);
9194 data = PyUnicode_DATA(decimal);
9195 /* Iterate over code points */
9196 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009197 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009198 if (ch > 127) {
9199 int decimal = Py_UNICODE_TODECIMAL(ch);
9200 if (decimal >= 0)
9201 ch = '0' + decimal;
9202 }
9203 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009204 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009205 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009206}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009207/* --- Decimal Encoder ---------------------------------------------------- */
9208
Alexander Belopolsky40018472011-02-26 01:02:56 +00009209int
9210PyUnicode_EncodeDecimal(Py_UNICODE *s,
9211 Py_ssize_t length,
9212 char *output,
9213 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009214{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009215 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009216 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009217 enum PyUnicode_Kind kind;
9218 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009219
9220 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009221 PyErr_BadArgument();
9222 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009223 }
9224
Victor Stinner42bf7752011-11-21 22:52:58 +01009225 unicode = PyUnicode_FromUnicode(s, length);
9226 if (unicode == NULL)
9227 return -1;
9228
Benjamin Petersonbac79492012-01-14 13:34:47 -05009229 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009230 Py_DECREF(unicode);
9231 return -1;
9232 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009233 kind = PyUnicode_KIND(unicode);
9234 data = PyUnicode_DATA(unicode);
9235
Victor Stinnerb84d7232011-11-22 01:50:07 +01009236 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009237 PyObject *exc;
9238 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009239 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009240 Py_ssize_t startpos;
9241
9242 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009243
Benjamin Peterson29060642009-01-31 22:14:21 +00009244 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009245 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009246 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009247 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009248 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009249 decimal = Py_UNICODE_TODECIMAL(ch);
9250 if (decimal >= 0) {
9251 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009252 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009253 continue;
9254 }
9255 if (0 < ch && ch < 256) {
9256 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009257 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009258 continue;
9259 }
Victor Stinner6345be92011-11-25 20:09:01 +01009260
Victor Stinner42bf7752011-11-21 22:52:58 +01009261 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009262 exc = NULL;
9263 raise_encode_exception(&exc, "decimal", unicode,
9264 startpos, startpos+1,
9265 "invalid decimal Unicode string");
9266 Py_XDECREF(exc);
9267 Py_DECREF(unicode);
9268 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009269 }
9270 /* 0-terminate the output string */
9271 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009272 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009273 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009274}
9275
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276/* --- Helpers ------------------------------------------------------------ */
9277
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009278/* helper macro to fixup start/end slice values */
9279#define ADJUST_INDICES(start, end, len) \
9280 if (end > len) \
9281 end = len; \
9282 else if (end < 0) { \
9283 end += len; \
9284 if (end < 0) \
9285 end = 0; \
9286 } \
9287 if (start < 0) { \
9288 start += len; \
9289 if (start < 0) \
9290 start = 0; \
9291 }
9292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009294any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009295 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009296 Py_ssize_t end,
9297 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009299 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009300 void *buf1, *buf2;
9301 Py_ssize_t len1, len2, result;
9302
9303 kind1 = PyUnicode_KIND(s1);
9304 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009305 if (kind1 < kind2)
9306 return -1;
9307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009308 len1 = PyUnicode_GET_LENGTH(s1);
9309 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009310 ADJUST_INDICES(start, end, len1);
9311 if (end - start < len2)
9312 return -1;
9313
9314 buf1 = PyUnicode_DATA(s1);
9315 buf2 = PyUnicode_DATA(s2);
9316 if (len2 == 1) {
9317 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9318 result = findchar((const char *)buf1 + kind1*start,
9319 kind1, end - start, ch, direction);
9320 if (result == -1)
9321 return -1;
9322 else
9323 return start + result;
9324 }
9325
9326 if (kind2 != kind1) {
9327 buf2 = _PyUnicode_AsKind(s2, kind1);
9328 if (!buf2)
9329 return -2;
9330 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009331
Victor Stinner794d5672011-10-10 03:21:36 +02009332 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009333 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009334 case PyUnicode_1BYTE_KIND:
9335 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9336 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9337 else
9338 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9339 break;
9340 case PyUnicode_2BYTE_KIND:
9341 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9342 break;
9343 case PyUnicode_4BYTE_KIND:
9344 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9345 break;
9346 default:
9347 assert(0); result = -2;
9348 }
9349 }
9350 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009351 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009352 case PyUnicode_1BYTE_KIND:
9353 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9354 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9355 else
9356 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9357 break;
9358 case PyUnicode_2BYTE_KIND:
9359 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9360 break;
9361 case PyUnicode_4BYTE_KIND:
9362 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9363 break;
9364 default:
9365 assert(0); result = -2;
9366 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009367 }
9368
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009369 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370 PyMem_Free(buf2);
9371
9372 return result;
9373}
9374
9375Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009376_PyUnicode_InsertThousandsGrouping(
9377 PyObject *unicode, Py_ssize_t index,
9378 Py_ssize_t n_buffer,
9379 void *digits, Py_ssize_t n_digits,
9380 Py_ssize_t min_width,
9381 const char *grouping, PyObject *thousands_sep,
9382 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009383{
Victor Stinner41a863c2012-02-24 00:37:51 +01009384 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009385 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009386 Py_ssize_t thousands_sep_len;
9387 Py_ssize_t len;
9388
9389 if (unicode != NULL) {
9390 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009391 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009392 }
9393 else {
9394 kind = PyUnicode_1BYTE_KIND;
9395 data = NULL;
9396 }
9397 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9398 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9399 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9400 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009401 if (thousands_sep_kind < kind) {
9402 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9403 if (!thousands_sep_data)
9404 return -1;
9405 }
9406 else {
9407 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9408 if (!data)
9409 return -1;
9410 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009411 }
9412
Benjamin Petersonead6b532011-12-20 17:23:42 -06009413 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009415 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009416 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009417 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009418 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009419 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009420 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009421 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009422 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009423 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009424 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009425 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009427 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009428 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009429 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009430 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009431 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009432 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009433 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009434 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009435 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009436 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009437 break;
9438 default:
9439 assert(0);
9440 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009441 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009442 if (unicode != NULL && thousands_sep_kind != kind) {
9443 if (thousands_sep_kind < kind)
9444 PyMem_Free(thousands_sep_data);
9445 else
9446 PyMem_Free(data);
9447 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009448 if (unicode == NULL) {
9449 *maxchar = 127;
9450 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009451 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009452 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009453 }
9454 }
9455 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009456}
9457
9458
Alexander Belopolsky40018472011-02-26 01:02:56 +00009459Py_ssize_t
9460PyUnicode_Count(PyObject *str,
9461 PyObject *substr,
9462 Py_ssize_t start,
9463 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009465 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009466 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009467 void *buf1 = NULL, *buf2 = NULL;
9468 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009469
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009470 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009471 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009472
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009473 kind1 = PyUnicode_KIND(str);
9474 kind2 = PyUnicode_KIND(substr);
9475 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009476 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009477
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009478 len1 = PyUnicode_GET_LENGTH(str);
9479 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009481 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009482 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009483
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009484 buf1 = PyUnicode_DATA(str);
9485 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009486 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009487 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009488 if (!buf2)
9489 goto onError;
9490 }
9491
9492 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009493 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009494 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009495 result = asciilib_count(
9496 ((Py_UCS1*)buf1) + start, end - start,
9497 buf2, len2, PY_SSIZE_T_MAX
9498 );
9499 else
9500 result = ucs1lib_count(
9501 ((Py_UCS1*)buf1) + start, end - start,
9502 buf2, len2, PY_SSIZE_T_MAX
9503 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 break;
9505 case PyUnicode_2BYTE_KIND:
9506 result = ucs2lib_count(
9507 ((Py_UCS2*)buf1) + start, end - start,
9508 buf2, len2, PY_SSIZE_T_MAX
9509 );
9510 break;
9511 case PyUnicode_4BYTE_KIND:
9512 result = ucs4lib_count(
9513 ((Py_UCS4*)buf1) + start, end - start,
9514 buf2, len2, PY_SSIZE_T_MAX
9515 );
9516 break;
9517 default:
9518 assert(0); result = 0;
9519 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009520
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009521 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522 PyMem_Free(buf2);
9523
Guido van Rossumd57fd912000-03-10 22:53:23 +00009524 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009526 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009527 PyMem_Free(buf2);
9528 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009529}
9530
Alexander Belopolsky40018472011-02-26 01:02:56 +00009531Py_ssize_t
9532PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009533 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009534 Py_ssize_t start,
9535 Py_ssize_t end,
9536 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009538 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009539 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009540
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009541 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009542}
9543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544Py_ssize_t
9545PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9546 Py_ssize_t start, Py_ssize_t end,
9547 int direction)
9548{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009549 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009550 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009551 if (PyUnicode_READY(str) == -1)
9552 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009553 if (start < 0 || end < 0) {
9554 PyErr_SetString(PyExc_IndexError, "string index out of range");
9555 return -2;
9556 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009557 if (end > PyUnicode_GET_LENGTH(str))
9558 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009559 if (start >= end)
9560 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009561 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009562 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9563 kind, end-start, ch, direction);
9564 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009566 else
9567 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568}
9569
Alexander Belopolsky40018472011-02-26 01:02:56 +00009570static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009571tailmatch(PyObject *self,
9572 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009573 Py_ssize_t start,
9574 Py_ssize_t end,
9575 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009576{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009577 int kind_self;
9578 int kind_sub;
9579 void *data_self;
9580 void *data_sub;
9581 Py_ssize_t offset;
9582 Py_ssize_t i;
9583 Py_ssize_t end_sub;
9584
9585 if (PyUnicode_READY(self) == -1 ||
9586 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009587 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9590 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009591 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009592 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009593
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009594 if (PyUnicode_GET_LENGTH(substring) == 0)
9595 return 1;
9596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009597 kind_self = PyUnicode_KIND(self);
9598 data_self = PyUnicode_DATA(self);
9599 kind_sub = PyUnicode_KIND(substring);
9600 data_sub = PyUnicode_DATA(substring);
9601 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9602
9603 if (direction > 0)
9604 offset = end;
9605 else
9606 offset = start;
9607
9608 if (PyUnicode_READ(kind_self, data_self, offset) ==
9609 PyUnicode_READ(kind_sub, data_sub, 0) &&
9610 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9611 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9612 /* If both are of the same kind, memcmp is sufficient */
9613 if (kind_self == kind_sub) {
9614 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009615 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009616 data_sub,
9617 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009618 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009619 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009620 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009621 else {
9622 /* We do not need to compare 0 and len(substring)-1 because
9623 the if statement above ensured already that they are equal
9624 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625 for (i = 1; i < end_sub; ++i) {
9626 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9627 PyUnicode_READ(kind_sub, data_sub, i))
9628 return 0;
9629 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009630 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009631 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009632 }
9633
9634 return 0;
9635}
9636
Alexander Belopolsky40018472011-02-26 01:02:56 +00009637Py_ssize_t
9638PyUnicode_Tailmatch(PyObject *str,
9639 PyObject *substr,
9640 Py_ssize_t start,
9641 Py_ssize_t end,
9642 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009643{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009644 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009645 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009646
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009647 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009648}
9649
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650/* Apply fixfct filter to the Unicode object self and return a
9651 reference to the modified object */
9652
Alexander Belopolsky40018472011-02-26 01:02:56 +00009653static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009654fixup(PyObject *self,
9655 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009656{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009657 PyObject *u;
9658 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009659 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009660
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009661 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009662 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009663 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009664 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009666 /* fix functions return the new maximum character in a string,
9667 if the kind of the resulting unicode object does not change,
9668 everything is fine. Otherwise we need to change the string kind
9669 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009670 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009671
9672 if (maxchar_new == 0) {
9673 /* no changes */;
9674 if (PyUnicode_CheckExact(self)) {
9675 Py_DECREF(u);
9676 Py_INCREF(self);
9677 return self;
9678 }
9679 else
9680 return u;
9681 }
9682
Victor Stinnere6abb482012-05-02 01:15:40 +02009683 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009684
Victor Stinnereaab6042011-12-11 22:22:39 +01009685 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009686 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009687
9688 /* In case the maximum character changed, we need to
9689 convert the string to the new category. */
9690 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9691 if (v == NULL) {
9692 Py_DECREF(u);
9693 return NULL;
9694 }
9695 if (maxchar_new > maxchar_old) {
9696 /* If the maxchar increased so that the kind changed, not all
9697 characters are representable anymore and we need to fix the
9698 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009699 _PyUnicode_FastCopyCharacters(v, 0,
9700 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009701 maxchar_old = fixfct(v);
9702 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009703 }
9704 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009705 _PyUnicode_FastCopyCharacters(v, 0,
9706 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009707 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009708 Py_DECREF(u);
9709 assert(_PyUnicode_CheckConsistency(v, 1));
9710 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009711}
9712
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009713static PyObject *
9714ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009715{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009716 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9717 char *resdata, *data = PyUnicode_DATA(self);
9718 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009719
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009720 res = PyUnicode_New(len, 127);
9721 if (res == NULL)
9722 return NULL;
9723 resdata = PyUnicode_DATA(res);
9724 if (lower)
9725 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009726 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009727 _Py_bytes_upper(resdata, data, len);
9728 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009729}
9730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009731static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009732handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009733{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009734 Py_ssize_t j;
9735 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009736 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009737 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009738
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009739 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9740
9741 where ! is a negation and \p{xxx} is a character with property xxx.
9742 */
9743 for (j = i - 1; j >= 0; j--) {
9744 c = PyUnicode_READ(kind, data, j);
9745 if (!_PyUnicode_IsCaseIgnorable(c))
9746 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009747 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009748 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9749 if (final_sigma) {
9750 for (j = i + 1; j < length; j++) {
9751 c = PyUnicode_READ(kind, data, j);
9752 if (!_PyUnicode_IsCaseIgnorable(c))
9753 break;
9754 }
9755 final_sigma = j == length || !_PyUnicode_IsCased(c);
9756 }
9757 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009758}
9759
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009760static int
9761lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9762 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009763{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009764 /* Obscure special case. */
9765 if (c == 0x3A3) {
9766 mapped[0] = handle_capital_sigma(kind, data, length, i);
9767 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009768 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009769 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009770}
9771
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009772static Py_ssize_t
9773do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009774{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009775 Py_ssize_t i, k = 0;
9776 int n_res, j;
9777 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009778
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009779 c = PyUnicode_READ(kind, data, 0);
9780 n_res = _PyUnicode_ToUpperFull(c, mapped);
9781 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009782 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009783 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009784 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009785 for (i = 1; i < length; i++) {
9786 c = PyUnicode_READ(kind, data, i);
9787 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9788 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009789 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009790 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009791 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009792 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009793 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009794}
9795
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009796static Py_ssize_t
9797do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9798 Py_ssize_t i, k = 0;
9799
9800 for (i = 0; i < length; i++) {
9801 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9802 int n_res, j;
9803 if (Py_UNICODE_ISUPPER(c)) {
9804 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9805 }
9806 else if (Py_UNICODE_ISLOWER(c)) {
9807 n_res = _PyUnicode_ToUpperFull(c, mapped);
9808 }
9809 else {
9810 n_res = 1;
9811 mapped[0] = c;
9812 }
9813 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009814 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009815 res[k++] = mapped[j];
9816 }
9817 }
9818 return k;
9819}
9820
9821static Py_ssize_t
9822do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9823 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009824{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009825 Py_ssize_t i, k = 0;
9826
9827 for (i = 0; i < length; i++) {
9828 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9829 int n_res, j;
9830 if (lower)
9831 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9832 else
9833 n_res = _PyUnicode_ToUpperFull(c, mapped);
9834 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009835 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009836 res[k++] = mapped[j];
9837 }
9838 }
9839 return k;
9840}
9841
9842static Py_ssize_t
9843do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9844{
9845 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9846}
9847
9848static Py_ssize_t
9849do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9850{
9851 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9852}
9853
Benjamin Petersone51757f2012-01-12 21:10:29 -05009854static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009855do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9856{
9857 Py_ssize_t i, k = 0;
9858
9859 for (i = 0; i < length; i++) {
9860 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9861 Py_UCS4 mapped[3];
9862 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9863 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009864 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009865 res[k++] = mapped[j];
9866 }
9867 }
9868 return k;
9869}
9870
9871static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009872do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9873{
9874 Py_ssize_t i, k = 0;
9875 int previous_is_cased;
9876
9877 previous_is_cased = 0;
9878 for (i = 0; i < length; i++) {
9879 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9880 Py_UCS4 mapped[3];
9881 int n_res, j;
9882
9883 if (previous_is_cased)
9884 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9885 else
9886 n_res = _PyUnicode_ToTitleFull(c, mapped);
9887
9888 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009889 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009890 res[k++] = mapped[j];
9891 }
9892
9893 previous_is_cased = _PyUnicode_IsCased(c);
9894 }
9895 return k;
9896}
9897
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009898static PyObject *
9899case_operation(PyObject *self,
9900 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9901{
9902 PyObject *res = NULL;
9903 Py_ssize_t length, newlength = 0;
9904 int kind, outkind;
9905 void *data, *outdata;
9906 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9907
Benjamin Petersoneea48462012-01-16 14:28:50 -05009908 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009909
9910 kind = PyUnicode_KIND(self);
9911 data = PyUnicode_DATA(self);
9912 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009913 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009914 PyErr_SetString(PyExc_OverflowError, "string is too long");
9915 return NULL;
9916 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009917 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009918 if (tmp == NULL)
9919 return PyErr_NoMemory();
9920 newlength = perform(kind, data, length, tmp, &maxchar);
9921 res = PyUnicode_New(newlength, maxchar);
9922 if (res == NULL)
9923 goto leave;
9924 tmpend = tmp + newlength;
9925 outdata = PyUnicode_DATA(res);
9926 outkind = PyUnicode_KIND(res);
9927 switch (outkind) {
9928 case PyUnicode_1BYTE_KIND:
9929 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9930 break;
9931 case PyUnicode_2BYTE_KIND:
9932 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9933 break;
9934 case PyUnicode_4BYTE_KIND:
9935 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9936 break;
9937 default:
9938 assert(0);
9939 break;
9940 }
9941 leave:
9942 PyMem_FREE(tmp);
9943 return res;
9944}
9945
Tim Peters8ce9f162004-08-27 01:49:32 +00009946PyObject *
9947PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009948{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009949 PyObject *res;
9950 PyObject *fseq;
9951 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009952 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009953
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009954 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009955 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009956 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009957 }
9958
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009959 /* NOTE: the following code can't call back into Python code,
9960 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009961 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009962
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009963 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009964 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009965 res = _PyUnicode_JoinArray(separator, items, seqlen);
9966 Py_DECREF(fseq);
9967 return res;
9968}
9969
9970PyObject *
9971_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9972{
9973 PyObject *res = NULL; /* the result */
9974 PyObject *sep = NULL;
9975 Py_ssize_t seplen;
9976 PyObject *item;
9977 Py_ssize_t sz, i, res_offset;
9978 Py_UCS4 maxchar;
9979 Py_UCS4 item_maxchar;
9980 int use_memcpy;
9981 unsigned char *res_data = NULL, *sep_data = NULL;
9982 PyObject *last_obj;
9983 unsigned int kind = 0;
9984
Tim Peters05eba1f2004-08-27 21:32:02 +00009985 /* If empty sequence, return u"". */
9986 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009987 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009988 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009989
Tim Peters05eba1f2004-08-27 21:32:02 +00009990 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009991 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009992 if (seqlen == 1) {
9993 if (PyUnicode_CheckExact(items[0])) {
9994 res = items[0];
9995 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009996 return res;
9997 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009998 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009999 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +000010000 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010001 else {
Victor Stinneracf47b82011-10-06 12:32:37 +020010002 /* Set up sep and seplen */
10003 if (separator == NULL) {
10004 /* fall back to a blank space separator */
10005 sep = PyUnicode_FromOrdinal(' ');
10006 if (!sep)
10007 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +020010008 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +020010009 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +000010010 }
Victor Stinneracf47b82011-10-06 12:32:37 +020010011 else {
10012 if (!PyUnicode_Check(separator)) {
10013 PyErr_Format(PyExc_TypeError,
10014 "separator: expected str instance,"
10015 " %.80s found",
10016 Py_TYPE(separator)->tp_name);
10017 goto onError;
10018 }
10019 if (PyUnicode_READY(separator))
10020 goto onError;
10021 sep = separator;
10022 seplen = PyUnicode_GET_LENGTH(separator);
10023 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10024 /* inc refcount to keep this code path symmetric with the
10025 above case of a blank separator */
10026 Py_INCREF(sep);
10027 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010028 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +000010029 }
10030
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010031 /* There are at least two things to join, or else we have a subclass
10032 * of str in the sequence.
10033 * Do a pre-pass to figure out the total amount of space we'll
10034 * need (sz), and see whether all argument are strings.
10035 */
10036 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +020010037#ifdef Py_DEBUG
10038 use_memcpy = 0;
10039#else
10040 use_memcpy = 1;
10041#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010042 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +080010043 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010044 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010045 if (!PyUnicode_Check(item)) {
10046 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +020010047 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +000010048 " %.80s found",
10049 i, Py_TYPE(item)->tp_name);
10050 goto onError;
10051 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052 if (PyUnicode_READY(item) == -1)
10053 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010054 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010056 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010057 if (i != 0) {
10058 add_sz += seplen;
10059 }
10060 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010061 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010062 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010063 goto onError;
10064 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010065 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010066 if (use_memcpy && last_obj != NULL) {
10067 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10068 use_memcpy = 0;
10069 }
10070 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010071 }
Tim Petersced69f82003-09-16 20:30:58 +000010072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010074 if (res == NULL)
10075 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010076
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010077 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010078#ifdef Py_DEBUG
10079 use_memcpy = 0;
10080#else
10081 if (use_memcpy) {
10082 res_data = PyUnicode_1BYTE_DATA(res);
10083 kind = PyUnicode_KIND(res);
10084 if (seplen != 0)
10085 sep_data = PyUnicode_1BYTE_DATA(sep);
10086 }
10087#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010088 if (use_memcpy) {
10089 for (i = 0; i < seqlen; ++i) {
10090 Py_ssize_t itemlen;
10091 item = items[i];
10092
10093 /* Copy item, and maybe the separator. */
10094 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010095 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010096 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010097 kind * seplen);
10098 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010099 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010100
10101 itemlen = PyUnicode_GET_LENGTH(item);
10102 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010103 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010104 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010105 kind * itemlen);
10106 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010107 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010108 }
10109 assert(res_data == PyUnicode_1BYTE_DATA(res)
10110 + kind * PyUnicode_GET_LENGTH(res));
10111 }
10112 else {
10113 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10114 Py_ssize_t itemlen;
10115 item = items[i];
10116
10117 /* Copy item, and maybe the separator. */
10118 if (i && seplen != 0) {
10119 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10120 res_offset += seplen;
10121 }
10122
10123 itemlen = PyUnicode_GET_LENGTH(item);
10124 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010125 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010126 res_offset += itemlen;
10127 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010128 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010129 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010130 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010131
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010133 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135
Benjamin Peterson29060642009-01-31 22:14:21 +000010136 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010138 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010139 return NULL;
10140}
10141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142#define FILL(kind, data, value, start, length) \
10143 do { \
10144 Py_ssize_t i_ = 0; \
10145 assert(kind != PyUnicode_WCHAR_KIND); \
10146 switch ((kind)) { \
10147 case PyUnicode_1BYTE_KIND: { \
10148 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010149 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 break; \
10151 } \
10152 case PyUnicode_2BYTE_KIND: { \
10153 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10154 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10155 break; \
10156 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010157 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10159 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10160 break; \
10161 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010162 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 } \
10164 } while (0)
10165
Victor Stinnerd3f08822012-05-29 12:57:52 +020010166void
10167_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10168 Py_UCS4 fill_char)
10169{
10170 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10171 const void *data = PyUnicode_DATA(unicode);
10172 assert(PyUnicode_IS_READY(unicode));
10173 assert(unicode_modifiable(unicode));
10174 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10175 assert(start >= 0);
10176 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10177 FILL(kind, data, fill_char, start, length);
10178}
10179
Victor Stinner3fe55312012-01-04 00:33:50 +010010180Py_ssize_t
10181PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10182 Py_UCS4 fill_char)
10183{
10184 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010185
10186 if (!PyUnicode_Check(unicode)) {
10187 PyErr_BadInternalCall();
10188 return -1;
10189 }
10190 if (PyUnicode_READY(unicode) == -1)
10191 return -1;
10192 if (unicode_check_modifiable(unicode))
10193 return -1;
10194
Victor Stinnerd3f08822012-05-29 12:57:52 +020010195 if (start < 0) {
10196 PyErr_SetString(PyExc_IndexError, "string index out of range");
10197 return -1;
10198 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010199 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10200 PyErr_SetString(PyExc_ValueError,
10201 "fill character is bigger than "
10202 "the string maximum character");
10203 return -1;
10204 }
10205
10206 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10207 length = Py_MIN(maxlen, length);
10208 if (length <= 0)
10209 return 0;
10210
Victor Stinnerd3f08822012-05-29 12:57:52 +020010211 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010212 return length;
10213}
10214
Victor Stinner9310abb2011-10-05 00:59:23 +020010215static PyObject *
10216pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010217 Py_ssize_t left,
10218 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010220{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010221 PyObject *u;
10222 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010223 int kind;
10224 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010225
10226 if (left < 0)
10227 left = 0;
10228 if (right < 0)
10229 right = 0;
10230
Victor Stinnerc4b49542011-12-11 22:44:26 +010010231 if (left == 0 && right == 0)
10232 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010233
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10235 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010236 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10237 return NULL;
10238 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010240 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010242 if (!u)
10243 return NULL;
10244
10245 kind = PyUnicode_KIND(u);
10246 data = PyUnicode_DATA(u);
10247 if (left)
10248 FILL(kind, data, fill, 0, left);
10249 if (right)
10250 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010251 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010252 assert(_PyUnicode_CheckConsistency(u, 1));
10253 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010254}
10255
Alexander Belopolsky40018472011-02-26 01:02:56 +000010256PyObject *
10257PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010258{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010259 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010260
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010261 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010262 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010263
Benjamin Petersonead6b532011-12-20 17:23:42 -060010264 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010265 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010266 if (PyUnicode_IS_ASCII(string))
10267 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010268 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010269 PyUnicode_GET_LENGTH(string), keepends);
10270 else
10271 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010272 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010273 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010274 break;
10275 case PyUnicode_2BYTE_KIND:
10276 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010277 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278 PyUnicode_GET_LENGTH(string), keepends);
10279 break;
10280 case PyUnicode_4BYTE_KIND:
10281 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010282 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 PyUnicode_GET_LENGTH(string), keepends);
10284 break;
10285 default:
10286 assert(0);
10287 list = 0;
10288 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010289 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290}
10291
Alexander Belopolsky40018472011-02-26 01:02:56 +000010292static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010293split(PyObject *self,
10294 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010295 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010296{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010297 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 void *buf1, *buf2;
10299 Py_ssize_t len1, len2;
10300 PyObject* out;
10301
Guido van Rossumd57fd912000-03-10 22:53:23 +000010302 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010303 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 if (PyUnicode_READY(self) == -1)
10306 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010309 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010311 if (PyUnicode_IS_ASCII(self))
10312 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010313 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010314 PyUnicode_GET_LENGTH(self), maxcount
10315 );
10316 else
10317 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010318 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010319 PyUnicode_GET_LENGTH(self), maxcount
10320 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010321 case PyUnicode_2BYTE_KIND:
10322 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010323 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 PyUnicode_GET_LENGTH(self), maxcount
10325 );
10326 case PyUnicode_4BYTE_KIND:
10327 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010328 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 PyUnicode_GET_LENGTH(self), maxcount
10330 );
10331 default:
10332 assert(0);
10333 return NULL;
10334 }
10335
10336 if (PyUnicode_READY(substring) == -1)
10337 return NULL;
10338
10339 kind1 = PyUnicode_KIND(self);
10340 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 len1 = PyUnicode_GET_LENGTH(self);
10342 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010343 if (kind1 < kind2 || len1 < len2) {
10344 out = PyList_New(1);
10345 if (out == NULL)
10346 return NULL;
10347 Py_INCREF(self);
10348 PyList_SET_ITEM(out, 0, self);
10349 return out;
10350 }
10351 buf1 = PyUnicode_DATA(self);
10352 buf2 = PyUnicode_DATA(substring);
10353 if (kind2 != kind1) {
10354 buf2 = _PyUnicode_AsKind(substring, kind1);
10355 if (!buf2)
10356 return NULL;
10357 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010359 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010361 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10362 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010363 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010364 else
10365 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010366 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367 break;
10368 case PyUnicode_2BYTE_KIND:
10369 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010370 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371 break;
10372 case PyUnicode_4BYTE_KIND:
10373 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010374 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 break;
10376 default:
10377 out = NULL;
10378 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010379 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 PyMem_Free(buf2);
10381 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382}
10383
Alexander Belopolsky40018472011-02-26 01:02:56 +000010384static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010385rsplit(PyObject *self,
10386 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010387 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010388{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010389 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 void *buf1, *buf2;
10391 Py_ssize_t len1, len2;
10392 PyObject* out;
10393
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010394 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010395 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010396
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 if (PyUnicode_READY(self) == -1)
10398 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010401 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010403 if (PyUnicode_IS_ASCII(self))
10404 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010405 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010406 PyUnicode_GET_LENGTH(self), maxcount
10407 );
10408 else
10409 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010410 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010411 PyUnicode_GET_LENGTH(self), maxcount
10412 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010413 case PyUnicode_2BYTE_KIND:
10414 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010415 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 PyUnicode_GET_LENGTH(self), maxcount
10417 );
10418 case PyUnicode_4BYTE_KIND:
10419 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010420 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 PyUnicode_GET_LENGTH(self), maxcount
10422 );
10423 default:
10424 assert(0);
10425 return NULL;
10426 }
10427
10428 if (PyUnicode_READY(substring) == -1)
10429 return NULL;
10430
10431 kind1 = PyUnicode_KIND(self);
10432 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 len1 = PyUnicode_GET_LENGTH(self);
10434 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010435 if (kind1 < kind2 || len1 < len2) {
10436 out = PyList_New(1);
10437 if (out == NULL)
10438 return NULL;
10439 Py_INCREF(self);
10440 PyList_SET_ITEM(out, 0, self);
10441 return out;
10442 }
10443 buf1 = PyUnicode_DATA(self);
10444 buf2 = PyUnicode_DATA(substring);
10445 if (kind2 != kind1) {
10446 buf2 = _PyUnicode_AsKind(substring, kind1);
10447 if (!buf2)
10448 return NULL;
10449 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010451 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010453 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10454 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010455 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010456 else
10457 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010458 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 break;
10460 case PyUnicode_2BYTE_KIND:
10461 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010462 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 break;
10464 case PyUnicode_4BYTE_KIND:
10465 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010466 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010467 break;
10468 default:
10469 out = NULL;
10470 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010471 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010472 PyMem_Free(buf2);
10473 return out;
10474}
10475
10476static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010477anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10478 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010480 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010481 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010482 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10483 return asciilib_find(buf1, len1, buf2, len2, offset);
10484 else
10485 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 case PyUnicode_2BYTE_KIND:
10487 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10488 case PyUnicode_4BYTE_KIND:
10489 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10490 }
10491 assert(0);
10492 return -1;
10493}
10494
10495static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010496anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10497 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010499 switch (kind) {
10500 case PyUnicode_1BYTE_KIND:
10501 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10502 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10503 else
10504 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10505 case PyUnicode_2BYTE_KIND:
10506 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10507 case PyUnicode_4BYTE_KIND:
10508 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10509 }
10510 assert(0);
10511 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010512}
10513
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010514static void
10515replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10516 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10517{
10518 int kind = PyUnicode_KIND(u);
10519 void *data = PyUnicode_DATA(u);
10520 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10521 if (kind == PyUnicode_1BYTE_KIND) {
10522 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10523 (Py_UCS1 *)data + len,
10524 u1, u2, maxcount);
10525 }
10526 else if (kind == PyUnicode_2BYTE_KIND) {
10527 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10528 (Py_UCS2 *)data + len,
10529 u1, u2, maxcount);
10530 }
10531 else {
10532 assert(kind == PyUnicode_4BYTE_KIND);
10533 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10534 (Py_UCS4 *)data + len,
10535 u1, u2, maxcount);
10536 }
10537}
10538
Alexander Belopolsky40018472011-02-26 01:02:56 +000010539static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540replace(PyObject *self, PyObject *str1,
10541 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010542{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 PyObject *u;
10544 char *sbuf = PyUnicode_DATA(self);
10545 char *buf1 = PyUnicode_DATA(str1);
10546 char *buf2 = PyUnicode_DATA(str2);
10547 int srelease = 0, release1 = 0, release2 = 0;
10548 int skind = PyUnicode_KIND(self);
10549 int kind1 = PyUnicode_KIND(str1);
10550 int kind2 = PyUnicode_KIND(str2);
10551 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10552 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10553 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010554 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010555 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010556
10557 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010558 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010560 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010561
Victor Stinner59de0ee2011-10-07 10:01:28 +020010562 if (str1 == str2)
10563 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564
Victor Stinner49a0a212011-10-12 23:46:10 +020010565 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010566 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10567 if (maxchar < maxchar_str1)
10568 /* substring too wide to be present */
10569 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010570 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10571 /* Replacing str1 with str2 may cause a maxchar reduction in the
10572 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010573 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010574 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010575
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010577 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010579 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010581 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010582 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010583 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010584
Victor Stinner69ed0f42013-04-09 21:48:24 +020010585 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010586 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010587 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010588 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010589 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010591 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010593
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010594 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10595 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010596 }
10597 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 int rkind = skind;
10599 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010600 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010601
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 if (kind1 < rkind) {
10603 /* widen substring */
10604 buf1 = _PyUnicode_AsKind(str1, rkind);
10605 if (!buf1) goto error;
10606 release1 = 1;
10607 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010608 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010609 if (i < 0)
10610 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611 if (rkind > kind2) {
10612 /* widen replacement */
10613 buf2 = _PyUnicode_AsKind(str2, rkind);
10614 if (!buf2) goto error;
10615 release2 = 1;
10616 }
10617 else if (rkind < kind2) {
10618 /* widen self and buf1 */
10619 rkind = kind2;
10620 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010621 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 sbuf = _PyUnicode_AsKind(self, rkind);
10623 if (!sbuf) goto error;
10624 srelease = 1;
10625 buf1 = _PyUnicode_AsKind(str1, rkind);
10626 if (!buf1) goto error;
10627 release1 = 1;
10628 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010629 u = PyUnicode_New(slen, maxchar);
10630 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010631 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010632 assert(PyUnicode_KIND(u) == rkind);
10633 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010634
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010635 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010636 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010637 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010638 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010639 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010641
10642 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010643 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010644 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010645 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010646 if (i == -1)
10647 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010648 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010650 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010652 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010653 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010654 }
10655 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010657 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 int rkind = skind;
10659 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010660
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010662 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 buf1 = _PyUnicode_AsKind(str1, rkind);
10664 if (!buf1) goto error;
10665 release1 = 1;
10666 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010667 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010668 if (n == 0)
10669 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010670 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010671 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 buf2 = _PyUnicode_AsKind(str2, rkind);
10673 if (!buf2) goto error;
10674 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010675 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010677 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 rkind = kind2;
10679 sbuf = _PyUnicode_AsKind(self, rkind);
10680 if (!sbuf) goto error;
10681 srelease = 1;
10682 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010683 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010684 buf1 = _PyUnicode_AsKind(str1, rkind);
10685 if (!buf1) goto error;
10686 release1 = 1;
10687 }
10688 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10689 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010690 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010691 PyErr_SetString(PyExc_OverflowError,
10692 "replace string is too long");
10693 goto error;
10694 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010695 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010696 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010697 _Py_INCREF_UNICODE_EMPTY();
10698 if (!unicode_empty)
10699 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010700 u = unicode_empty;
10701 goto done;
10702 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010703 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010704 PyErr_SetString(PyExc_OverflowError,
10705 "replace string is too long");
10706 goto error;
10707 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010708 u = PyUnicode_New(new_size, maxchar);
10709 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010710 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010711 assert(PyUnicode_KIND(u) == rkind);
10712 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010713 ires = i = 0;
10714 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010715 while (n-- > 0) {
10716 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010717 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010718 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010719 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010720 if (j == -1)
10721 break;
10722 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010723 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010724 memcpy(res + rkind * ires,
10725 sbuf + rkind * i,
10726 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010727 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010728 }
10729 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010730 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010731 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010733 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010734 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010735 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010736 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010737 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010738 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010739 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010740 memcpy(res + rkind * ires,
10741 sbuf + rkind * i,
10742 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010743 }
10744 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010745 /* interleave */
10746 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010747 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010748 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010749 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010750 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010751 if (--n <= 0)
10752 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010753 memcpy(res + rkind * ires,
10754 sbuf + rkind * i,
10755 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010756 ires++;
10757 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010758 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010759 memcpy(res + rkind * ires,
10760 sbuf + rkind * i,
10761 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010762 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010763 }
10764
10765 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010766 unicode_adjust_maxchar(&u);
10767 if (u == NULL)
10768 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010769 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010770
10771 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010772 if (srelease)
10773 PyMem_FREE(sbuf);
10774 if (release1)
10775 PyMem_FREE(buf1);
10776 if (release2)
10777 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010778 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010779 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010780
Benjamin Peterson29060642009-01-31 22:14:21 +000010781 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010782 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783 if (srelease)
10784 PyMem_FREE(sbuf);
10785 if (release1)
10786 PyMem_FREE(buf1);
10787 if (release2)
10788 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010789 return unicode_result_unchanged(self);
10790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010791 error:
10792 if (srelease && sbuf)
10793 PyMem_FREE(sbuf);
10794 if (release1 && buf1)
10795 PyMem_FREE(buf1);
10796 if (release2 && buf2)
10797 PyMem_FREE(buf2);
10798 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010799}
10800
10801/* --- Unicode Object Methods --------------------------------------------- */
10802
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010803PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010804 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010805\n\
10806Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010807characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808
10809static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010810unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010811{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010812 if (PyUnicode_READY(self) == -1)
10813 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010814 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010815}
10816
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010817PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010818 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010819\n\
10820Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010821have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010822
10823static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010824unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010825{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010826 if (PyUnicode_READY(self) == -1)
10827 return NULL;
10828 if (PyUnicode_GET_LENGTH(self) == 0)
10829 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010830 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010831}
10832
Benjamin Petersond5890c82012-01-14 13:23:30 -050010833PyDoc_STRVAR(casefold__doc__,
10834 "S.casefold() -> str\n\
10835\n\
10836Return a version of S suitable for caseless comparisons.");
10837
10838static PyObject *
10839unicode_casefold(PyObject *self)
10840{
10841 if (PyUnicode_READY(self) == -1)
10842 return NULL;
10843 if (PyUnicode_IS_ASCII(self))
10844 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010845 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010846}
10847
10848
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010849/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010850
10851static int
10852convert_uc(PyObject *obj, void *addr)
10853{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010854 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010855
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010856 if (!PyUnicode_Check(obj)) {
10857 PyErr_Format(PyExc_TypeError,
10858 "The fill character must be a unicode character, "
10859 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010860 return 0;
10861 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010862 if (PyUnicode_READY(obj) < 0)
10863 return 0;
10864 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010865 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010866 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010867 return 0;
10868 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010869 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010870 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010871}
10872
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010873PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010874 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010876Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010877done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010878
10879static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010880unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010881{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010882 Py_ssize_t marg, left;
10883 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010884 Py_UCS4 fillchar = ' ';
10885
Victor Stinnere9a29352011-10-01 02:14:59 +020010886 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010887 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888
Benjamin Petersonbac79492012-01-14 13:34:47 -050010889 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010890 return NULL;
10891
Victor Stinnerc4b49542011-12-11 22:44:26 +010010892 if (PyUnicode_GET_LENGTH(self) >= width)
10893 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010894
Victor Stinnerc4b49542011-12-11 22:44:26 +010010895 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010896 left = marg / 2 + (marg & width & 1);
10897
Victor Stinner9310abb2011-10-05 00:59:23 +020010898 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899}
10900
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010901/* This function assumes that str1 and str2 are readied by the caller. */
10902
Marc-André Lemburge5034372000-08-08 08:04:29 +000010903static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010904unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010905{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010906#define COMPARE(TYPE1, TYPE2) \
10907 do { \
10908 TYPE1* p1 = (TYPE1 *)data1; \
10909 TYPE2* p2 = (TYPE2 *)data2; \
10910 TYPE1* end = p1 + len; \
10911 Py_UCS4 c1, c2; \
10912 for (; p1 != end; p1++, p2++) { \
10913 c1 = *p1; \
10914 c2 = *p2; \
10915 if (c1 != c2) \
10916 return (c1 < c2) ? -1 : 1; \
10917 } \
10918 } \
10919 while (0)
10920
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010921 int kind1, kind2;
10922 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010923 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010925 kind1 = PyUnicode_KIND(str1);
10926 kind2 = PyUnicode_KIND(str2);
10927 data1 = PyUnicode_DATA(str1);
10928 data2 = PyUnicode_DATA(str2);
10929 len1 = PyUnicode_GET_LENGTH(str1);
10930 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010931 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010932
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010933 switch(kind1) {
10934 case PyUnicode_1BYTE_KIND:
10935 {
10936 switch(kind2) {
10937 case PyUnicode_1BYTE_KIND:
10938 {
10939 int cmp = memcmp(data1, data2, len);
10940 /* normalize result of memcmp() into the range [-1; 1] */
10941 if (cmp < 0)
10942 return -1;
10943 if (cmp > 0)
10944 return 1;
10945 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010946 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010947 case PyUnicode_2BYTE_KIND:
10948 COMPARE(Py_UCS1, Py_UCS2);
10949 break;
10950 case PyUnicode_4BYTE_KIND:
10951 COMPARE(Py_UCS1, Py_UCS4);
10952 break;
10953 default:
10954 assert(0);
10955 }
10956 break;
10957 }
10958 case PyUnicode_2BYTE_KIND:
10959 {
10960 switch(kind2) {
10961 case PyUnicode_1BYTE_KIND:
10962 COMPARE(Py_UCS2, Py_UCS1);
10963 break;
10964 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010965 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010966 COMPARE(Py_UCS2, Py_UCS2);
10967 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010968 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010969 case PyUnicode_4BYTE_KIND:
10970 COMPARE(Py_UCS2, Py_UCS4);
10971 break;
10972 default:
10973 assert(0);
10974 }
10975 break;
10976 }
10977 case PyUnicode_4BYTE_KIND:
10978 {
10979 switch(kind2) {
10980 case PyUnicode_1BYTE_KIND:
10981 COMPARE(Py_UCS4, Py_UCS1);
10982 break;
10983 case PyUnicode_2BYTE_KIND:
10984 COMPARE(Py_UCS4, Py_UCS2);
10985 break;
10986 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010987 {
10988#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10989 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10990 /* normalize result of wmemcmp() into the range [-1; 1] */
10991 if (cmp < 0)
10992 return -1;
10993 if (cmp > 0)
10994 return 1;
10995#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010996 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010997#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010998 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010999 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011000 default:
11001 assert(0);
11002 }
11003 break;
11004 }
11005 default:
11006 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000011007 }
11008
Victor Stinner770e19e2012-10-04 22:59:45 +020011009 if (len1 == len2)
11010 return 0;
11011 if (len1 < len2)
11012 return -1;
11013 else
11014 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011015
11016#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000011017}
11018
Benjamin Peterson621b4302016-09-09 13:54:34 -070011019static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020011020unicode_compare_eq(PyObject *str1, PyObject *str2)
11021{
11022 int kind;
11023 void *data1, *data2;
11024 Py_ssize_t len;
11025 int cmp;
11026
Victor Stinnere5567ad2012-10-23 02:48:49 +020011027 len = PyUnicode_GET_LENGTH(str1);
11028 if (PyUnicode_GET_LENGTH(str2) != len)
11029 return 0;
11030 kind = PyUnicode_KIND(str1);
11031 if (PyUnicode_KIND(str2) != kind)
11032 return 0;
11033 data1 = PyUnicode_DATA(str1);
11034 data2 = PyUnicode_DATA(str2);
11035
11036 cmp = memcmp(data1, data2, len * kind);
11037 return (cmp == 0);
11038}
11039
11040
Alexander Belopolsky40018472011-02-26 01:02:56 +000011041int
11042PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011044 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11045 if (PyUnicode_READY(left) == -1 ||
11046 PyUnicode_READY(right) == -1)
11047 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011048
11049 /* a string is equal to itself */
11050 if (left == right)
11051 return 0;
11052
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011053 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011055 PyErr_Format(PyExc_TypeError,
11056 "Can't compare %.100s and %.100s",
11057 left->ob_type->tp_name,
11058 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011059 return -1;
11060}
11061
Martin v. Löwis5b222132007-06-10 09:51:05 +000011062int
11063PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11064{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011065 Py_ssize_t i;
11066 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011067 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011068 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011069
Victor Stinner910337b2011-10-03 03:20:16 +020011070 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011071 if (!PyUnicode_IS_READY(uni)) {
11072 const wchar_t *ws = _PyUnicode_WSTR(uni);
11073 /* Compare Unicode string and source character set string */
11074 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11075 if (chr != ustr[i])
11076 return (chr < ustr[i]) ? -1 : 1;
11077 }
11078 /* This check keeps Python strings that end in '\0' from comparing equal
11079 to C strings identical up to that point. */
11080 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11081 return 1; /* uni is longer */
11082 if (ustr[i])
11083 return -1; /* str is longer */
11084 return 0;
11085 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011086 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011087 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011088 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011089 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011090 size_t len, len2 = strlen(str);
11091 int cmp;
11092
11093 len = Py_MIN(len1, len2);
11094 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011095 if (cmp != 0) {
11096 if (cmp < 0)
11097 return -1;
11098 else
11099 return 1;
11100 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011101 if (len1 > len2)
11102 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011103 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011104 return -1; /* str is longer */
11105 return 0;
11106 }
11107 else {
11108 void *data = PyUnicode_DATA(uni);
11109 /* Compare Unicode string and source character set string */
11110 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011111 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011112 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11113 /* This check keeps Python strings that end in '\0' from comparing equal
11114 to C strings identical up to that point. */
11115 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11116 return 1; /* uni is longer */
11117 if (str[i])
11118 return -1; /* str is longer */
11119 return 0;
11120 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011121}
11122
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011123static int
11124non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11125{
11126 size_t i, len;
11127 const wchar_t *p;
11128 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11129 if (strlen(str) != len)
11130 return 0;
11131 p = _PyUnicode_WSTR(unicode);
11132 assert(p);
11133 for (i = 0; i < len; i++) {
11134 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011135 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011136 return 0;
11137 }
11138 return 1;
11139}
11140
11141int
11142_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11143{
11144 size_t len;
11145 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011146 assert(str);
11147#ifndef NDEBUG
11148 for (const char *p = str; *p; p++) {
11149 assert((unsigned char)*p < 128);
11150 }
11151#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011152 if (PyUnicode_READY(unicode) == -1) {
11153 /* Memory error or bad data */
11154 PyErr_Clear();
11155 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11156 }
11157 if (!PyUnicode_IS_ASCII(unicode))
11158 return 0;
11159 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11160 return strlen(str) == len &&
11161 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11162}
11163
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011164int
11165_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11166{
11167 PyObject *right_uni;
11168 Py_hash_t hash;
11169
11170 assert(_PyUnicode_CHECK(left));
11171 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011172#ifndef NDEBUG
11173 for (const char *p = right->string; *p; p++) {
11174 assert((unsigned char)*p < 128);
11175 }
11176#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011177
11178 if (PyUnicode_READY(left) == -1) {
11179 /* memory error or bad data */
11180 PyErr_Clear();
11181 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11182 }
11183
11184 if (!PyUnicode_IS_ASCII(left))
11185 return 0;
11186
11187 right_uni = _PyUnicode_FromId(right); /* borrowed */
11188 if (right_uni == NULL) {
11189 /* memory error or bad data */
11190 PyErr_Clear();
11191 return _PyUnicode_EqualToASCIIString(left, right->string);
11192 }
11193
11194 if (left == right_uni)
11195 return 1;
11196
11197 if (PyUnicode_CHECK_INTERNED(left))
11198 return 0;
11199
11200 assert(_PyUnicode_HASH(right_uni) != 1);
11201 hash = _PyUnicode_HASH(left);
11202 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11203 return 0;
11204
11205 return unicode_compare_eq(left, right_uni);
11206}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011207
Benjamin Peterson29060642009-01-31 22:14:21 +000011208#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011209 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011210
Alexander Belopolsky40018472011-02-26 01:02:56 +000011211PyObject *
11212PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011213{
11214 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011215 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011216
Victor Stinnere5567ad2012-10-23 02:48:49 +020011217 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11218 Py_RETURN_NOTIMPLEMENTED;
11219
11220 if (PyUnicode_READY(left) == -1 ||
11221 PyUnicode_READY(right) == -1)
11222 return NULL;
11223
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011224 if (left == right) {
11225 switch (op) {
11226 case Py_EQ:
11227 case Py_LE:
11228 case Py_GE:
11229 /* a string is equal to itself */
11230 v = Py_True;
11231 break;
11232 case Py_NE:
11233 case Py_LT:
11234 case Py_GT:
11235 v = Py_False;
11236 break;
11237 default:
11238 PyErr_BadArgument();
11239 return NULL;
11240 }
11241 }
11242 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011243 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011244 result ^= (op == Py_NE);
11245 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011246 }
11247 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011248 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011249
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011250 /* Convert the return value to a Boolean */
11251 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011252 case Py_LE:
11253 v = TEST_COND(result <= 0);
11254 break;
11255 case Py_GE:
11256 v = TEST_COND(result >= 0);
11257 break;
11258 case Py_LT:
11259 v = TEST_COND(result == -1);
11260 break;
11261 case Py_GT:
11262 v = TEST_COND(result == 1);
11263 break;
11264 default:
11265 PyErr_BadArgument();
11266 return NULL;
11267 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011268 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011269 Py_INCREF(v);
11270 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011271}
11272
Alexander Belopolsky40018472011-02-26 01:02:56 +000011273int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011274_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11275{
11276 return unicode_eq(aa, bb);
11277}
11278
11279int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011280PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011281{
Victor Stinner77282cb2013-04-14 19:22:47 +020011282 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283 void *buf1, *buf2;
11284 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011285 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011286
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011287 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011289 "'in <string>' requires string as left operand, not %.100s",
11290 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011291 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011292 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011293 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011294 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011295 if (ensure_unicode(str) < 0)
11296 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011297
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011298 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011299 kind2 = PyUnicode_KIND(substr);
11300 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011301 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011302 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011303 len2 = PyUnicode_GET_LENGTH(substr);
11304 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011305 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011306 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011307 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011308 if (len2 == 1) {
11309 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11310 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011311 return result;
11312 }
11313 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011314 buf2 = _PyUnicode_AsKind(substr, kind1);
11315 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011316 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011317 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011318
Victor Stinner77282cb2013-04-14 19:22:47 +020011319 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 case PyUnicode_1BYTE_KIND:
11321 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11322 break;
11323 case PyUnicode_2BYTE_KIND:
11324 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11325 break;
11326 case PyUnicode_4BYTE_KIND:
11327 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11328 break;
11329 default:
11330 result = -1;
11331 assert(0);
11332 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011333
Victor Stinner77282cb2013-04-14 19:22:47 +020011334 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011335 PyMem_Free(buf2);
11336
Guido van Rossum403d68b2000-03-13 15:55:09 +000011337 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011338}
11339
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340/* Concat to string or Unicode object giving a new Unicode object. */
11341
Alexander Belopolsky40018472011-02-26 01:02:56 +000011342PyObject *
11343PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011345 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011346 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011347 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011349 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11350 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351
11352 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011353 if (left == unicode_empty)
11354 return PyUnicode_FromObject(right);
11355 if (right == unicode_empty)
11356 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011357
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011358 left_len = PyUnicode_GET_LENGTH(left);
11359 right_len = PyUnicode_GET_LENGTH(right);
11360 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011361 PyErr_SetString(PyExc_OverflowError,
11362 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011363 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011364 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011365 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011366
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011367 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11368 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011369 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011370
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011372 result = PyUnicode_New(new_len, maxchar);
11373 if (result == NULL)
11374 return NULL;
11375 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11376 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11377 assert(_PyUnicode_CheckConsistency(result, 1));
11378 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379}
11380
Walter Dörwald1ab83302007-05-18 17:15:44 +000011381void
Victor Stinner23e56682011-10-03 03:54:37 +020011382PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011383{
Victor Stinner23e56682011-10-03 03:54:37 +020011384 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011385 Py_UCS4 maxchar, maxchar2;
11386 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011387
11388 if (p_left == NULL) {
11389 if (!PyErr_Occurred())
11390 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011391 return;
11392 }
Victor Stinner23e56682011-10-03 03:54:37 +020011393 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011394 if (right == NULL || left == NULL
11395 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011396 if (!PyErr_Occurred())
11397 PyErr_BadInternalCall();
11398 goto error;
11399 }
11400
Benjamin Petersonbac79492012-01-14 13:34:47 -050011401 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011402 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011403 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011404 goto error;
11405
Victor Stinner488fa492011-12-12 00:01:39 +010011406 /* Shortcuts */
11407 if (left == unicode_empty) {
11408 Py_DECREF(left);
11409 Py_INCREF(right);
11410 *p_left = right;
11411 return;
11412 }
11413 if (right == unicode_empty)
11414 return;
11415
11416 left_len = PyUnicode_GET_LENGTH(left);
11417 right_len = PyUnicode_GET_LENGTH(right);
11418 if (left_len > PY_SSIZE_T_MAX - right_len) {
11419 PyErr_SetString(PyExc_OverflowError,
11420 "strings are too large to concat");
11421 goto error;
11422 }
11423 new_len = left_len + right_len;
11424
11425 if (unicode_modifiable(left)
11426 && PyUnicode_CheckExact(right)
11427 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011428 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11429 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011430 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011431 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011432 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11433 {
11434 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011435 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011436 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011437
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011438 /* copy 'right' into the newly allocated area of 'left' */
11439 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011440 }
Victor Stinner488fa492011-12-12 00:01:39 +010011441 else {
11442 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11443 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011444 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011445
Victor Stinner488fa492011-12-12 00:01:39 +010011446 /* Concat the two Unicode strings */
11447 res = PyUnicode_New(new_len, maxchar);
11448 if (res == NULL)
11449 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011450 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11451 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011452 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011453 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011454 }
11455 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011456 return;
11457
11458error:
Victor Stinner488fa492011-12-12 00:01:39 +010011459 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011460}
11461
11462void
11463PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11464{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011465 PyUnicode_Append(pleft, right);
11466 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011467}
11468
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011469/*
11470Wraps stringlib_parse_args_finds() and additionally ensures that the
11471first argument is a unicode object.
11472*/
11473
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011474static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011475parse_args_finds_unicode(const char * function_name, PyObject *args,
11476 PyObject **substring,
11477 Py_ssize_t *start, Py_ssize_t *end)
11478{
11479 if(stringlib_parse_args_finds(function_name, args, substring,
11480 start, end)) {
11481 if (ensure_unicode(*substring) < 0)
11482 return 0;
11483 return 1;
11484 }
11485 return 0;
11486}
11487
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011488PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011489 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011491Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011492string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011493interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494
11495static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011496unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011498 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011499 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011500 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011502 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011503 void *buf1, *buf2;
11504 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011506 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011507 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011509 kind1 = PyUnicode_KIND(self);
11510 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011511 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011512 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 len1 = PyUnicode_GET_LENGTH(self);
11515 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011516 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011517 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011518 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011519
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011520 buf1 = PyUnicode_DATA(self);
11521 buf2 = PyUnicode_DATA(substring);
11522 if (kind2 != kind1) {
11523 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011524 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011525 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011526 }
11527 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011528 case PyUnicode_1BYTE_KIND:
11529 iresult = ucs1lib_count(
11530 ((Py_UCS1*)buf1) + start, end - start,
11531 buf2, len2, PY_SSIZE_T_MAX
11532 );
11533 break;
11534 case PyUnicode_2BYTE_KIND:
11535 iresult = ucs2lib_count(
11536 ((Py_UCS2*)buf1) + start, end - start,
11537 buf2, len2, PY_SSIZE_T_MAX
11538 );
11539 break;
11540 case PyUnicode_4BYTE_KIND:
11541 iresult = ucs4lib_count(
11542 ((Py_UCS4*)buf1) + start, end - start,
11543 buf2, len2, PY_SSIZE_T_MAX
11544 );
11545 break;
11546 default:
11547 assert(0); iresult = 0;
11548 }
11549
11550 result = PyLong_FromSsize_t(iresult);
11551
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011552 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555 return result;
11556}
11557
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011558PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011559 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011561Encode S using the codec registered for encoding. Default encoding\n\
11562is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011563handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011564a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11565'xmlcharrefreplace' as well as any other name registered with\n\
11566codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567
11568static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011569unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011571 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572 char *encoding = NULL;
11573 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011574
Benjamin Peterson308d6372009-09-18 21:42:35 +000011575 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11576 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011578 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011579}
11580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011581PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011582 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583\n\
11584Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011585If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586
11587static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011588unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011590 Py_ssize_t i, j, line_pos, src_len, incr;
11591 Py_UCS4 ch;
11592 PyObject *u;
11593 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011594 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011596 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011597 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598
Ezio Melotti745d54d2013-11-16 19:10:57 +020011599 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11600 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011601 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602
Antoine Pitrou22425222011-10-04 19:10:51 +020011603 if (PyUnicode_READY(self) == -1)
11604 return NULL;
11605
Thomas Wouters7e474022000-07-16 12:04:32 +000011606 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011607 src_len = PyUnicode_GET_LENGTH(self);
11608 i = j = line_pos = 0;
11609 kind = PyUnicode_KIND(self);
11610 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011611 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011612 for (; i < src_len; i++) {
11613 ch = PyUnicode_READ(kind, src_data, i);
11614 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011615 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011616 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011617 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011619 goto overflow;
11620 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011621 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011622 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011623 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011625 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011626 goto overflow;
11627 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011629 if (ch == '\n' || ch == '\r')
11630 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011632 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011633 if (!found)
11634 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011635
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011637 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011638 if (!u)
11639 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011640 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641
Antoine Pitroue71d5742011-10-04 15:55:09 +020011642 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643
Antoine Pitroue71d5742011-10-04 15:55:09 +020011644 for (; i < src_len; i++) {
11645 ch = PyUnicode_READ(kind, src_data, i);
11646 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011647 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011648 incr = tabsize - (line_pos % tabsize);
11649 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011650 FILL(kind, dest_data, ' ', j, incr);
11651 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011652 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011653 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011654 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011655 line_pos++;
11656 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011657 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011658 if (ch == '\n' || ch == '\r')
11659 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011661 }
11662 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011663 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011664
Antoine Pitroue71d5742011-10-04 15:55:09 +020011665 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011666 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11667 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668}
11669
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011670PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011671 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672\n\
11673Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011674such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675arguments start and end are interpreted as in slice notation.\n\
11676\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011677Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678
11679static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011682 /* initialize variables to prevent gcc warning */
11683 PyObject *substring = NULL;
11684 Py_ssize_t start = 0;
11685 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011686 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011688 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011691 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011692 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011694 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696 if (result == -2)
11697 return NULL;
11698
Christian Heimes217cfd12007-12-02 14:31:20 +000011699 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700}
11701
11702static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011703unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011705 void *data;
11706 enum PyUnicode_Kind kind;
11707 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011708
11709 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11710 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011711 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011712 }
11713 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11714 PyErr_SetString(PyExc_IndexError, "string index out of range");
11715 return NULL;
11716 }
11717 kind = PyUnicode_KIND(self);
11718 data = PyUnicode_DATA(self);
11719 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011720 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721}
11722
Guido van Rossumc2504932007-09-18 19:42:40 +000011723/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011724 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011725static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011726unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727{
Guido van Rossumc2504932007-09-18 19:42:40 +000011728 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011729 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011730
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011731#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011732 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011733#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011734 if (_PyUnicode_HASH(self) != -1)
11735 return _PyUnicode_HASH(self);
11736 if (PyUnicode_READY(self) == -1)
11737 return -1;
11738 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011739 /*
11740 We make the hash of the empty string be 0, rather than using
11741 (prefix ^ suffix), since this slightly obfuscates the hash secret
11742 */
11743 if (len == 0) {
11744 _PyUnicode_HASH(self) = 0;
11745 return 0;
11746 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011747 x = _Py_HashBytes(PyUnicode_DATA(self),
11748 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011749 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011750 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751}
11752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011753PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011754 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755\n\
Mariatta577fc042017-04-09 15:17:06 -070011756Return the lowest index in S where substring sub is found, \n\
11757such that sub is contained within S[start:end]. Optional\n\
11758arguments start and end are interpreted as in slice notation.\n\
11759\n\
11760Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761
11762static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011765 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011766 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011767 PyObject *substring = NULL;
11768 Py_ssize_t start = 0;
11769 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011771 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011772 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011774 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011777 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011778
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 if (result == -2)
11780 return NULL;
11781
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782 if (result < 0) {
11783 PyErr_SetString(PyExc_ValueError, "substring not found");
11784 return NULL;
11785 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011786
Christian Heimes217cfd12007-12-02 14:31:20 +000011787 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788}
11789
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011790PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011791 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011793Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011794at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795
11796static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011797unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 Py_ssize_t i, length;
11800 int kind;
11801 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011802 int cased;
11803
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011804 if (PyUnicode_READY(self) == -1)
11805 return NULL;
11806 length = PyUnicode_GET_LENGTH(self);
11807 kind = PyUnicode_KIND(self);
11808 data = PyUnicode_DATA(self);
11809
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 if (length == 1)
11812 return PyBool_FromLong(
11813 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011814
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011815 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011818
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011820 for (i = 0; i < length; i++) {
11821 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011822
Benjamin Peterson29060642009-01-31 22:14:21 +000011823 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11824 return PyBool_FromLong(0);
11825 else if (!cased && Py_UNICODE_ISLOWER(ch))
11826 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011828 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011829}
11830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011831PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011832 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011834Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011835at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836
11837static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011838unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011839{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011840 Py_ssize_t i, length;
11841 int kind;
11842 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011843 int cased;
11844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011845 if (PyUnicode_READY(self) == -1)
11846 return NULL;
11847 length = PyUnicode_GET_LENGTH(self);
11848 kind = PyUnicode_KIND(self);
11849 data = PyUnicode_DATA(self);
11850
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 if (length == 1)
11853 return PyBool_FromLong(
11854 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011855
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011856 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011858 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011859
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 for (i = 0; i < length; i++) {
11862 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011863
Benjamin Peterson29060642009-01-31 22:14:21 +000011864 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11865 return PyBool_FromLong(0);
11866 else if (!cased && Py_UNICODE_ISUPPER(ch))
11867 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011869 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870}
11871
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011872PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011873 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011874\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011875Return True if S is a titlecased string and there is at least one\n\
11876character in S, i.e. upper- and titlecase characters may only\n\
11877follow uncased characters and lowercase characters only cased ones.\n\
11878Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879
11880static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011881unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 Py_ssize_t i, length;
11884 int kind;
11885 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886 int cased, previous_is_cased;
11887
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 if (PyUnicode_READY(self) == -1)
11889 return NULL;
11890 length = PyUnicode_GET_LENGTH(self);
11891 kind = PyUnicode_KIND(self);
11892 data = PyUnicode_DATA(self);
11893
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011895 if (length == 1) {
11896 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11897 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11898 (Py_UNICODE_ISUPPER(ch) != 0));
11899 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011901 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011902 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011903 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011904
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905 cased = 0;
11906 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 for (i = 0; i < length; i++) {
11908 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011909
Benjamin Peterson29060642009-01-31 22:14:21 +000011910 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11911 if (previous_is_cased)
11912 return PyBool_FromLong(0);
11913 previous_is_cased = 1;
11914 cased = 1;
11915 }
11916 else if (Py_UNICODE_ISLOWER(ch)) {
11917 if (!previous_is_cased)
11918 return PyBool_FromLong(0);
11919 previous_is_cased = 1;
11920 cased = 1;
11921 }
11922 else
11923 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011925 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011926}
11927
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011928PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011929 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011931Return True if all characters in S are whitespace\n\
11932and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933
11934static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011935unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011936{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011937 Py_ssize_t i, length;
11938 int kind;
11939 void *data;
11940
11941 if (PyUnicode_READY(self) == -1)
11942 return NULL;
11943 length = PyUnicode_GET_LENGTH(self);
11944 kind = PyUnicode_KIND(self);
11945 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011946
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011948 if (length == 1)
11949 return PyBool_FromLong(
11950 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011952 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011954 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011955
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011956 for (i = 0; i < length; i++) {
11957 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011958 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011959 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011961 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011962}
11963
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011964PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011965 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011966\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011967Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011968and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011969
11970static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011971unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011972{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973 Py_ssize_t i, length;
11974 int kind;
11975 void *data;
11976
11977 if (PyUnicode_READY(self) == -1)
11978 return NULL;
11979 length = PyUnicode_GET_LENGTH(self);
11980 kind = PyUnicode_KIND(self);
11981 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011982
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011983 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011984 if (length == 1)
11985 return PyBool_FromLong(
11986 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011987
11988 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011989 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011990 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992 for (i = 0; i < length; i++) {
11993 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011994 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011995 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011996 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011997}
11998
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011999PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012000 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012001\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000012002Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012003and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012004
12005static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012006unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012007{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012008 int kind;
12009 void *data;
12010 Py_ssize_t len, i;
12011
12012 if (PyUnicode_READY(self) == -1)
12013 return NULL;
12014
12015 kind = PyUnicode_KIND(self);
12016 data = PyUnicode_DATA(self);
12017 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012018
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012019 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012020 if (len == 1) {
12021 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12022 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12023 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012024
12025 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012026 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012027 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029 for (i = 0; i < len; i++) {
12030 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012031 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000012032 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012033 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012034 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012035}
12036
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012037PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012038 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012039\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000012040Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012041False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012042
12043static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012044unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012045{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 Py_ssize_t i, length;
12047 int kind;
12048 void *data;
12049
12050 if (PyUnicode_READY(self) == -1)
12051 return NULL;
12052 length = PyUnicode_GET_LENGTH(self);
12053 kind = PyUnicode_KIND(self);
12054 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012055
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012057 if (length == 1)
12058 return PyBool_FromLong(
12059 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012060
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012061 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012063 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012064
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012065 for (i = 0; i < length; i++) {
12066 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012067 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012068 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012069 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012070}
12071
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012072PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012073 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012074\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000012075Return True if all characters in S are digits\n\
12076and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012077
12078static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012079unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012080{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012081 Py_ssize_t i, length;
12082 int kind;
12083 void *data;
12084
12085 if (PyUnicode_READY(self) == -1)
12086 return NULL;
12087 length = PyUnicode_GET_LENGTH(self);
12088 kind = PyUnicode_KIND(self);
12089 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090
Guido van Rossumd57fd912000-03-10 22:53:23 +000012091 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012092 if (length == 1) {
12093 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12094 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12095 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012097 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012098 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012099 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012101 for (i = 0; i < length; i++) {
12102 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012103 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012105 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106}
12107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012108PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012109 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000012111Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012112False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113
12114static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012115unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012116{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012117 Py_ssize_t i, length;
12118 int kind;
12119 void *data;
12120
12121 if (PyUnicode_READY(self) == -1)
12122 return NULL;
12123 length = PyUnicode_GET_LENGTH(self);
12124 kind = PyUnicode_KIND(self);
12125 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012126
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128 if (length == 1)
12129 return PyBool_FromLong(
12130 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012132 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012133 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012134 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012136 for (i = 0; i < length; i++) {
12137 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012138 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012139 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012140 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141}
12142
Martin v. Löwis47383402007-08-15 07:32:56 +000012143int
12144PyUnicode_IsIdentifier(PyObject *self)
12145{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012146 int kind;
12147 void *data;
12148 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012149 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012150
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012151 if (PyUnicode_READY(self) == -1) {
12152 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012153 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012154 }
12155
12156 /* Special case for empty strings */
12157 if (PyUnicode_GET_LENGTH(self) == 0)
12158 return 0;
12159 kind = PyUnicode_KIND(self);
12160 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012161
12162 /* PEP 3131 says that the first character must be in
12163 XID_Start and subsequent characters in XID_Continue,
12164 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012165 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012166 letters, digits, underscore). However, given the current
12167 definition of XID_Start and XID_Continue, it is sufficient
12168 to check just for these, except that _ must be allowed
12169 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012171 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012172 return 0;
12173
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012174 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012175 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012176 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012177 return 1;
12178}
12179
12180PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012181 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012182\n\
12183Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012184to the language definition.\n\
12185\n\
12186Use keyword.iskeyword() to test for reserved identifiers\n\
12187such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012188
12189static PyObject*
12190unicode_isidentifier(PyObject *self)
12191{
12192 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12193}
12194
Georg Brandl559e5d72008-06-11 18:37:52 +000012195PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012196 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012197\n\
12198Return True if all characters in S are considered\n\
12199printable in repr() or S is empty, False otherwise.");
12200
12201static PyObject*
12202unicode_isprintable(PyObject *self)
12203{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012204 Py_ssize_t i, length;
12205 int kind;
12206 void *data;
12207
12208 if (PyUnicode_READY(self) == -1)
12209 return NULL;
12210 length = PyUnicode_GET_LENGTH(self);
12211 kind = PyUnicode_KIND(self);
12212 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012213
12214 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012215 if (length == 1)
12216 return PyBool_FromLong(
12217 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012219 for (i = 0; i < length; i++) {
12220 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012221 Py_RETURN_FALSE;
12222 }
12223 }
12224 Py_RETURN_TRUE;
12225}
12226
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012227PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012228 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012229\n\
12230Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012231iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232
12233static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012234unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012235{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012236 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012237}
12238
Martin v. Löwis18e16552006-02-15 17:27:45 +000012239static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012240unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012242 if (PyUnicode_READY(self) == -1)
12243 return -1;
12244 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012245}
12246
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012247PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012248 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012250Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012251done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012252
12253static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012254unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012256 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012257 Py_UCS4 fillchar = ' ';
12258
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012259 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260 return NULL;
12261
Benjamin Petersonbac79492012-01-14 13:34:47 -050012262 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012263 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264
Victor Stinnerc4b49542011-12-11 22:44:26 +010012265 if (PyUnicode_GET_LENGTH(self) >= width)
12266 return unicode_result_unchanged(self);
12267
12268 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012269}
12270
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012271PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012272 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012273\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012274Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012275
12276static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012277unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012279 if (PyUnicode_READY(self) == -1)
12280 return NULL;
12281 if (PyUnicode_IS_ASCII(self))
12282 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012283 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012284}
12285
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012286#define LEFTSTRIP 0
12287#define RIGHTSTRIP 1
12288#define BOTHSTRIP 2
12289
12290/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012291static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012292
12293#define STRIPNAME(i) (stripformat[i]+3)
12294
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012295/* externally visible for str.strip(unicode) */
12296PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012297_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012298{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012299 void *data;
12300 int kind;
12301 Py_ssize_t i, j, len;
12302 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012303 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12306 return NULL;
12307
12308 kind = PyUnicode_KIND(self);
12309 data = PyUnicode_DATA(self);
12310 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012311 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012312 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12313 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012314 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012315
Benjamin Peterson14339b62009-01-31 16:36:08 +000012316 i = 0;
12317 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012318 while (i < len) {
12319 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12320 if (!BLOOM(sepmask, ch))
12321 break;
12322 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12323 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012324 i++;
12325 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012326 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012327
Benjamin Peterson14339b62009-01-31 16:36:08 +000012328 j = len;
12329 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012330 j--;
12331 while (j >= i) {
12332 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12333 if (!BLOOM(sepmask, ch))
12334 break;
12335 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12336 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012337 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012338 }
12339
Benjamin Peterson29060642009-01-31 22:14:21 +000012340 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012341 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012342
Victor Stinner7931d9a2011-11-04 00:22:48 +010012343 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012344}
12345
12346PyObject*
12347PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12348{
12349 unsigned char *data;
12350 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012351 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352
Victor Stinnerde636f32011-10-01 03:55:54 +020012353 if (PyUnicode_READY(self) == -1)
12354 return NULL;
12355
Victor Stinner684d5fd2012-05-03 02:32:34 +020012356 length = PyUnicode_GET_LENGTH(self);
12357 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012358
Victor Stinner684d5fd2012-05-03 02:32:34 +020012359 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012360 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361
Victor Stinnerde636f32011-10-01 03:55:54 +020012362 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012363 PyErr_SetString(PyExc_IndexError, "string index out of range");
12364 return NULL;
12365 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012366 if (start >= length || end < start)
12367 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012368
Victor Stinner684d5fd2012-05-03 02:32:34 +020012369 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012370 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012371 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012372 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012373 }
12374 else {
12375 kind = PyUnicode_KIND(self);
12376 data = PyUnicode_1BYTE_DATA(self);
12377 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012378 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012379 length);
12380 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012381}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012382
12383static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012384do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012385{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012386 Py_ssize_t len, i, j;
12387
12388 if (PyUnicode_READY(self) == -1)
12389 return NULL;
12390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012391 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012392
Victor Stinnercc7af722013-04-09 22:39:24 +020012393 if (PyUnicode_IS_ASCII(self)) {
12394 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12395
12396 i = 0;
12397 if (striptype != RIGHTSTRIP) {
12398 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012399 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012400 if (!_Py_ascii_whitespace[ch])
12401 break;
12402 i++;
12403 }
12404 }
12405
12406 j = len;
12407 if (striptype != LEFTSTRIP) {
12408 j--;
12409 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012410 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012411 if (!_Py_ascii_whitespace[ch])
12412 break;
12413 j--;
12414 }
12415 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012416 }
12417 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012418 else {
12419 int kind = PyUnicode_KIND(self);
12420 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012421
Victor Stinnercc7af722013-04-09 22:39:24 +020012422 i = 0;
12423 if (striptype != RIGHTSTRIP) {
12424 while (i < len) {
12425 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12426 if (!Py_UNICODE_ISSPACE(ch))
12427 break;
12428 i++;
12429 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012430 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012431
12432 j = len;
12433 if (striptype != LEFTSTRIP) {
12434 j--;
12435 while (j >= i) {
12436 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12437 if (!Py_UNICODE_ISSPACE(ch))
12438 break;
12439 j--;
12440 }
12441 j++;
12442 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012443 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012444
Victor Stinner7931d9a2011-11-04 00:22:48 +010012445 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012446}
12447
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012448
12449static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012450do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012451{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012452 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012453
Serhiy Storchakac6792272013-10-19 21:03:34 +030012454 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012455 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012456
Benjamin Peterson14339b62009-01-31 16:36:08 +000012457 if (sep != NULL && sep != Py_None) {
12458 if (PyUnicode_Check(sep))
12459 return _PyUnicode_XStrip(self, striptype, sep);
12460 else {
12461 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012462 "%s arg must be None or str",
12463 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012464 return NULL;
12465 }
12466 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012467
Benjamin Peterson14339b62009-01-31 16:36:08 +000012468 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012469}
12470
12471
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012472PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012473 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012474\n\
12475Return a copy of the string S with leading and trailing\n\
12476whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012477If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012478
12479static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012480unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012481{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012482 if (PyTuple_GET_SIZE(args) == 0)
12483 return do_strip(self, BOTHSTRIP); /* Common case */
12484 else
12485 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012486}
12487
12488
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012489PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012490 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012491\n\
12492Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012493If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012494
12495static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012496unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012497{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012498 if (PyTuple_GET_SIZE(args) == 0)
12499 return do_strip(self, LEFTSTRIP); /* Common case */
12500 else
12501 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012502}
12503
12504
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012505PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012506 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012507\n\
12508Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012509If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012510
12511static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012512unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012513{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012514 if (PyTuple_GET_SIZE(args) == 0)
12515 return do_strip(self, RIGHTSTRIP); /* Common case */
12516 else
12517 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012518}
12519
12520
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012522unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012524 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012525 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526
Serhiy Storchaka05997252013-01-26 12:14:02 +020012527 if (len < 1)
12528 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529
Victor Stinnerc4b49542011-12-11 22:44:26 +010012530 /* no repeat, return original string */
12531 if (len == 1)
12532 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012533
Benjamin Petersonbac79492012-01-14 13:34:47 -050012534 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012535 return NULL;
12536
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012537 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012538 PyErr_SetString(PyExc_OverflowError,
12539 "repeated string is too long");
12540 return NULL;
12541 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012543
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012544 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012545 if (!u)
12546 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012547 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 if (PyUnicode_GET_LENGTH(str) == 1) {
12550 const int kind = PyUnicode_KIND(str);
12551 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012552 if (kind == PyUnicode_1BYTE_KIND) {
12553 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012554 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012555 }
12556 else if (kind == PyUnicode_2BYTE_KIND) {
12557 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012558 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012559 ucs2[n] = fill_char;
12560 } else {
12561 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12562 assert(kind == PyUnicode_4BYTE_KIND);
12563 for (n = 0; n < len; ++n)
12564 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012565 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012566 }
12567 else {
12568 /* number of characters copied this far */
12569 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012570 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012572 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012573 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012574 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012576 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012577 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012578 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012579 }
12580
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012581 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012582 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012583}
12584
Alexander Belopolsky40018472011-02-26 01:02:56 +000012585PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012586PyUnicode_Replace(PyObject *str,
12587 PyObject *substr,
12588 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012589 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012590{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012591 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12592 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012593 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012594 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012595}
12596
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012597PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012598 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599\n\
12600Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012601old replaced by new. If the optional argument count is\n\
12602given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012603
12604static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012605unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012607 PyObject *str1;
12608 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012609 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012611 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012613 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012614 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012615 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012616}
12617
Alexander Belopolsky40018472011-02-26 01:02:56 +000012618static PyObject *
12619unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012620{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012621 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012622 Py_ssize_t isize;
12623 Py_ssize_t osize, squote, dquote, i, o;
12624 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012625 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012626 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012627
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012628 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012629 return NULL;
12630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012631 isize = PyUnicode_GET_LENGTH(unicode);
12632 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 /* Compute length of output, quote characters, and
12635 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012636 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012637 max = 127;
12638 squote = dquote = 0;
12639 ikind = PyUnicode_KIND(unicode);
12640 for (i = 0; i < isize; i++) {
12641 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012642 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012643 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012644 case '\'': squote++; break;
12645 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012646 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012647 incr = 2;
12648 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012649 default:
12650 /* Fast-path ASCII */
12651 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012652 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012654 ;
12655 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012656 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012657 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012658 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012659 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012660 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012662 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012663 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012664 if (osize > PY_SSIZE_T_MAX - incr) {
12665 PyErr_SetString(PyExc_OverflowError,
12666 "string is too long to generate repr");
12667 return NULL;
12668 }
12669 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012670 }
12671
12672 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012673 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012674 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012675 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012676 if (dquote)
12677 /* Both squote and dquote present. Use squote,
12678 and escape them */
12679 osize += squote;
12680 else
12681 quote = '"';
12682 }
Victor Stinner55c08782013-04-14 18:45:39 +020012683 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012684
12685 repr = PyUnicode_New(osize, max);
12686 if (repr == NULL)
12687 return NULL;
12688 okind = PyUnicode_KIND(repr);
12689 odata = PyUnicode_DATA(repr);
12690
12691 PyUnicode_WRITE(okind, odata, 0, quote);
12692 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012693 if (unchanged) {
12694 _PyUnicode_FastCopyCharacters(repr, 1,
12695 unicode, 0,
12696 isize);
12697 }
12698 else {
12699 for (i = 0, o = 1; i < isize; i++) {
12700 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012701
Victor Stinner55c08782013-04-14 18:45:39 +020012702 /* Escape quotes and backslashes */
12703 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012704 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012705 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012706 continue;
12707 }
12708
12709 /* Map special whitespace to '\t', \n', '\r' */
12710 if (ch == '\t') {
12711 PyUnicode_WRITE(okind, odata, o++, '\\');
12712 PyUnicode_WRITE(okind, odata, o++, 't');
12713 }
12714 else if (ch == '\n') {
12715 PyUnicode_WRITE(okind, odata, o++, '\\');
12716 PyUnicode_WRITE(okind, odata, o++, 'n');
12717 }
12718 else if (ch == '\r') {
12719 PyUnicode_WRITE(okind, odata, o++, '\\');
12720 PyUnicode_WRITE(okind, odata, o++, 'r');
12721 }
12722
12723 /* Map non-printable US ASCII to '\xhh' */
12724 else if (ch < ' ' || ch == 0x7F) {
12725 PyUnicode_WRITE(okind, odata, o++, '\\');
12726 PyUnicode_WRITE(okind, odata, o++, 'x');
12727 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12728 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12729 }
12730
12731 /* Copy ASCII characters as-is */
12732 else if (ch < 0x7F) {
12733 PyUnicode_WRITE(okind, odata, o++, ch);
12734 }
12735
12736 /* Non-ASCII characters */
12737 else {
12738 /* Map Unicode whitespace and control characters
12739 (categories Z* and C* except ASCII space)
12740 */
12741 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12742 PyUnicode_WRITE(okind, odata, o++, '\\');
12743 /* Map 8-bit characters to '\xhh' */
12744 if (ch <= 0xff) {
12745 PyUnicode_WRITE(okind, odata, o++, 'x');
12746 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12747 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12748 }
12749 /* Map 16-bit characters to '\uxxxx' */
12750 else if (ch <= 0xffff) {
12751 PyUnicode_WRITE(okind, odata, o++, 'u');
12752 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12753 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12754 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12755 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12756 }
12757 /* Map 21-bit characters to '\U00xxxxxx' */
12758 else {
12759 PyUnicode_WRITE(okind, odata, o++, 'U');
12760 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12761 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12762 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12763 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12764 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12765 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12766 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12767 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12768 }
12769 }
12770 /* Copy characters as-is */
12771 else {
12772 PyUnicode_WRITE(okind, odata, o++, ch);
12773 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012774 }
12775 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012777 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012778 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012779 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780}
12781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012782PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012783 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784\n\
12785Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012786such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787arguments start and end are interpreted as in slice notation.\n\
12788\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012789Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790
12791static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012792unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012794 /* initialize variables to prevent gcc warning */
12795 PyObject *substring = NULL;
12796 Py_ssize_t start = 0;
12797 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012798 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012800 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012801 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012803 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012804 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012805
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012806 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012807
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012808 if (result == -2)
12809 return NULL;
12810
Christian Heimes217cfd12007-12-02 14:31:20 +000012811 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012812}
12813
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012814PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012815 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816\n\
Mariatta577fc042017-04-09 15:17:06 -070012817Return the highest index in S where substring sub is found,\n\
12818such that sub is contained within S[start:end]. Optional\n\
12819arguments start and end are interpreted as in slice notation.\n\
12820\n\
12821Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012822
12823static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012824unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012826 /* initialize variables to prevent gcc warning */
12827 PyObject *substring = NULL;
12828 Py_ssize_t start = 0;
12829 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012830 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012831
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012832 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012833 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012834
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012835 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012836 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012837
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012838 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012839
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012840 if (result == -2)
12841 return NULL;
12842
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843 if (result < 0) {
12844 PyErr_SetString(PyExc_ValueError, "substring not found");
12845 return NULL;
12846 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012847
Christian Heimes217cfd12007-12-02 14:31:20 +000012848 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849}
12850
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012851PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012852 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012854Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012855done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012856
12857static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012858unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012859{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012860 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012861 Py_UCS4 fillchar = ' ';
12862
Victor Stinnere9a29352011-10-01 02:14:59 +020012863 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012864 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012865
Benjamin Petersonbac79492012-01-14 13:34:47 -050012866 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012867 return NULL;
12868
Victor Stinnerc4b49542011-12-11 22:44:26 +010012869 if (PyUnicode_GET_LENGTH(self) >= width)
12870 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012871
Victor Stinnerc4b49542011-12-11 22:44:26 +010012872 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012873}
12874
Alexander Belopolsky40018472011-02-26 01:02:56 +000012875PyObject *
12876PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012878 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012879 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012880
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012881 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012882}
12883
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012884PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012885 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886\n\
12887Return a list of the words in S, using sep as the\n\
12888delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012889splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012890whitespace string is a separator and empty strings are\n\
12891removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892
12893static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012894unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012895{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012896 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012897 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012898 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012899
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012900 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12901 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012902 return NULL;
12903
12904 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012905 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012906
12907 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012908 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012909
12910 PyErr_Format(PyExc_TypeError,
12911 "must be str or None, not %.100s",
12912 Py_TYPE(substring)->tp_name);
12913 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012914}
12915
Thomas Wouters477c8d52006-05-27 19:21:47 +000012916PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012917PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012918{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012919 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012920 int kind1, kind2;
12921 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012922 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012923
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012924 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012925 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012926
Victor Stinner14f8f022011-10-05 20:58:25 +020012927 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012928 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012929 len1 = PyUnicode_GET_LENGTH(str_obj);
12930 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012931 if (kind1 < kind2 || len1 < len2) {
12932 _Py_INCREF_UNICODE_EMPTY();
12933 if (!unicode_empty)
12934 out = NULL;
12935 else {
12936 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12937 Py_DECREF(unicode_empty);
12938 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012939 return out;
12940 }
12941 buf1 = PyUnicode_DATA(str_obj);
12942 buf2 = PyUnicode_DATA(sep_obj);
12943 if (kind2 != kind1) {
12944 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12945 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012946 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012947 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012948
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012949 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012950 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012951 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12952 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12953 else
12954 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012955 break;
12956 case PyUnicode_2BYTE_KIND:
12957 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12958 break;
12959 case PyUnicode_4BYTE_KIND:
12960 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12961 break;
12962 default:
12963 assert(0);
12964 out = 0;
12965 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012966
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012967 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012968 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012969
12970 return out;
12971}
12972
12973
12974PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012975PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012976{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012977 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012978 int kind1, kind2;
12979 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012980 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012981
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012982 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012983 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012984
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012985 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012986 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012987 len1 = PyUnicode_GET_LENGTH(str_obj);
12988 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012989 if (kind1 < kind2 || len1 < len2) {
12990 _Py_INCREF_UNICODE_EMPTY();
12991 if (!unicode_empty)
12992 out = NULL;
12993 else {
12994 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12995 Py_DECREF(unicode_empty);
12996 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012997 return out;
12998 }
12999 buf1 = PyUnicode_DATA(str_obj);
13000 buf2 = PyUnicode_DATA(sep_obj);
13001 if (kind2 != kind1) {
13002 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13003 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013004 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013006
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013007 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013009 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13010 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13011 else
13012 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013013 break;
13014 case PyUnicode_2BYTE_KIND:
13015 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13016 break;
13017 case PyUnicode_4BYTE_KIND:
13018 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13019 break;
13020 default:
13021 assert(0);
13022 out = 0;
13023 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013024
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013025 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013026 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013027
13028 return out;
13029}
13030
13031PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013032 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013033\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013034Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013035the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013036found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013037
13038static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013039unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013040{
Victor Stinner9310abb2011-10-05 00:59:23 +020013041 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013042}
13043
13044PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000013045 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013046\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013047Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013048the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013049separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013050
13051static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013052unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013053{
Victor Stinner9310abb2011-10-05 00:59:23 +020013054 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013055}
13056
Alexander Belopolsky40018472011-02-26 01:02:56 +000013057PyObject *
13058PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013059{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013060 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013061 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013062
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013063 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013064}
13065
13066PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013067 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013068\n\
13069Return a list of the words in S, using sep as the\n\
13070delimiter string, starting at the end of the string and\n\
13071working to the front. If maxsplit is given, at most maxsplit\n\
13072splits are done. If sep is not specified, any whitespace string\n\
13073is a separator.");
13074
13075static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013076unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013077{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013078 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013079 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013080 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013081
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013082 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
13083 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013084 return NULL;
13085
13086 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000013087 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013088
13089 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020013090 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013091
13092 PyErr_Format(PyExc_TypeError,
13093 "must be str or None, not %.100s",
13094 Py_TYPE(substring)->tp_name);
13095 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013096}
13097
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013098PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013099 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100\n\
13101Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000013102Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013103is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104
13105static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013106unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013107{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013108 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000013109 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013111 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
13112 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113 return NULL;
13114
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013115 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116}
13117
13118static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013119PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013121 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122}
13123
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013124PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013125 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013126\n\
13127Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013128and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013129
13130static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013131unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013133 if (PyUnicode_READY(self) == -1)
13134 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013135 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013136}
13137
Larry Hastings61272b72014-01-07 12:41:53 -080013138/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013139
Larry Hastings31826802013-10-19 00:09:25 -070013140@staticmethod
13141str.maketrans as unicode_maketrans
13142
13143 x: object
13144
13145 y: unicode=NULL
13146
13147 z: unicode=NULL
13148
13149 /
13150
13151Return a translation table usable for str.translate().
13152
13153If there is only one argument, it must be a dictionary mapping Unicode
13154ordinals (integers) or characters to Unicode ordinals, strings or None.
13155Character keys will be then converted to ordinals.
13156If there are two arguments, they must be strings of equal length, and
13157in the resulting dictionary, each character in x will be mapped to the
13158character at the same position in y. If there is a third argument, it
13159must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013160[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013161
Larry Hastings31826802013-10-19 00:09:25 -070013162static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013163unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013164/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013165{
Georg Brandlceee0772007-11-27 23:48:05 +000013166 PyObject *new = NULL, *key, *value;
13167 Py_ssize_t i = 0;
13168 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013169
Georg Brandlceee0772007-11-27 23:48:05 +000013170 new = PyDict_New();
13171 if (!new)
13172 return NULL;
13173 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013174 int x_kind, y_kind, z_kind;
13175 void *x_data, *y_data, *z_data;
13176
Georg Brandlceee0772007-11-27 23:48:05 +000013177 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013178 if (!PyUnicode_Check(x)) {
13179 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13180 "be a string if there is a second argument");
13181 goto err;
13182 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013183 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013184 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13185 "arguments must have equal length");
13186 goto err;
13187 }
13188 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013189 x_kind = PyUnicode_KIND(x);
13190 y_kind = PyUnicode_KIND(y);
13191 x_data = PyUnicode_DATA(x);
13192 y_data = PyUnicode_DATA(y);
13193 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13194 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013195 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013196 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013197 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013198 if (!value) {
13199 Py_DECREF(key);
13200 goto err;
13201 }
Georg Brandlceee0772007-11-27 23:48:05 +000013202 res = PyDict_SetItem(new, key, value);
13203 Py_DECREF(key);
13204 Py_DECREF(value);
13205 if (res < 0)
13206 goto err;
13207 }
13208 /* create entries for deleting chars in z */
13209 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013210 z_kind = PyUnicode_KIND(z);
13211 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013212 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013213 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013214 if (!key)
13215 goto err;
13216 res = PyDict_SetItem(new, key, Py_None);
13217 Py_DECREF(key);
13218 if (res < 0)
13219 goto err;
13220 }
13221 }
13222 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013223 int kind;
13224 void *data;
13225
Georg Brandlceee0772007-11-27 23:48:05 +000013226 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013227 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013228 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13229 "to maketrans it must be a dict");
13230 goto err;
13231 }
13232 /* copy entries into the new dict, converting string keys to int keys */
13233 while (PyDict_Next(x, &i, &key, &value)) {
13234 if (PyUnicode_Check(key)) {
13235 /* convert string keys to integer keys */
13236 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013237 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013238 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13239 "table must be of length 1");
13240 goto err;
13241 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013242 kind = PyUnicode_KIND(key);
13243 data = PyUnicode_DATA(key);
13244 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013245 if (!newkey)
13246 goto err;
13247 res = PyDict_SetItem(new, newkey, value);
13248 Py_DECREF(newkey);
13249 if (res < 0)
13250 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013251 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013252 /* just keep integer keys */
13253 if (PyDict_SetItem(new, key, value) < 0)
13254 goto err;
13255 } else {
13256 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13257 "be strings or integers");
13258 goto err;
13259 }
13260 }
13261 }
13262 return new;
13263 err:
13264 Py_DECREF(new);
13265 return NULL;
13266}
13267
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013268PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013269 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013271Return a copy of the string S in which each character has been mapped\n\
13272through the given translation table. The table must implement\n\
13273lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13274mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13275this operation raises LookupError, the character is left untouched.\n\
13276Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013277
13278static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013279unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013280{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013281 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013282}
13283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013284PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013285 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013286\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013287Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013288
13289static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013290unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013291{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013292 if (PyUnicode_READY(self) == -1)
13293 return NULL;
13294 if (PyUnicode_IS_ASCII(self))
13295 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013296 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013297}
13298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013299PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013300 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013301\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013302Pad a numeric string S with zeros on the left, to fill a field\n\
13303of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013304
13305static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013306unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013307{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013308 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013309 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013310 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013311 int kind;
13312 void *data;
13313 Py_UCS4 chr;
13314
Martin v. Löwis18e16552006-02-15 17:27:45 +000013315 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013316 return NULL;
13317
Benjamin Petersonbac79492012-01-14 13:34:47 -050013318 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013319 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013320
Victor Stinnerc4b49542011-12-11 22:44:26 +010013321 if (PyUnicode_GET_LENGTH(self) >= width)
13322 return unicode_result_unchanged(self);
13323
13324 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013325
13326 u = pad(self, fill, 0, '0');
13327
Walter Dörwald068325e2002-04-15 13:36:47 +000013328 if (u == NULL)
13329 return NULL;
13330
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013331 kind = PyUnicode_KIND(u);
13332 data = PyUnicode_DATA(u);
13333 chr = PyUnicode_READ(kind, data, fill);
13334
13335 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013336 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013337 PyUnicode_WRITE(kind, data, 0, chr);
13338 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013339 }
13340
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013341 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013342 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013343}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013344
13345#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013346static PyObject *
13347unicode__decimal2ascii(PyObject *self)
13348{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013349 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013350}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013351#endif
13352
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013353PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013354 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013355\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013356Return True if S starts with the specified prefix, False otherwise.\n\
13357With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013358With optional end, stop comparing S at that position.\n\
13359prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013360
13361static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013362unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013363 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013364{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013365 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013366 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013367 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013368 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013369 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013370
Jesus Ceaac451502011-04-20 17:09:23 +020013371 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013372 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013373 if (PyTuple_Check(subobj)) {
13374 Py_ssize_t i;
13375 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013376 substring = PyTuple_GET_ITEM(subobj, i);
13377 if (!PyUnicode_Check(substring)) {
13378 PyErr_Format(PyExc_TypeError,
13379 "tuple for startswith must only contain str, "
13380 "not %.100s",
13381 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013382 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013383 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013384 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013385 if (result == -1)
13386 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013387 if (result) {
13388 Py_RETURN_TRUE;
13389 }
13390 }
13391 /* nothing matched */
13392 Py_RETURN_FALSE;
13393 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013394 if (!PyUnicode_Check(subobj)) {
13395 PyErr_Format(PyExc_TypeError,
13396 "startswith first arg must be str or "
13397 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013398 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013399 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013400 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013401 if (result == -1)
13402 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013403 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013404}
13405
13406
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013407PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013409\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013410Return True if S ends with the specified suffix, False otherwise.\n\
13411With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013412With optional end, stop comparing S at that position.\n\
13413suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013414
13415static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013416unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013417 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013418{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013419 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013420 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013421 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013422 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013423 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013424
Jesus Ceaac451502011-04-20 17:09:23 +020013425 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013427 if (PyTuple_Check(subobj)) {
13428 Py_ssize_t i;
13429 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013430 substring = PyTuple_GET_ITEM(subobj, i);
13431 if (!PyUnicode_Check(substring)) {
13432 PyErr_Format(PyExc_TypeError,
13433 "tuple for endswith must only contain str, "
13434 "not %.100s",
13435 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013436 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013437 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013438 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013439 if (result == -1)
13440 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013441 if (result) {
13442 Py_RETURN_TRUE;
13443 }
13444 }
13445 Py_RETURN_FALSE;
13446 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013447 if (!PyUnicode_Check(subobj)) {
13448 PyErr_Format(PyExc_TypeError,
13449 "endswith first arg must be str or "
13450 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013451 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013452 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013453 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013454 if (result == -1)
13455 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013456 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013457}
13458
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013459static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013460_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013461{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013462 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13463 writer->data = PyUnicode_DATA(writer->buffer);
13464
13465 if (!writer->readonly) {
13466 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013467 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013468 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013469 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013470 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13471 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13472 writer->kind = PyUnicode_WCHAR_KIND;
13473 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13474
Victor Stinner8f674cc2013-04-17 23:02:17 +020013475 /* Copy-on-write mode: set buffer size to 0 so
13476 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13477 * next write. */
13478 writer->size = 0;
13479 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013480}
13481
Victor Stinnerd3f08822012-05-29 12:57:52 +020013482void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013483_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013484{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013485 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013486
13487 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013488 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013489
13490 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13491 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13492 writer->kind = PyUnicode_WCHAR_KIND;
13493 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013494}
13495
Victor Stinnerd3f08822012-05-29 12:57:52 +020013496int
13497_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13498 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013499{
13500 Py_ssize_t newlen;
13501 PyObject *newbuffer;
13502
Victor Stinner2740e462016-09-06 16:58:36 -070013503 assert(maxchar <= MAX_UNICODE);
13504
Victor Stinnerca9381e2015-09-22 00:58:32 +020013505 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013506 assert((maxchar > writer->maxchar && length >= 0)
13507 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013508
Victor Stinner202fdca2012-05-07 12:47:02 +020013509 if (length > PY_SSIZE_T_MAX - writer->pos) {
13510 PyErr_NoMemory();
13511 return -1;
13512 }
13513 newlen = writer->pos + length;
13514
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013515 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013516
Victor Stinnerd3f08822012-05-29 12:57:52 +020013517 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013518 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013519 if (writer->overallocate
13520 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13521 /* overallocate to limit the number of realloc() */
13522 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013523 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013524 if (newlen < writer->min_length)
13525 newlen = writer->min_length;
13526
Victor Stinnerd3f08822012-05-29 12:57:52 +020013527 writer->buffer = PyUnicode_New(newlen, maxchar);
13528 if (writer->buffer == NULL)
13529 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013530 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013531 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013532 if (writer->overallocate
13533 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13534 /* overallocate to limit the number of realloc() */
13535 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013536 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013537 if (newlen < writer->min_length)
13538 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013539
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013540 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013541 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013542 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013543 newbuffer = PyUnicode_New(newlen, maxchar);
13544 if (newbuffer == NULL)
13545 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013546 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13547 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013548 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013549 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013550 }
13551 else {
13552 newbuffer = resize_compact(writer->buffer, newlen);
13553 if (newbuffer == NULL)
13554 return -1;
13555 }
13556 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013557 }
13558 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013559 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013560 newbuffer = PyUnicode_New(writer->size, maxchar);
13561 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013562 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013563 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13564 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013565 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013566 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013567 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013568 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013569
13570#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013571}
13572
Victor Stinnerca9381e2015-09-22 00:58:32 +020013573int
13574_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13575 enum PyUnicode_Kind kind)
13576{
13577 Py_UCS4 maxchar;
13578
13579 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13580 assert(writer->kind < kind);
13581
13582 switch (kind)
13583 {
13584 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13585 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13586 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13587 default:
13588 assert(0 && "invalid kind");
13589 return -1;
13590 }
13591
13592 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13593}
13594
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013595static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013596_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013597{
Victor Stinner2740e462016-09-06 16:58:36 -070013598 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013599 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13600 return -1;
13601 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13602 writer->pos++;
13603 return 0;
13604}
13605
13606int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013607_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13608{
13609 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13610}
13611
13612int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013613_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13614{
13615 Py_UCS4 maxchar;
13616 Py_ssize_t len;
13617
13618 if (PyUnicode_READY(str) == -1)
13619 return -1;
13620 len = PyUnicode_GET_LENGTH(str);
13621 if (len == 0)
13622 return 0;
13623 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13624 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013625 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013626 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013627 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013628 Py_INCREF(str);
13629 writer->buffer = str;
13630 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013631 writer->pos += len;
13632 return 0;
13633 }
13634 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13635 return -1;
13636 }
13637 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13638 str, 0, len);
13639 writer->pos += len;
13640 return 0;
13641}
13642
Victor Stinnere215d962012-10-06 23:03:36 +020013643int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013644_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13645 Py_ssize_t start, Py_ssize_t end)
13646{
13647 Py_UCS4 maxchar;
13648 Py_ssize_t len;
13649
13650 if (PyUnicode_READY(str) == -1)
13651 return -1;
13652
13653 assert(0 <= start);
13654 assert(end <= PyUnicode_GET_LENGTH(str));
13655 assert(start <= end);
13656
13657 if (end == 0)
13658 return 0;
13659
13660 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13661 return _PyUnicodeWriter_WriteStr(writer, str);
13662
13663 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13664 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13665 else
13666 maxchar = writer->maxchar;
13667 len = end - start;
13668
13669 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13670 return -1;
13671
13672 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13673 str, start, len);
13674 writer->pos += len;
13675 return 0;
13676}
13677
13678int
Victor Stinner4a587072013-11-19 12:54:53 +010013679_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13680 const char *ascii, Py_ssize_t len)
13681{
13682 if (len == -1)
13683 len = strlen(ascii);
13684
13685 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13686
13687 if (writer->buffer == NULL && !writer->overallocate) {
13688 PyObject *str;
13689
13690 str = _PyUnicode_FromASCII(ascii, len);
13691 if (str == NULL)
13692 return -1;
13693
13694 writer->readonly = 1;
13695 writer->buffer = str;
13696 _PyUnicodeWriter_Update(writer);
13697 writer->pos += len;
13698 return 0;
13699 }
13700
13701 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13702 return -1;
13703
13704 switch (writer->kind)
13705 {
13706 case PyUnicode_1BYTE_KIND:
13707 {
13708 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13709 Py_UCS1 *data = writer->data;
13710
Christian Heimesf051e432016-09-13 20:22:02 +020013711 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013712 break;
13713 }
13714 case PyUnicode_2BYTE_KIND:
13715 {
13716 _PyUnicode_CONVERT_BYTES(
13717 Py_UCS1, Py_UCS2,
13718 ascii, ascii + len,
13719 (Py_UCS2 *)writer->data + writer->pos);
13720 break;
13721 }
13722 case PyUnicode_4BYTE_KIND:
13723 {
13724 _PyUnicode_CONVERT_BYTES(
13725 Py_UCS1, Py_UCS4,
13726 ascii, ascii + len,
13727 (Py_UCS4 *)writer->data + writer->pos);
13728 break;
13729 }
13730 default:
13731 assert(0);
13732 }
13733
13734 writer->pos += len;
13735 return 0;
13736}
13737
13738int
13739_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13740 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013741{
13742 Py_UCS4 maxchar;
13743
13744 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13745 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13746 return -1;
13747 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13748 writer->pos += len;
13749 return 0;
13750}
13751
Victor Stinnerd3f08822012-05-29 12:57:52 +020013752PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013753_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013754{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013755 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013756
Victor Stinnerd3f08822012-05-29 12:57:52 +020013757 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013758 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013759 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013760 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013761
13762 str = writer->buffer;
13763 writer->buffer = NULL;
13764
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013765 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013766 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13767 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013768 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013769
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013770 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13771 PyObject *str2;
13772 str2 = resize_compact(str, writer->pos);
13773 if (str2 == NULL) {
13774 Py_DECREF(str);
13775 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013776 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013777 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013778 }
13779
Victor Stinner15a0bd32013-07-08 22:29:55 +020013780 assert(_PyUnicode_CheckConsistency(str, 1));
13781 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013782}
13783
Victor Stinnerd3f08822012-05-29 12:57:52 +020013784void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013785_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013786{
13787 Py_CLEAR(writer->buffer);
13788}
13789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013790#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013791
13792PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013793 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013794\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013795Return a formatted version of S, using substitutions from args and kwargs.\n\
13796The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013797
Eric Smith27bbca62010-11-04 17:06:58 +000013798PyDoc_STRVAR(format_map__doc__,
13799 "S.format_map(mapping) -> str\n\
13800\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013801Return a formatted version of S, using substitutions from mapping.\n\
13802The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013803
Eric Smith4a7d76d2008-05-30 18:10:19 +000013804static PyObject *
13805unicode__format__(PyObject* self, PyObject* args)
13806{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013807 PyObject *format_spec;
13808 _PyUnicodeWriter writer;
13809 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013810
13811 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13812 return NULL;
13813
Victor Stinnerd3f08822012-05-29 12:57:52 +020013814 if (PyUnicode_READY(self) == -1)
13815 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013816 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013817 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13818 self, format_spec, 0,
13819 PyUnicode_GET_LENGTH(format_spec));
13820 if (ret == -1) {
13821 _PyUnicodeWriter_Dealloc(&writer);
13822 return NULL;
13823 }
13824 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013825}
13826
Eric Smith8c663262007-08-25 02:26:07 +000013827PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013828 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013829\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013830Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013831
13832static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013833unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013834{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013835 Py_ssize_t size;
13836
13837 /* If it's a compact object, account for base structure +
13838 character data. */
13839 if (PyUnicode_IS_COMPACT_ASCII(v))
13840 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13841 else if (PyUnicode_IS_COMPACT(v))
13842 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013843 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013844 else {
13845 /* If it is a two-block object, account for base object, and
13846 for character block if present. */
13847 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013848 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013849 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013850 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013851 }
13852 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013853 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013854 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013855 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013856 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013857 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013858
13859 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013860}
13861
13862PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013863 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013864
13865static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013866unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013867{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013868 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013869 if (!copy)
13870 return NULL;
13871 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013872}
13873
Guido van Rossumd57fd912000-03-10 22:53:23 +000013874static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013875 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013876 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013877 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13878 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013879 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13880 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013881 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013882 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13883 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13884 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013885 {"expandtabs", (PyCFunction) unicode_expandtabs,
13886 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013887 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013888 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013889 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13890 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13891 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013892 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013893 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13894 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13895 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013896 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013897 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013898 {"splitlines", (PyCFunction) unicode_splitlines,
13899 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013900 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013901 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13902 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13903 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13904 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13905 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13906 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13907 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13908 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13909 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13910 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13911 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13912 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13913 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13914 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013915 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013916 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013917 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013918 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013919 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013920 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013921 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013922 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013923#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013924 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013925 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013926#endif
13927
Benjamin Peterson14339b62009-01-31 16:36:08 +000013928 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013929 {NULL, NULL}
13930};
13931
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013932static PyObject *
13933unicode_mod(PyObject *v, PyObject *w)
13934{
Brian Curtindfc80e32011-08-10 20:28:54 -050013935 if (!PyUnicode_Check(v))
13936 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013937 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013938}
13939
13940static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013941 0, /*nb_add*/
13942 0, /*nb_subtract*/
13943 0, /*nb_multiply*/
13944 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013945};
13946
Guido van Rossumd57fd912000-03-10 22:53:23 +000013947static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013948 (lenfunc) unicode_length, /* sq_length */
13949 PyUnicode_Concat, /* sq_concat */
13950 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13951 (ssizeargfunc) unicode_getitem, /* sq_item */
13952 0, /* sq_slice */
13953 0, /* sq_ass_item */
13954 0, /* sq_ass_slice */
13955 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013956};
13957
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013958static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013959unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013960{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013961 if (PyUnicode_READY(self) == -1)
13962 return NULL;
13963
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013964 if (PyIndex_Check(item)) {
13965 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013966 if (i == -1 && PyErr_Occurred())
13967 return NULL;
13968 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013969 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013970 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013971 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013972 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013973 PyObject *result;
13974 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013975 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013976 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013977
Serhiy Storchakac26b19d2017-04-08 11:18:14 +030013978 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013979 return NULL;
13980 }
Serhiy Storchakac26b19d2017-04-08 11:18:14 +030013981 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13982 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013983
13984 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013985 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013986 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013987 slicelength == PyUnicode_GET_LENGTH(self)) {
13988 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013989 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013990 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013991 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013992 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013993 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013994 src_kind = PyUnicode_KIND(self);
13995 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013996 if (!PyUnicode_IS_ASCII(self)) {
13997 kind_limit = kind_maxchar_limit(src_kind);
13998 max_char = 0;
13999 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14000 ch = PyUnicode_READ(src_kind, src_data, cur);
14001 if (ch > max_char) {
14002 max_char = ch;
14003 if (max_char >= kind_limit)
14004 break;
14005 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014006 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014007 }
Victor Stinner55c99112011-10-13 01:17:06 +020014008 else
14009 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014010 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014011 if (result == NULL)
14012 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014013 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014014 dest_data = PyUnicode_DATA(result);
14015
14016 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014017 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14018 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014019 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014020 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014021 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014022 } else {
14023 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14024 return NULL;
14025 }
14026}
14027
14028static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014029 (lenfunc)unicode_length, /* mp_length */
14030 (binaryfunc)unicode_subscript, /* mp_subscript */
14031 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014032};
14033
Guido van Rossumd57fd912000-03-10 22:53:23 +000014034
Guido van Rossumd57fd912000-03-10 22:53:23 +000014035/* Helpers for PyUnicode_Format() */
14036
Victor Stinnera47082312012-10-04 02:19:54 +020014037struct unicode_formatter_t {
14038 PyObject *args;
14039 int args_owned;
14040 Py_ssize_t arglen, argidx;
14041 PyObject *dict;
14042
14043 enum PyUnicode_Kind fmtkind;
14044 Py_ssize_t fmtcnt, fmtpos;
14045 void *fmtdata;
14046 PyObject *fmtstr;
14047
14048 _PyUnicodeWriter writer;
14049};
14050
14051struct unicode_format_arg_t {
14052 Py_UCS4 ch;
14053 int flags;
14054 Py_ssize_t width;
14055 int prec;
14056 int sign;
14057};
14058
Guido van Rossumd57fd912000-03-10 22:53:23 +000014059static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014060unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014061{
Victor Stinnera47082312012-10-04 02:19:54 +020014062 Py_ssize_t argidx = ctx->argidx;
14063
14064 if (argidx < ctx->arglen) {
14065 ctx->argidx++;
14066 if (ctx->arglen < 0)
14067 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014068 else
Victor Stinnera47082312012-10-04 02:19:54 +020014069 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014070 }
14071 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014072 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014073 return NULL;
14074}
14075
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014076/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014077
Victor Stinnera47082312012-10-04 02:19:54 +020014078/* Format a float into the writer if the writer is not NULL, or into *p_output
14079 otherwise.
14080
14081 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014082static int
Victor Stinnera47082312012-10-04 02:19:54 +020014083formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14084 PyObject **p_output,
14085 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014086{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014087 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014088 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014089 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014090 int prec;
14091 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014092
Guido van Rossumd57fd912000-03-10 22:53:23 +000014093 x = PyFloat_AsDouble(v);
14094 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014095 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014096
Victor Stinnera47082312012-10-04 02:19:54 +020014097 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014098 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014099 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014100
Victor Stinnera47082312012-10-04 02:19:54 +020014101 if (arg->flags & F_ALT)
14102 dtoa_flags = Py_DTSF_ALT;
14103 else
14104 dtoa_flags = 0;
14105 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014106 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014107 return -1;
14108 len = strlen(p);
14109 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014110 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014111 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014112 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014113 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014114 }
14115 else
14116 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014117 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014118 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014119}
14120
Victor Stinnerd0880d52012-04-27 23:40:13 +020014121/* formatlong() emulates the format codes d, u, o, x and X, and
14122 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14123 * Python's regular ints.
14124 * Return value: a new PyUnicodeObject*, or NULL if error.
14125 * The output string is of the form
14126 * "-"? ("0x" | "0X")? digit+
14127 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14128 * set in flags. The case of hex digits will be correct,
14129 * There will be at least prec digits, zero-filled on the left if
14130 * necessary to get that many.
14131 * val object to be converted
14132 * flags bitmask of format flags; only F_ALT is looked at
14133 * prec minimum number of digits; 0-fill on left if needed
14134 * type a character in [duoxX]; u acts the same as d
14135 *
14136 * CAUTION: o, x and X conversions on regular ints can never
14137 * produce a '-' sign, but can for Python's unbounded ints.
14138 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014139PyObject *
14140_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014141{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014142 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014143 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014144 Py_ssize_t i;
14145 int sign; /* 1 if '-', else 0 */
14146 int len; /* number of characters */
14147 Py_ssize_t llen;
14148 int numdigits; /* len == numnondigits + numdigits */
14149 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014150
Victor Stinnerd0880d52012-04-27 23:40:13 +020014151 /* Avoid exceeding SSIZE_T_MAX */
14152 if (prec > INT_MAX-3) {
14153 PyErr_SetString(PyExc_OverflowError,
14154 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014155 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014156 }
14157
14158 assert(PyLong_Check(val));
14159
14160 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014161 default:
14162 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014163 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014164 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014165 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014166 /* int and int subclasses should print numerically when a numeric */
14167 /* format code is used (see issue18780) */
14168 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014169 break;
14170 case 'o':
14171 numnondigits = 2;
14172 result = PyNumber_ToBase(val, 8);
14173 break;
14174 case 'x':
14175 case 'X':
14176 numnondigits = 2;
14177 result = PyNumber_ToBase(val, 16);
14178 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014179 }
14180 if (!result)
14181 return NULL;
14182
14183 assert(unicode_modifiable(result));
14184 assert(PyUnicode_IS_READY(result));
14185 assert(PyUnicode_IS_ASCII(result));
14186
14187 /* To modify the string in-place, there can only be one reference. */
14188 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014189 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014190 PyErr_BadInternalCall();
14191 return NULL;
14192 }
14193 buf = PyUnicode_DATA(result);
14194 llen = PyUnicode_GET_LENGTH(result);
14195 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014196 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014197 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014198 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014199 return NULL;
14200 }
14201 len = (int)llen;
14202 sign = buf[0] == '-';
14203 numnondigits += sign;
14204 numdigits = len - numnondigits;
14205 assert(numdigits > 0);
14206
14207 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014208 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014209 (type == 'o' || type == 'x' || type == 'X'))) {
14210 assert(buf[sign] == '0');
14211 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14212 buf[sign+1] == 'o');
14213 numnondigits -= 2;
14214 buf += 2;
14215 len -= 2;
14216 if (sign)
14217 buf[0] = '-';
14218 assert(len == numnondigits + numdigits);
14219 assert(numdigits > 0);
14220 }
14221
14222 /* Fill with leading zeroes to meet minimum width. */
14223 if (prec > numdigits) {
14224 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14225 numnondigits + prec);
14226 char *b1;
14227 if (!r1) {
14228 Py_DECREF(result);
14229 return NULL;
14230 }
14231 b1 = PyBytes_AS_STRING(r1);
14232 for (i = 0; i < numnondigits; ++i)
14233 *b1++ = *buf++;
14234 for (i = 0; i < prec - numdigits; i++)
14235 *b1++ = '0';
14236 for (i = 0; i < numdigits; i++)
14237 *b1++ = *buf++;
14238 *b1 = '\0';
14239 Py_DECREF(result);
14240 result = r1;
14241 buf = PyBytes_AS_STRING(result);
14242 len = numnondigits + prec;
14243 }
14244
14245 /* Fix up case for hex conversions. */
14246 if (type == 'X') {
14247 /* Need to convert all lower case letters to upper case.
14248 and need to convert 0x to 0X (and -0x to -0X). */
14249 for (i = 0; i < len; i++)
14250 if (buf[i] >= 'a' && buf[i] <= 'x')
14251 buf[i] -= 'a'-'A';
14252 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014253 if (!PyUnicode_Check(result)
14254 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014255 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014256 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014257 Py_DECREF(result);
14258 result = unicode;
14259 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014260 else if (len != PyUnicode_GET_LENGTH(result)) {
14261 if (PyUnicode_Resize(&result, len) < 0)
14262 Py_CLEAR(result);
14263 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014264 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014265}
14266
Ethan Furmandf3ed242014-01-05 06:50:30 -080014267/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014268 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014269 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014270 * -1 and raise an exception on error */
14271static int
Victor Stinnera47082312012-10-04 02:19:54 +020014272mainformatlong(PyObject *v,
14273 struct unicode_format_arg_t *arg,
14274 PyObject **p_output,
14275 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014276{
14277 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014278 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014279
14280 if (!PyNumber_Check(v))
14281 goto wrongtype;
14282
Ethan Furman9ab74802014-03-21 06:38:46 -070014283 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014284 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014285 if (type == 'o' || type == 'x' || type == 'X') {
14286 iobj = PyNumber_Index(v);
14287 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014288 if (PyErr_ExceptionMatches(PyExc_TypeError))
14289 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014290 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014291 }
14292 }
14293 else {
14294 iobj = PyNumber_Long(v);
14295 if (iobj == NULL ) {
14296 if (PyErr_ExceptionMatches(PyExc_TypeError))
14297 goto wrongtype;
14298 return -1;
14299 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014300 }
14301 assert(PyLong_Check(iobj));
14302 }
14303 else {
14304 iobj = v;
14305 Py_INCREF(iobj);
14306 }
14307
14308 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014309 && arg->width == -1 && arg->prec == -1
14310 && !(arg->flags & (F_SIGN | F_BLANK))
14311 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014312 {
14313 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014314 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014315 int base;
14316
Victor Stinnera47082312012-10-04 02:19:54 +020014317 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014318 {
14319 default:
14320 assert(0 && "'type' not in [diuoxX]");
14321 case 'd':
14322 case 'i':
14323 case 'u':
14324 base = 10;
14325 break;
14326 case 'o':
14327 base = 8;
14328 break;
14329 case 'x':
14330 case 'X':
14331 base = 16;
14332 break;
14333 }
14334
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014335 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14336 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014337 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014338 }
14339 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014340 return 1;
14341 }
14342
Ethan Furmanb95b5612015-01-23 20:05:18 -080014343 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014344 Py_DECREF(iobj);
14345 if (res == NULL)
14346 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014347 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014348 return 0;
14349
14350wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014351 switch(type)
14352 {
14353 case 'o':
14354 case 'x':
14355 case 'X':
14356 PyErr_Format(PyExc_TypeError,
14357 "%%%c format: an integer is required, "
14358 "not %.200s",
14359 type, Py_TYPE(v)->tp_name);
14360 break;
14361 default:
14362 PyErr_Format(PyExc_TypeError,
14363 "%%%c format: a number is required, "
14364 "not %.200s",
14365 type, Py_TYPE(v)->tp_name);
14366 break;
14367 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014368 return -1;
14369}
14370
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014371static Py_UCS4
14372formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014373{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014374 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014375 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014376 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014377 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014378 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014379 goto onError;
14380 }
14381 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014382 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014383 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014384 /* make sure number is a type of integer */
14385 if (!PyLong_Check(v)) {
14386 iobj = PyNumber_Index(v);
14387 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014388 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014389 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014390 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014391 Py_DECREF(iobj);
14392 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014393 else {
14394 x = PyLong_AsLong(v);
14395 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014396 if (x == -1 && PyErr_Occurred())
14397 goto onError;
14398
Victor Stinner8faf8212011-12-08 22:14:11 +010014399 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014400 PyErr_SetString(PyExc_OverflowError,
14401 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014402 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014403 }
14404
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014405 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014406 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014407
Benjamin Peterson29060642009-01-31 22:14:21 +000014408 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014409 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014410 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014411 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014412}
14413
Victor Stinnera47082312012-10-04 02:19:54 +020014414/* Parse options of an argument: flags, width, precision.
14415 Handle also "%(name)" syntax.
14416
14417 Return 0 if the argument has been formatted into arg->str.
14418 Return 1 if the argument has been written into ctx->writer,
14419 Raise an exception and return -1 on error. */
14420static int
14421unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14422 struct unicode_format_arg_t *arg)
14423{
14424#define FORMAT_READ(ctx) \
14425 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14426
14427 PyObject *v;
14428
Victor Stinnera47082312012-10-04 02:19:54 +020014429 if (arg->ch == '(') {
14430 /* Get argument value from a dictionary. Example: "%(name)s". */
14431 Py_ssize_t keystart;
14432 Py_ssize_t keylen;
14433 PyObject *key;
14434 int pcount = 1;
14435
14436 if (ctx->dict == NULL) {
14437 PyErr_SetString(PyExc_TypeError,
14438 "format requires a mapping");
14439 return -1;
14440 }
14441 ++ctx->fmtpos;
14442 --ctx->fmtcnt;
14443 keystart = ctx->fmtpos;
14444 /* Skip over balanced parentheses */
14445 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14446 arg->ch = FORMAT_READ(ctx);
14447 if (arg->ch == ')')
14448 --pcount;
14449 else if (arg->ch == '(')
14450 ++pcount;
14451 ctx->fmtpos++;
14452 }
14453 keylen = ctx->fmtpos - keystart - 1;
14454 if (ctx->fmtcnt < 0 || pcount > 0) {
14455 PyErr_SetString(PyExc_ValueError,
14456 "incomplete format key");
14457 return -1;
14458 }
14459 key = PyUnicode_Substring(ctx->fmtstr,
14460 keystart, keystart + keylen);
14461 if (key == NULL)
14462 return -1;
14463 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014464 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014465 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014466 }
14467 ctx->args = PyObject_GetItem(ctx->dict, key);
14468 Py_DECREF(key);
14469 if (ctx->args == NULL)
14470 return -1;
14471 ctx->args_owned = 1;
14472 ctx->arglen = -1;
14473 ctx->argidx = -2;
14474 }
14475
14476 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014477 while (--ctx->fmtcnt >= 0) {
14478 arg->ch = FORMAT_READ(ctx);
14479 ctx->fmtpos++;
14480 switch (arg->ch) {
14481 case '-': arg->flags |= F_LJUST; continue;
14482 case '+': arg->flags |= F_SIGN; continue;
14483 case ' ': arg->flags |= F_BLANK; continue;
14484 case '#': arg->flags |= F_ALT; continue;
14485 case '0': arg->flags |= F_ZERO; continue;
14486 }
14487 break;
14488 }
14489
14490 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014491 if (arg->ch == '*') {
14492 v = unicode_format_getnextarg(ctx);
14493 if (v == NULL)
14494 return -1;
14495 if (!PyLong_Check(v)) {
14496 PyErr_SetString(PyExc_TypeError,
14497 "* wants int");
14498 return -1;
14499 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014500 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014501 if (arg->width == -1 && PyErr_Occurred())
14502 return -1;
14503 if (arg->width < 0) {
14504 arg->flags |= F_LJUST;
14505 arg->width = -arg->width;
14506 }
14507 if (--ctx->fmtcnt >= 0) {
14508 arg->ch = FORMAT_READ(ctx);
14509 ctx->fmtpos++;
14510 }
14511 }
14512 else if (arg->ch >= '0' && arg->ch <= '9') {
14513 arg->width = arg->ch - '0';
14514 while (--ctx->fmtcnt >= 0) {
14515 arg->ch = FORMAT_READ(ctx);
14516 ctx->fmtpos++;
14517 if (arg->ch < '0' || arg->ch > '9')
14518 break;
14519 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14520 mixing signed and unsigned comparison. Since arg->ch is between
14521 '0' and '9', casting to int is safe. */
14522 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14523 PyErr_SetString(PyExc_ValueError,
14524 "width too big");
14525 return -1;
14526 }
14527 arg->width = arg->width*10 + (arg->ch - '0');
14528 }
14529 }
14530
14531 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014532 if (arg->ch == '.') {
14533 arg->prec = 0;
14534 if (--ctx->fmtcnt >= 0) {
14535 arg->ch = FORMAT_READ(ctx);
14536 ctx->fmtpos++;
14537 }
14538 if (arg->ch == '*') {
14539 v = unicode_format_getnextarg(ctx);
14540 if (v == NULL)
14541 return -1;
14542 if (!PyLong_Check(v)) {
14543 PyErr_SetString(PyExc_TypeError,
14544 "* wants int");
14545 return -1;
14546 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014547 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014548 if (arg->prec == -1 && PyErr_Occurred())
14549 return -1;
14550 if (arg->prec < 0)
14551 arg->prec = 0;
14552 if (--ctx->fmtcnt >= 0) {
14553 arg->ch = FORMAT_READ(ctx);
14554 ctx->fmtpos++;
14555 }
14556 }
14557 else if (arg->ch >= '0' && arg->ch <= '9') {
14558 arg->prec = arg->ch - '0';
14559 while (--ctx->fmtcnt >= 0) {
14560 arg->ch = FORMAT_READ(ctx);
14561 ctx->fmtpos++;
14562 if (arg->ch < '0' || arg->ch > '9')
14563 break;
14564 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14565 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014566 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014567 return -1;
14568 }
14569 arg->prec = arg->prec*10 + (arg->ch - '0');
14570 }
14571 }
14572 }
14573
14574 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14575 if (ctx->fmtcnt >= 0) {
14576 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14577 if (--ctx->fmtcnt >= 0) {
14578 arg->ch = FORMAT_READ(ctx);
14579 ctx->fmtpos++;
14580 }
14581 }
14582 }
14583 if (ctx->fmtcnt < 0) {
14584 PyErr_SetString(PyExc_ValueError,
14585 "incomplete format");
14586 return -1;
14587 }
14588 return 0;
14589
14590#undef FORMAT_READ
14591}
14592
14593/* Format one argument. Supported conversion specifiers:
14594
14595 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014596 - "i", "d", "u": int or float
14597 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014598 - "e", "E", "f", "F", "g", "G": float
14599 - "c": int or str (1 character)
14600
Victor Stinner8dbd4212012-12-04 09:30:24 +010014601 When possible, the output is written directly into the Unicode writer
14602 (ctx->writer). A string is created when padding is required.
14603
Victor Stinnera47082312012-10-04 02:19:54 +020014604 Return 0 if the argument has been formatted into *p_str,
14605 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014606 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014607static int
14608unicode_format_arg_format(struct unicode_formatter_t *ctx,
14609 struct unicode_format_arg_t *arg,
14610 PyObject **p_str)
14611{
14612 PyObject *v;
14613 _PyUnicodeWriter *writer = &ctx->writer;
14614
14615 if (ctx->fmtcnt == 0)
14616 ctx->writer.overallocate = 0;
14617
14618 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014619 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014620 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014621 return 1;
14622 }
14623
14624 v = unicode_format_getnextarg(ctx);
14625 if (v == NULL)
14626 return -1;
14627
Victor Stinnera47082312012-10-04 02:19:54 +020014628
14629 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014630 case 's':
14631 case 'r':
14632 case 'a':
14633 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14634 /* Fast path */
14635 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14636 return -1;
14637 return 1;
14638 }
14639
14640 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14641 *p_str = v;
14642 Py_INCREF(*p_str);
14643 }
14644 else {
14645 if (arg->ch == 's')
14646 *p_str = PyObject_Str(v);
14647 else if (arg->ch == 'r')
14648 *p_str = PyObject_Repr(v);
14649 else
14650 *p_str = PyObject_ASCII(v);
14651 }
14652 break;
14653
14654 case 'i':
14655 case 'd':
14656 case 'u':
14657 case 'o':
14658 case 'x':
14659 case 'X':
14660 {
14661 int ret = mainformatlong(v, arg, p_str, writer);
14662 if (ret != 0)
14663 return ret;
14664 arg->sign = 1;
14665 break;
14666 }
14667
14668 case 'e':
14669 case 'E':
14670 case 'f':
14671 case 'F':
14672 case 'g':
14673 case 'G':
14674 if (arg->width == -1 && arg->prec == -1
14675 && !(arg->flags & (F_SIGN | F_BLANK)))
14676 {
14677 /* Fast path */
14678 if (formatfloat(v, arg, NULL, writer) == -1)
14679 return -1;
14680 return 1;
14681 }
14682
14683 arg->sign = 1;
14684 if (formatfloat(v, arg, p_str, NULL) == -1)
14685 return -1;
14686 break;
14687
14688 case 'c':
14689 {
14690 Py_UCS4 ch = formatchar(v);
14691 if (ch == (Py_UCS4) -1)
14692 return -1;
14693 if (arg->width == -1 && arg->prec == -1) {
14694 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014695 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014696 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014697 return 1;
14698 }
14699 *p_str = PyUnicode_FromOrdinal(ch);
14700 break;
14701 }
14702
14703 default:
14704 PyErr_Format(PyExc_ValueError,
14705 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014706 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014707 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14708 (int)arg->ch,
14709 ctx->fmtpos - 1);
14710 return -1;
14711 }
14712 if (*p_str == NULL)
14713 return -1;
14714 assert (PyUnicode_Check(*p_str));
14715 return 0;
14716}
14717
14718static int
14719unicode_format_arg_output(struct unicode_formatter_t *ctx,
14720 struct unicode_format_arg_t *arg,
14721 PyObject *str)
14722{
14723 Py_ssize_t len;
14724 enum PyUnicode_Kind kind;
14725 void *pbuf;
14726 Py_ssize_t pindex;
14727 Py_UCS4 signchar;
14728 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014729 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014730 Py_ssize_t sublen;
14731 _PyUnicodeWriter *writer = &ctx->writer;
14732 Py_UCS4 fill;
14733
14734 fill = ' ';
14735 if (arg->sign && arg->flags & F_ZERO)
14736 fill = '0';
14737
14738 if (PyUnicode_READY(str) == -1)
14739 return -1;
14740
14741 len = PyUnicode_GET_LENGTH(str);
14742 if ((arg->width == -1 || arg->width <= len)
14743 && (arg->prec == -1 || arg->prec >= len)
14744 && !(arg->flags & (F_SIGN | F_BLANK)))
14745 {
14746 /* Fast path */
14747 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14748 return -1;
14749 return 0;
14750 }
14751
14752 /* Truncate the string for "s", "r" and "a" formats
14753 if the precision is set */
14754 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14755 if (arg->prec >= 0 && len > arg->prec)
14756 len = arg->prec;
14757 }
14758
14759 /* Adjust sign and width */
14760 kind = PyUnicode_KIND(str);
14761 pbuf = PyUnicode_DATA(str);
14762 pindex = 0;
14763 signchar = '\0';
14764 if (arg->sign) {
14765 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14766 if (ch == '-' || ch == '+') {
14767 signchar = ch;
14768 len--;
14769 pindex++;
14770 }
14771 else if (arg->flags & F_SIGN)
14772 signchar = '+';
14773 else if (arg->flags & F_BLANK)
14774 signchar = ' ';
14775 else
14776 arg->sign = 0;
14777 }
14778 if (arg->width < len)
14779 arg->width = len;
14780
14781 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014782 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014783 if (!(arg->flags & F_LJUST)) {
14784 if (arg->sign) {
14785 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014786 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014787 }
14788 else {
14789 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014790 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014791 }
14792 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014793 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14794 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014795 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014796 }
14797
Victor Stinnera47082312012-10-04 02:19:54 +020014798 buflen = arg->width;
14799 if (arg->sign && len == arg->width)
14800 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014801 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014802 return -1;
14803
14804 /* Write the sign if needed */
14805 if (arg->sign) {
14806 if (fill != ' ') {
14807 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14808 writer->pos += 1;
14809 }
14810 if (arg->width > len)
14811 arg->width--;
14812 }
14813
14814 /* Write the numeric prefix for "x", "X" and "o" formats
14815 if the alternate form is used.
14816 For example, write "0x" for the "%#x" format. */
14817 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14818 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14819 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14820 if (fill != ' ') {
14821 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14822 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14823 writer->pos += 2;
14824 pindex += 2;
14825 }
14826 arg->width -= 2;
14827 if (arg->width < 0)
14828 arg->width = 0;
14829 len -= 2;
14830 }
14831
14832 /* Pad left with the fill character if needed */
14833 if (arg->width > len && !(arg->flags & F_LJUST)) {
14834 sublen = arg->width - len;
14835 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14836 writer->pos += sublen;
14837 arg->width = len;
14838 }
14839
14840 /* If padding with spaces: write sign if needed and/or numeric prefix if
14841 the alternate form is used */
14842 if (fill == ' ') {
14843 if (arg->sign) {
14844 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14845 writer->pos += 1;
14846 }
14847 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14848 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14849 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14850 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14851 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14852 writer->pos += 2;
14853 pindex += 2;
14854 }
14855 }
14856
14857 /* Write characters */
14858 if (len) {
14859 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14860 str, pindex, len);
14861 writer->pos += len;
14862 }
14863
14864 /* Pad right with the fill character if needed */
14865 if (arg->width > len) {
14866 sublen = arg->width - len;
14867 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14868 writer->pos += sublen;
14869 }
14870 return 0;
14871}
14872
14873/* Helper of PyUnicode_Format(): format one arg.
14874 Return 0 on success, raise an exception and return -1 on error. */
14875static int
14876unicode_format_arg(struct unicode_formatter_t *ctx)
14877{
14878 struct unicode_format_arg_t arg;
14879 PyObject *str;
14880 int ret;
14881
Victor Stinner8dbd4212012-12-04 09:30:24 +010014882 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14883 arg.flags = 0;
14884 arg.width = -1;
14885 arg.prec = -1;
14886 arg.sign = 0;
14887 str = NULL;
14888
Victor Stinnera47082312012-10-04 02:19:54 +020014889 ret = unicode_format_arg_parse(ctx, &arg);
14890 if (ret == -1)
14891 return -1;
14892
14893 ret = unicode_format_arg_format(ctx, &arg, &str);
14894 if (ret == -1)
14895 return -1;
14896
14897 if (ret != 1) {
14898 ret = unicode_format_arg_output(ctx, &arg, str);
14899 Py_DECREF(str);
14900 if (ret == -1)
14901 return -1;
14902 }
14903
14904 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14905 PyErr_SetString(PyExc_TypeError,
14906 "not all arguments converted during string formatting");
14907 return -1;
14908 }
14909 return 0;
14910}
14911
Alexander Belopolsky40018472011-02-26 01:02:56 +000014912PyObject *
14913PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014914{
Victor Stinnera47082312012-10-04 02:19:54 +020014915 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014916
Guido van Rossumd57fd912000-03-10 22:53:23 +000014917 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014918 PyErr_BadInternalCall();
14919 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014920 }
Victor Stinnera47082312012-10-04 02:19:54 +020014921
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014922 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014923 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014924
14925 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014926 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14927 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14928 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14929 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014930
Victor Stinner8f674cc2013-04-17 23:02:17 +020014931 _PyUnicodeWriter_Init(&ctx.writer);
14932 ctx.writer.min_length = ctx.fmtcnt + 100;
14933 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014934
Guido van Rossumd57fd912000-03-10 22:53:23 +000014935 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014936 ctx.arglen = PyTuple_Size(args);
14937 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014938 }
14939 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014940 ctx.arglen = -1;
14941 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014942 }
Victor Stinnera47082312012-10-04 02:19:54 +020014943 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014944 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014945 ctx.dict = args;
14946 else
14947 ctx.dict = NULL;
14948 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014949
Victor Stinnera47082312012-10-04 02:19:54 +020014950 while (--ctx.fmtcnt >= 0) {
14951 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014952 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014953
14954 nonfmtpos = ctx.fmtpos++;
14955 while (ctx.fmtcnt >= 0 &&
14956 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14957 ctx.fmtpos++;
14958 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014959 }
Victor Stinnera47082312012-10-04 02:19:54 +020014960 if (ctx.fmtcnt < 0) {
14961 ctx.fmtpos--;
14962 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014963 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014964
Victor Stinnercfc4c132013-04-03 01:48:39 +020014965 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14966 nonfmtpos, ctx.fmtpos) < 0)
14967 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014968 }
14969 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014970 ctx.fmtpos++;
14971 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014972 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014973 }
14974 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014975
Victor Stinnera47082312012-10-04 02:19:54 +020014976 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014977 PyErr_SetString(PyExc_TypeError,
14978 "not all arguments converted during string formatting");
14979 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014980 }
14981
Victor Stinnera47082312012-10-04 02:19:54 +020014982 if (ctx.args_owned) {
14983 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014984 }
Victor Stinnera47082312012-10-04 02:19:54 +020014985 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014986
Benjamin Peterson29060642009-01-31 22:14:21 +000014987 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014988 _PyUnicodeWriter_Dealloc(&ctx.writer);
14989 if (ctx.args_owned) {
14990 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014991 }
14992 return NULL;
14993}
14994
Jeremy Hylton938ace62002-07-17 16:30:39 +000014995static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014996unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14997
Tim Peters6d6c1a32001-08-02 04:15:00 +000014998static PyObject *
14999unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15000{
Benjamin Peterson29060642009-01-31 22:14:21 +000015001 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015002 static char *kwlist[] = {"object", "encoding", "errors", 0};
15003 char *encoding = NULL;
15004 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000015005
Benjamin Peterson14339b62009-01-31 16:36:08 +000015006 if (type != &PyUnicode_Type)
15007 return unicode_subtype_new(type, args, kwds);
15008 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015009 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015010 return NULL;
15011 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015012 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015013 if (encoding == NULL && errors == NULL)
15014 return PyObject_Str(x);
15015 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015016 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015017}
15018
Guido van Rossume023fe02001-08-30 03:12:59 +000015019static PyObject *
15020unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15021{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015022 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015023 Py_ssize_t length, char_size;
15024 int share_wstr, share_utf8;
15025 unsigned int kind;
15026 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015027
Benjamin Peterson14339b62009-01-31 16:36:08 +000015028 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015029
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015030 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015031 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015032 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015033 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015034 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015035 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015036 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015037 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015038
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015039 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015040 if (self == NULL) {
15041 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015042 return NULL;
15043 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015044 kind = PyUnicode_KIND(unicode);
15045 length = PyUnicode_GET_LENGTH(unicode);
15046
15047 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015048#ifdef Py_DEBUG
15049 _PyUnicode_HASH(self) = -1;
15050#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015051 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015052#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015053 _PyUnicode_STATE(self).interned = 0;
15054 _PyUnicode_STATE(self).kind = kind;
15055 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015056 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015057 _PyUnicode_STATE(self).ready = 1;
15058 _PyUnicode_WSTR(self) = NULL;
15059 _PyUnicode_UTF8_LENGTH(self) = 0;
15060 _PyUnicode_UTF8(self) = NULL;
15061 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015062 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015063
15064 share_utf8 = 0;
15065 share_wstr = 0;
15066 if (kind == PyUnicode_1BYTE_KIND) {
15067 char_size = 1;
15068 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15069 share_utf8 = 1;
15070 }
15071 else if (kind == PyUnicode_2BYTE_KIND) {
15072 char_size = 2;
15073 if (sizeof(wchar_t) == 2)
15074 share_wstr = 1;
15075 }
15076 else {
15077 assert(kind == PyUnicode_4BYTE_KIND);
15078 char_size = 4;
15079 if (sizeof(wchar_t) == 4)
15080 share_wstr = 1;
15081 }
15082
15083 /* Ensure we won't overflow the length. */
15084 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15085 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015086 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015087 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015088 data = PyObject_MALLOC((length + 1) * char_size);
15089 if (data == NULL) {
15090 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015091 goto onError;
15092 }
15093
Victor Stinnerc3c74152011-10-02 20:39:55 +020015094 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015095 if (share_utf8) {
15096 _PyUnicode_UTF8_LENGTH(self) = length;
15097 _PyUnicode_UTF8(self) = data;
15098 }
15099 if (share_wstr) {
15100 _PyUnicode_WSTR_LENGTH(self) = length;
15101 _PyUnicode_WSTR(self) = (wchar_t *)data;
15102 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015103
Christian Heimesf051e432016-09-13 20:22:02 +020015104 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015105 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015106 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015107#ifdef Py_DEBUG
15108 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15109#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015110 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015111 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015112
15113onError:
15114 Py_DECREF(unicode);
15115 Py_DECREF(self);
15116 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015117}
15118
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015119PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015120"str(object='') -> str\n\
15121str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015122\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015123Create a new string object from the given object. If encoding or\n\
15124errors is specified, then the object must expose a data buffer\n\
15125that will be decoded using the given encoding and error handler.\n\
15126Otherwise, returns the result of object.__str__() (if defined)\n\
15127or repr(object).\n\
15128encoding defaults to sys.getdefaultencoding().\n\
15129errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015130
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015131static PyObject *unicode_iter(PyObject *seq);
15132
Guido van Rossumd57fd912000-03-10 22:53:23 +000015133PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015134 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015135 "str", /* tp_name */
15136 sizeof(PyUnicodeObject), /* tp_size */
15137 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015138 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015139 (destructor)unicode_dealloc, /* tp_dealloc */
15140 0, /* tp_print */
15141 0, /* tp_getattr */
15142 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015143 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015144 unicode_repr, /* tp_repr */
15145 &unicode_as_number, /* tp_as_number */
15146 &unicode_as_sequence, /* tp_as_sequence */
15147 &unicode_as_mapping, /* tp_as_mapping */
15148 (hashfunc) unicode_hash, /* tp_hash*/
15149 0, /* tp_call*/
15150 (reprfunc) unicode_str, /* tp_str */
15151 PyObject_GenericGetAttr, /* tp_getattro */
15152 0, /* tp_setattro */
15153 0, /* tp_as_buffer */
15154 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015155 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015156 unicode_doc, /* tp_doc */
15157 0, /* tp_traverse */
15158 0, /* tp_clear */
15159 PyUnicode_RichCompare, /* tp_richcompare */
15160 0, /* tp_weaklistoffset */
15161 unicode_iter, /* tp_iter */
15162 0, /* tp_iternext */
15163 unicode_methods, /* tp_methods */
15164 0, /* tp_members */
15165 0, /* tp_getset */
15166 &PyBaseObject_Type, /* tp_base */
15167 0, /* tp_dict */
15168 0, /* tp_descr_get */
15169 0, /* tp_descr_set */
15170 0, /* tp_dictoffset */
15171 0, /* tp_init */
15172 0, /* tp_alloc */
15173 unicode_new, /* tp_new */
15174 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015175};
15176
15177/* Initialize the Unicode implementation */
15178
Victor Stinner3a50e702011-10-18 21:21:00 +020015179int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015180{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015181 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015182 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015183 0x000A, /* LINE FEED */
15184 0x000D, /* CARRIAGE RETURN */
15185 0x001C, /* FILE SEPARATOR */
15186 0x001D, /* GROUP SEPARATOR */
15187 0x001E, /* RECORD SEPARATOR */
15188 0x0085, /* NEXT LINE */
15189 0x2028, /* LINE SEPARATOR */
15190 0x2029, /* PARAGRAPH SEPARATOR */
15191 };
15192
Fred Drakee4315f52000-05-09 19:53:39 +000015193 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015194 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015195 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015196 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015197 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015198
Guido van Rossumcacfc072002-05-24 19:01:59 +000015199 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015200 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015201
15202 /* initialize the linebreak bloom filter */
15203 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015204 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015205 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015206
Christian Heimes26532f72013-07-20 14:57:16 +020015207 if (PyType_Ready(&EncodingMapType) < 0)
15208 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015209
Benjamin Petersonc4311282012-10-30 23:21:10 -040015210 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15211 Py_FatalError("Can't initialize field name iterator type");
15212
15213 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15214 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015215
Victor Stinner3a50e702011-10-18 21:21:00 +020015216 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015217}
15218
15219/* Finalize the Unicode implementation */
15220
Christian Heimesa156e092008-02-16 07:38:31 +000015221int
15222PyUnicode_ClearFreeList(void)
15223{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015224 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015225}
15226
Guido van Rossumd57fd912000-03-10 22:53:23 +000015227void
Thomas Wouters78890102000-07-22 19:25:51 +000015228_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015229{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015230 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015231
Serhiy Storchaka05997252013-01-26 12:14:02 +020015232 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015233
Serhiy Storchaka05997252013-01-26 12:14:02 +020015234 for (i = 0; i < 256; i++)
15235 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015236 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015237 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015238}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015239
Walter Dörwald16807132007-05-25 13:52:07 +000015240void
15241PyUnicode_InternInPlace(PyObject **p)
15242{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015243 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015244 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015245#ifdef Py_DEBUG
15246 assert(s != NULL);
15247 assert(_PyUnicode_CHECK(s));
15248#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015249 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015250 return;
15251#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015252 /* If it's a subclass, we don't really know what putting
15253 it in the interned dict might do. */
15254 if (!PyUnicode_CheckExact(s))
15255 return;
15256 if (PyUnicode_CHECK_INTERNED(s))
15257 return;
15258 if (interned == NULL) {
15259 interned = PyDict_New();
15260 if (interned == NULL) {
15261 PyErr_Clear(); /* Don't leave an exception */
15262 return;
15263 }
15264 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015265 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015266 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015267 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015268 if (t == NULL) {
15269 PyErr_Clear();
15270 return;
15271 }
15272 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015273 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015274 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015275 return;
15276 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015277 /* The two references in interned are not counted by refcnt.
15278 The deallocator will take care of this */
15279 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015280 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015281}
15282
15283void
15284PyUnicode_InternImmortal(PyObject **p)
15285{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015286 PyUnicode_InternInPlace(p);
15287 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015288 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015289 Py_INCREF(*p);
15290 }
Walter Dörwald16807132007-05-25 13:52:07 +000015291}
15292
15293PyObject *
15294PyUnicode_InternFromString(const char *cp)
15295{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015296 PyObject *s = PyUnicode_FromString(cp);
15297 if (s == NULL)
15298 return NULL;
15299 PyUnicode_InternInPlace(&s);
15300 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015301}
15302
Alexander Belopolsky40018472011-02-26 01:02:56 +000015303void
15304_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015305{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015306 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015307 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015308 Py_ssize_t i, n;
15309 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015310
Benjamin Peterson14339b62009-01-31 16:36:08 +000015311 if (interned == NULL || !PyDict_Check(interned))
15312 return;
15313 keys = PyDict_Keys(interned);
15314 if (keys == NULL || !PyList_Check(keys)) {
15315 PyErr_Clear();
15316 return;
15317 }
Walter Dörwald16807132007-05-25 13:52:07 +000015318
Benjamin Peterson14339b62009-01-31 16:36:08 +000015319 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15320 detector, interned unicode strings are not forcibly deallocated;
15321 rather, we give them their stolen references back, and then clear
15322 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015323
Benjamin Peterson14339b62009-01-31 16:36:08 +000015324 n = PyList_GET_SIZE(keys);
15325 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015326 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015327 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015328 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015329 if (PyUnicode_READY(s) == -1) {
15330 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015331 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015332 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015333 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015334 case SSTATE_NOT_INTERNED:
15335 /* XXX Shouldn't happen */
15336 break;
15337 case SSTATE_INTERNED_IMMORTAL:
15338 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015339 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015340 break;
15341 case SSTATE_INTERNED_MORTAL:
15342 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015343 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015344 break;
15345 default:
15346 Py_FatalError("Inconsistent interned string state.");
15347 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015348 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015349 }
15350 fprintf(stderr, "total size of all interned strings: "
15351 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15352 "mortal/immortal\n", mortal_size, immortal_size);
15353 Py_DECREF(keys);
15354 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015355 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015356}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015357
15358
15359/********************* Unicode Iterator **************************/
15360
15361typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015362 PyObject_HEAD
15363 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015364 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015365} unicodeiterobject;
15366
15367static void
15368unicodeiter_dealloc(unicodeiterobject *it)
15369{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015370 _PyObject_GC_UNTRACK(it);
15371 Py_XDECREF(it->it_seq);
15372 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015373}
15374
15375static int
15376unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15377{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015378 Py_VISIT(it->it_seq);
15379 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015380}
15381
15382static PyObject *
15383unicodeiter_next(unicodeiterobject *it)
15384{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015385 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015386
Benjamin Peterson14339b62009-01-31 16:36:08 +000015387 assert(it != NULL);
15388 seq = it->it_seq;
15389 if (seq == NULL)
15390 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015391 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015392
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015393 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15394 int kind = PyUnicode_KIND(seq);
15395 void *data = PyUnicode_DATA(seq);
15396 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15397 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015398 if (item != NULL)
15399 ++it->it_index;
15400 return item;
15401 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015402
Benjamin Peterson14339b62009-01-31 16:36:08 +000015403 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015404 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015405 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015406}
15407
15408static PyObject *
15409unicodeiter_len(unicodeiterobject *it)
15410{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015411 Py_ssize_t len = 0;
15412 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015413 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015414 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015415}
15416
15417PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15418
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015419static PyObject *
15420unicodeiter_reduce(unicodeiterobject *it)
15421{
15422 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015423 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015424 it->it_seq, it->it_index);
15425 } else {
15426 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15427 if (u == NULL)
15428 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015429 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015430 }
15431}
15432
15433PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15434
15435static PyObject *
15436unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15437{
15438 Py_ssize_t index = PyLong_AsSsize_t(state);
15439 if (index == -1 && PyErr_Occurred())
15440 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015441 if (it->it_seq != NULL) {
15442 if (index < 0)
15443 index = 0;
15444 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15445 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15446 it->it_index = index;
15447 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015448 Py_RETURN_NONE;
15449}
15450
15451PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15452
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015453static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015454 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015455 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015456 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15457 reduce_doc},
15458 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15459 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015460 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015461};
15462
15463PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015464 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15465 "str_iterator", /* tp_name */
15466 sizeof(unicodeiterobject), /* tp_basicsize */
15467 0, /* tp_itemsize */
15468 /* methods */
15469 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15470 0, /* tp_print */
15471 0, /* tp_getattr */
15472 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015473 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015474 0, /* tp_repr */
15475 0, /* tp_as_number */
15476 0, /* tp_as_sequence */
15477 0, /* tp_as_mapping */
15478 0, /* tp_hash */
15479 0, /* tp_call */
15480 0, /* tp_str */
15481 PyObject_GenericGetAttr, /* tp_getattro */
15482 0, /* tp_setattro */
15483 0, /* tp_as_buffer */
15484 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15485 0, /* tp_doc */
15486 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15487 0, /* tp_clear */
15488 0, /* tp_richcompare */
15489 0, /* tp_weaklistoffset */
15490 PyObject_SelfIter, /* tp_iter */
15491 (iternextfunc)unicodeiter_next, /* tp_iternext */
15492 unicodeiter_methods, /* tp_methods */
15493 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015494};
15495
15496static PyObject *
15497unicode_iter(PyObject *seq)
15498{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015499 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015500
Benjamin Peterson14339b62009-01-31 16:36:08 +000015501 if (!PyUnicode_Check(seq)) {
15502 PyErr_BadInternalCall();
15503 return NULL;
15504 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015505 if (PyUnicode_READY(seq) == -1)
15506 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015507 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15508 if (it == NULL)
15509 return NULL;
15510 it->it_index = 0;
15511 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015512 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015513 _PyObject_GC_TRACK(it);
15514 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015515}
15516
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015517
15518size_t
15519Py_UNICODE_strlen(const Py_UNICODE *u)
15520{
15521 int res = 0;
15522 while(*u++)
15523 res++;
15524 return res;
15525}
15526
15527Py_UNICODE*
15528Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15529{
15530 Py_UNICODE *u = s1;
15531 while ((*u++ = *s2++));
15532 return s1;
15533}
15534
15535Py_UNICODE*
15536Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15537{
15538 Py_UNICODE *u = s1;
15539 while ((*u++ = *s2++))
15540 if (n-- == 0)
15541 break;
15542 return s1;
15543}
15544
15545Py_UNICODE*
15546Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15547{
15548 Py_UNICODE *u1 = s1;
15549 u1 += Py_UNICODE_strlen(u1);
15550 Py_UNICODE_strcpy(u1, s2);
15551 return s1;
15552}
15553
15554int
15555Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15556{
15557 while (*s1 && *s2 && *s1 == *s2)
15558 s1++, s2++;
15559 if (*s1 && *s2)
15560 return (*s1 < *s2) ? -1 : +1;
15561 if (*s1)
15562 return 1;
15563 if (*s2)
15564 return -1;
15565 return 0;
15566}
15567
15568int
15569Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15570{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015571 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015572 for (; n != 0; n--) {
15573 u1 = *s1;
15574 u2 = *s2;
15575 if (u1 != u2)
15576 return (u1 < u2) ? -1 : +1;
15577 if (u1 == '\0')
15578 return 0;
15579 s1++;
15580 s2++;
15581 }
15582 return 0;
15583}
15584
15585Py_UNICODE*
15586Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15587{
15588 const Py_UNICODE *p;
15589 for (p = s; *p; p++)
15590 if (*p == c)
15591 return (Py_UNICODE*)p;
15592 return NULL;
15593}
15594
15595Py_UNICODE*
15596Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15597{
15598 const Py_UNICODE *p;
15599 p = s + Py_UNICODE_strlen(s);
15600 while (p != s) {
15601 p--;
15602 if (*p == c)
15603 return (Py_UNICODE*)p;
15604 }
15605 return NULL;
15606}
Victor Stinner331ea922010-08-10 16:37:20 +000015607
Victor Stinner71133ff2010-09-01 23:43:53 +000015608Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015609PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015610{
Victor Stinner577db2c2011-10-11 22:12:48 +020015611 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015612 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015613
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015614 if (!PyUnicode_Check(unicode)) {
15615 PyErr_BadArgument();
15616 return NULL;
15617 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015618 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015619 if (u == NULL)
15620 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015621 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015622 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015623 PyErr_NoMemory();
15624 return NULL;
15625 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015626 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015627 size *= sizeof(Py_UNICODE);
15628 copy = PyMem_Malloc(size);
15629 if (copy == NULL) {
15630 PyErr_NoMemory();
15631 return NULL;
15632 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015633 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015634 return copy;
15635}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015636
Georg Brandl66c221e2010-10-14 07:04:07 +000015637/* A _string module, to export formatter_parser and formatter_field_name_split
15638 to the string.Formatter class implemented in Python. */
15639
15640static PyMethodDef _string_methods[] = {
15641 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15642 METH_O, PyDoc_STR("split the argument as a field name")},
15643 {"formatter_parser", (PyCFunction) formatter_parser,
15644 METH_O, PyDoc_STR("parse the argument as a format string")},
15645 {NULL, NULL}
15646};
15647
15648static struct PyModuleDef _string_module = {
15649 PyModuleDef_HEAD_INIT,
15650 "_string",
15651 PyDoc_STR("string helper module"),
15652 0,
15653 _string_methods,
15654 NULL,
15655 NULL,
15656 NULL,
15657 NULL
15658};
15659
15660PyMODINIT_FUNC
15661PyInit__string(void)
15662{
15663 return PyModule_Create(&_string_module);
15664}
15665
15666
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015667#ifdef __cplusplus
15668}
15669#endif