blob: 494cdbd42e033bfbe2b094094270de715a541ced [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 Storchaka58cf6072013-11-19 11:32:41 +02005516 Py_ssize_t morebytes = 4 * (moreunits - 1);
5517 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5518 /* integer overflow */
5519 PyErr_NoMemory();
5520 goto error;
5521 }
5522 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5523 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005524 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005525 }
5526
5527 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005528 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005529 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005530 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005531 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005532 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5533 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005534 }
5535
5536 Py_CLEAR(rep);
5537 }
5538
5539 /* Cut back to size actually needed. This is necessary for, for example,
5540 encoding of a string containing isolated surrogates and the 'ignore'
5541 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005542 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005543 if (nsize != PyBytes_GET_SIZE(v))
5544 _PyBytes_Resize(&v, nsize);
5545 Py_XDECREF(errorHandler);
5546 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005547 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005548 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005549 error:
5550 Py_XDECREF(rep);
5551 Py_XDECREF(errorHandler);
5552 Py_XDECREF(exc);
5553 Py_XDECREF(v);
5554 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005555}
5556
Alexander Belopolsky40018472011-02-26 01:02:56 +00005557PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005558PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5559 Py_ssize_t size,
5560 const char *errors,
5561 int byteorder)
5562{
5563 PyObject *result;
5564 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5565 if (tmp == NULL)
5566 return NULL;
5567 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5568 Py_DECREF(tmp);
5569 return result;
5570}
5571
5572PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005573PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005574{
Victor Stinnerb960b342011-11-20 19:12:52 +01005575 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005576}
5577
Guido van Rossumd57fd912000-03-10 22:53:23 +00005578/* --- UTF-16 Codec ------------------------------------------------------- */
5579
Tim Peters772747b2001-08-09 22:21:55 +00005580PyObject *
5581PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005582 Py_ssize_t size,
5583 const char *errors,
5584 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005585{
Walter Dörwald69652032004-09-07 20:24:22 +00005586 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5587}
5588
5589PyObject *
5590PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005591 Py_ssize_t size,
5592 const char *errors,
5593 int *byteorder,
5594 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005595{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005596 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005597 Py_ssize_t startinpos;
5598 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005599 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005600 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005601 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005602 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005603 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005604 PyObject *errorHandler = NULL;
5605 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005606 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005607
Tim Peters772747b2001-08-09 22:21:55 +00005608 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005609 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005610
5611 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005612 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005613
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005614 /* Check for BOM marks (U+FEFF) in the input and adjust current
5615 byte order setting accordingly. In native mode, the leading BOM
5616 mark is skipped, in all other modes, it is copied to the output
5617 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005618 if (bo == 0 && size >= 2) {
5619 const Py_UCS4 bom = (q[1] << 8) | q[0];
5620 if (bom == 0xFEFF) {
5621 q += 2;
5622 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005623 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005624 else if (bom == 0xFFFE) {
5625 q += 2;
5626 bo = 1;
5627 }
5628 if (byteorder)
5629 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005630 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005631
Antoine Pitrou63065d72012-05-15 23:48:04 +02005632 if (q == e) {
5633 if (consumed)
5634 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005635 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005636 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005637
Christian Heimes743e0cd2012-10-17 23:52:17 +02005638#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005639 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005640 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005641#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005642 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005643 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005644#endif
Tim Peters772747b2001-08-09 22:21:55 +00005645
Antoine Pitrou63065d72012-05-15 23:48:04 +02005646 /* Note: size will always be longer than the resulting Unicode
5647 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005648 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005649 writer.min_length = (e - q + 1) / 2;
5650 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005651 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005652
Antoine Pitrou63065d72012-05-15 23:48:04 +02005653 while (1) {
5654 Py_UCS4 ch = 0;
5655 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005656 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005657 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005658 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005659 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005660 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005661 native_ordering);
5662 else
5663 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005664 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005665 native_ordering);
5666 } else if (kind == PyUnicode_2BYTE_KIND) {
5667 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005668 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005669 native_ordering);
5670 } else {
5671 assert(kind == PyUnicode_4BYTE_KIND);
5672 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005673 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005674 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005675 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005676 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005677
Antoine Pitrou63065d72012-05-15 23:48:04 +02005678 switch (ch)
5679 {
5680 case 0:
5681 /* remaining byte at the end? (size should be even) */
5682 if (q == e || consumed)
5683 goto End;
5684 errmsg = "truncated data";
5685 startinpos = ((const char *)q) - starts;
5686 endinpos = ((const char *)e) - starts;
5687 break;
5688 /* The remaining input chars are ignored if the callback
5689 chooses to skip the input */
5690 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005691 q -= 2;
5692 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005693 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005694 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005695 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005696 endinpos = ((const char *)e) - starts;
5697 break;
5698 case 2:
5699 errmsg = "illegal encoding";
5700 startinpos = ((const char *)q) - 2 - starts;
5701 endinpos = startinpos + 2;
5702 break;
5703 case 3:
5704 errmsg = "illegal UTF-16 surrogate";
5705 startinpos = ((const char *)q) - 4 - starts;
5706 endinpos = startinpos + 2;
5707 break;
5708 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005709 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005710 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 continue;
5712 }
5713
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005714 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005715 errors,
5716 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005717 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005718 &starts,
5719 (const char **)&e,
5720 &startinpos,
5721 &endinpos,
5722 &exc,
5723 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005724 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005725 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 }
5727
Antoine Pitrou63065d72012-05-15 23:48:04 +02005728End:
Walter Dörwald69652032004-09-07 20:24:22 +00005729 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005730 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005731
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005732 Py_XDECREF(errorHandler);
5733 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005734 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005735
Benjamin Peterson29060642009-01-31 22:14:21 +00005736 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005737 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005738 Py_XDECREF(errorHandler);
5739 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740 return NULL;
5741}
5742
Tim Peters772747b2001-08-09 22:21:55 +00005743PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005744_PyUnicode_EncodeUTF16(PyObject *str,
5745 const char *errors,
5746 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005748 enum PyUnicode_Kind kind;
5749 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005750 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005751 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005752 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005753 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005754#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005755 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005756#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005757 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005758#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005759 const char *encoding;
5760 Py_ssize_t nsize, pos;
5761 PyObject *errorHandler = NULL;
5762 PyObject *exc = NULL;
5763 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005764
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005765 if (!PyUnicode_Check(str)) {
5766 PyErr_BadArgument();
5767 return NULL;
5768 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005769 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005770 return NULL;
5771 kind = PyUnicode_KIND(str);
5772 data = PyUnicode_DATA(str);
5773 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005774
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005775 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005776 if (kind == PyUnicode_4BYTE_KIND) {
5777 const Py_UCS4 *in = (const Py_UCS4 *)data;
5778 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005779 while (in < end) {
5780 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005781 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005782 }
5783 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005784 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005785 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005786 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005787 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005788 nsize = len + pairs + (byteorder == 0);
5789 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005790 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005791 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005792 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005793
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005794 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005795 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005796 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005797 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005798 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005799 }
5800 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005801 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005802 }
Tim Peters772747b2001-08-09 22:21:55 +00005803
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005804 if (kind == PyUnicode_1BYTE_KIND) {
5805 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5806 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005807 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005808
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005809 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005810 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005811 }
5812 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005813 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005814 }
5815 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005816 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005817 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005818
5819 pos = 0;
5820 while (pos < len) {
5821 Py_ssize_t repsize, moreunits;
5822
5823 if (kind == PyUnicode_2BYTE_KIND) {
5824 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5825 &out, native_ordering);
5826 }
5827 else {
5828 assert(kind == PyUnicode_4BYTE_KIND);
5829 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5830 &out, native_ordering);
5831 }
5832 if (pos == len)
5833 break;
5834
5835 rep = unicode_encode_call_errorhandler(
5836 errors, &errorHandler,
5837 encoding, "surrogates not allowed",
5838 str, &exc, pos, pos + 1, &pos);
5839 if (!rep)
5840 goto error;
5841
5842 if (PyBytes_Check(rep)) {
5843 repsize = PyBytes_GET_SIZE(rep);
5844 if (repsize & 1) {
5845 raise_encode_exception(&exc, encoding,
5846 str, pos - 1, pos,
5847 "surrogates not allowed");
5848 goto error;
5849 }
5850 moreunits = repsize / 2;
5851 }
5852 else {
5853 assert(PyUnicode_Check(rep));
5854 if (PyUnicode_READY(rep) < 0)
5855 goto error;
5856 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5857 if (!PyUnicode_IS_ASCII(rep)) {
5858 raise_encode_exception(&exc, encoding,
5859 str, pos - 1, pos,
5860 "surrogates not allowed");
5861 goto error;
5862 }
5863 }
5864
5865 /* two bytes are reserved for each surrogate */
5866 if (moreunits > 1) {
5867 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5868 Py_ssize_t morebytes = 2 * (moreunits - 1);
5869 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5870 /* integer overflow */
5871 PyErr_NoMemory();
5872 goto error;
5873 }
5874 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5875 goto error;
5876 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5877 }
5878
5879 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005880 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005881 out += moreunits;
5882 } else /* rep is unicode */ {
5883 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5884 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5885 &out, native_ordering);
5886 }
5887
5888 Py_CLEAR(rep);
5889 }
5890
5891 /* Cut back to size actually needed. This is necessary for, for example,
5892 encoding of a string containing isolated surrogates and the 'ignore' handler
5893 is used. */
5894 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5895 if (nsize != PyBytes_GET_SIZE(v))
5896 _PyBytes_Resize(&v, nsize);
5897 Py_XDECREF(errorHandler);
5898 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005899 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005900 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005901 error:
5902 Py_XDECREF(rep);
5903 Py_XDECREF(errorHandler);
5904 Py_XDECREF(exc);
5905 Py_XDECREF(v);
5906 return NULL;
5907#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908}
5909
Alexander Belopolsky40018472011-02-26 01:02:56 +00005910PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005911PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5912 Py_ssize_t size,
5913 const char *errors,
5914 int byteorder)
5915{
5916 PyObject *result;
5917 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5918 if (tmp == NULL)
5919 return NULL;
5920 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5921 Py_DECREF(tmp);
5922 return result;
5923}
5924
5925PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005926PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005928 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929}
5930
5931/* --- Unicode Escape Codec ----------------------------------------------- */
5932
Fredrik Lundh06d12682001-01-24 07:59:11 +00005933static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005934
Alexander Belopolsky40018472011-02-26 01:02:56 +00005935PyObject *
Eric V. Smith56466482016-10-31 14:46:26 -04005936_PyUnicode_DecodeUnicodeEscape(const char *s,
5937 Py_ssize_t size,
5938 const char *errors,
5939 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005940{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005941 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005942 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005943 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005944 PyObject *errorHandler = NULL;
5945 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005946
Eric V. Smith56466482016-10-31 14:46:26 -04005947 // so we can remember if we've seen an invalid escape char or not
5948 *first_invalid_escape = NULL;
5949
Victor Stinner62ec3312016-09-06 17:04:34 -07005950 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005951 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005952 }
5953 /* Escaped strings will always be longer than the resulting
5954 Unicode string, so we start with size here and then reduce the
5955 length after conversion to the true value.
5956 (but if the error callback returns a long replacement string
5957 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005958 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005959 writer.min_length = size;
5960 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5961 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005962 }
5963
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964 end = s + size;
5965 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005966 unsigned char c = (unsigned char) *s++;
5967 Py_UCS4 ch;
5968 int count;
5969 Py_ssize_t startinpos;
5970 Py_ssize_t endinpos;
5971 const char *message;
5972
5973#define WRITE_ASCII_CHAR(ch) \
5974 do { \
5975 assert(ch <= 127); \
5976 assert(writer.pos < writer.size); \
5977 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5978 } while(0)
5979
5980#define WRITE_CHAR(ch) \
5981 do { \
5982 if (ch <= writer.maxchar) { \
5983 assert(writer.pos < writer.size); \
5984 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5985 } \
5986 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5987 goto onError; \
5988 } \
5989 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005990
5991 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005992 if (c != '\\') {
5993 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005994 continue;
5995 }
5996
Victor Stinner62ec3312016-09-06 17:04:34 -07005997 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005998 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005999 if (s >= end) {
6000 message = "\\ at end of string";
6001 goto error;
6002 }
6003 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006004
Victor Stinner62ec3312016-09-06 17:04:34 -07006005 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006006 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006007
Benjamin Peterson29060642009-01-31 22:14:21 +00006008 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006009 case '\n': continue;
6010 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6011 case '\'': WRITE_ASCII_CHAR('\''); continue;
6012 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6013 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006014 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006015 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6016 case 't': WRITE_ASCII_CHAR('\t'); continue;
6017 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6018 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006019 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006020 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006021 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006022 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006023
Benjamin Peterson29060642009-01-31 22:14:21 +00006024 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025 case '0': case '1': case '2': case '3':
6026 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006027 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006028 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006029 ch = (ch<<3) + *s++ - '0';
6030 if (s < end && '0' <= *s && *s <= '7') {
6031 ch = (ch<<3) + *s++ - '0';
6032 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006034 WRITE_CHAR(ch);
6035 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036
Benjamin Peterson29060642009-01-31 22:14:21 +00006037 /* hex escapes */
6038 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006040 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006041 message = "truncated \\xXX escape";
6042 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043
Benjamin Peterson29060642009-01-31 22:14:21 +00006044 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006045 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006046 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006047 message = "truncated \\uXXXX escape";
6048 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006049
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006051 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006052 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006053 message = "truncated \\UXXXXXXXX escape";
6054 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006055 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006056 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006057 ch <<= 4;
6058 if (c >= '0' && c <= '9') {
6059 ch += c - '0';
6060 }
6061 else if (c >= 'a' && c <= 'f') {
6062 ch += c - ('a' - 10);
6063 }
6064 else if (c >= 'A' && c <= 'F') {
6065 ch += c - ('A' - 10);
6066 }
6067 else {
6068 break;
6069 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006070 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006071 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006072 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006073 }
6074
6075 /* when we get here, ch is a 32-bit unicode character */
6076 if (ch > MAX_UNICODE) {
6077 message = "illegal Unicode character";
6078 goto error;
6079 }
6080
6081 WRITE_CHAR(ch);
6082 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006083
Benjamin Peterson29060642009-01-31 22:14:21 +00006084 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006085 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006086 if (ucnhash_CAPI == NULL) {
6087 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006088 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6089 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006090 if (ucnhash_CAPI == NULL) {
6091 PyErr_SetString(
6092 PyExc_UnicodeError,
6093 "\\N escapes not supported (can't load unicodedata module)"
6094 );
6095 goto onError;
6096 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006097 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006098
6099 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006100 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006101 const char *start = ++s;
6102 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006103 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006104 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006105 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006106 namelen = s - start;
6107 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006108 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006109 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006110 ch = 0xffffffff; /* in case 'getcode' messes up */
6111 if (namelen <= INT_MAX &&
6112 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6113 &ch, 0)) {
6114 assert(ch <= MAX_UNICODE);
6115 WRITE_CHAR(ch);
6116 continue;
6117 }
6118 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006119 }
6120 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006121 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006122
6123 default:
Eric V. Smith56466482016-10-31 14:46:26 -04006124 if (*first_invalid_escape == NULL) {
6125 *first_invalid_escape = s-1; /* Back up one char, since we've
6126 already incremented s. */
6127 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006128 WRITE_ASCII_CHAR('\\');
6129 WRITE_CHAR(c);
6130 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006132
6133 error:
6134 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006135 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006136 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006137 errors, &errorHandler,
6138 "unicodeescape", message,
6139 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006140 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006141 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006142 }
6143 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6144 goto onError;
6145 }
6146
6147#undef WRITE_ASCII_CHAR
6148#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006149 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006150
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006151 Py_XDECREF(errorHandler);
6152 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006153 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006154
Benjamin Peterson29060642009-01-31 22:14:21 +00006155 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006156 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006157 Py_XDECREF(errorHandler);
6158 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159 return NULL;
6160}
6161
Eric V. Smith56466482016-10-31 14:46:26 -04006162PyObject *
6163PyUnicode_DecodeUnicodeEscape(const char *s,
6164 Py_ssize_t size,
6165 const char *errors)
6166{
6167 const char *first_invalid_escape;
6168 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6169 &first_invalid_escape);
6170 if (result == NULL)
6171 return NULL;
6172 if (first_invalid_escape != NULL) {
6173 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6174 "invalid escape sequence '\\%c'",
6175 *first_invalid_escape) < 0) {
6176 Py_DECREF(result);
6177 return NULL;
6178 }
6179 }
6180 return result;
6181}
6182
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006183/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184
Alexander Belopolsky40018472011-02-26 01:02:56 +00006185PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006186PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006188 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006189 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006190 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006191 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006192 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006193 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006194
Ezio Melottie7f90372012-10-05 03:33:31 +03006195 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006196 escape.
6197
Ezio Melottie7f90372012-10-05 03:33:31 +03006198 For UCS1 strings it's '\xxx', 4 bytes per source character.
6199 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6200 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006201 */
6202
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006203 if (!PyUnicode_Check(unicode)) {
6204 PyErr_BadArgument();
6205 return NULL;
6206 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006207 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006208 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006209 }
Victor Stinner358af132015-10-12 22:36:57 +02006210
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006211 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006212 if (len == 0) {
6213 return PyBytes_FromStringAndSize(NULL, 0);
6214 }
6215
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006216 kind = PyUnicode_KIND(unicode);
6217 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006218 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6219 bytes, and 1 byte characters 4. */
6220 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006221 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006222 return PyErr_NoMemory();
6223 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006224 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006225 if (repr == NULL) {
6226 return NULL;
6227 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006228
Victor Stinner62ec3312016-09-06 17:04:34 -07006229 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006230 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006231 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006232
Victor Stinner62ec3312016-09-06 17:04:34 -07006233 /* U+0000-U+00ff range */
6234 if (ch < 0x100) {
6235 if (ch >= ' ' && ch < 127) {
6236 if (ch != '\\') {
6237 /* Copy printable US ASCII as-is */
6238 *p++ = (char) ch;
6239 }
6240 /* Escape backslashes */
6241 else {
6242 *p++ = '\\';
6243 *p++ = '\\';
6244 }
6245 }
Victor Stinner358af132015-10-12 22:36:57 +02006246
Victor Stinner62ec3312016-09-06 17:04:34 -07006247 /* Map special whitespace to '\t', \n', '\r' */
6248 else if (ch == '\t') {
6249 *p++ = '\\';
6250 *p++ = 't';
6251 }
6252 else if (ch == '\n') {
6253 *p++ = '\\';
6254 *p++ = 'n';
6255 }
6256 else if (ch == '\r') {
6257 *p++ = '\\';
6258 *p++ = 'r';
6259 }
6260
6261 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6262 else {
6263 *p++ = '\\';
6264 *p++ = 'x';
6265 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6266 *p++ = Py_hexdigits[ch & 0x000F];
6267 }
Tim Petersced69f82003-09-16 20:30:58 +00006268 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006269 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006270 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006271 *p++ = '\\';
6272 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006273 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6274 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6275 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6276 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006277 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006278 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6279 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006280
Victor Stinner62ec3312016-09-06 17:04:34 -07006281 /* Make sure that the first two digits are zero */
6282 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006283 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006284 *p++ = 'U';
6285 *p++ = '0';
6286 *p++ = '0';
6287 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6288 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6289 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6290 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6291 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6292 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006293 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006294 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006295
Victor Stinner62ec3312016-09-06 17:04:34 -07006296 assert(p - PyBytes_AS_STRING(repr) > 0);
6297 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6298 return NULL;
6299 }
6300 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006301}
6302
Alexander Belopolsky40018472011-02-26 01:02:56 +00006303PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006304PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6305 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006306{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006307 PyObject *result;
6308 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006309 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006310 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006311 }
6312
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006313 result = PyUnicode_AsUnicodeEscapeString(tmp);
6314 Py_DECREF(tmp);
6315 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006316}
6317
6318/* --- Raw Unicode Escape Codec ------------------------------------------- */
6319
Alexander Belopolsky40018472011-02-26 01:02:56 +00006320PyObject *
6321PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006322 Py_ssize_t size,
6323 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006324{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006325 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006326 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006327 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006328 PyObject *errorHandler = NULL;
6329 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006330
Victor Stinner62ec3312016-09-06 17:04:34 -07006331 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006332 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006333 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006334
Guido van Rossumd57fd912000-03-10 22:53:23 +00006335 /* Escaped strings will always be longer than the resulting
6336 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006337 length after conversion to the true value. (But decoding error
6338 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006339 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006340 writer.min_length = size;
6341 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6342 goto onError;
6343 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006344
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345 end = s + size;
6346 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006347 unsigned char c = (unsigned char) *s++;
6348 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006349 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006350 Py_ssize_t startinpos;
6351 Py_ssize_t endinpos;
6352 const char *message;
6353
6354#define WRITE_CHAR(ch) \
6355 do { \
6356 if (ch <= writer.maxchar) { \
6357 assert(writer.pos < writer.size); \
6358 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6359 } \
6360 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6361 goto onError; \
6362 } \
6363 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006364
Benjamin Peterson29060642009-01-31 22:14:21 +00006365 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006366 if (c != '\\' || s >= end) {
6367 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006369 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006370
Victor Stinner62ec3312016-09-06 17:04:34 -07006371 c = (unsigned char) *s++;
6372 if (c == 'u') {
6373 count = 4;
6374 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006375 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006376 else if (c == 'U') {
6377 count = 8;
6378 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006379 }
6380 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006381 assert(writer.pos < writer.size);
6382 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6383 WRITE_CHAR(c);
6384 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006385 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006386 startinpos = s - starts - 2;
6387
6388 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6389 for (ch = 0; count && s < end; ++s, --count) {
6390 c = (unsigned char)*s;
6391 ch <<= 4;
6392 if (c >= '0' && c <= '9') {
6393 ch += c - '0';
6394 }
6395 else if (c >= 'a' && c <= 'f') {
6396 ch += c - ('a' - 10);
6397 }
6398 else if (c >= 'A' && c <= 'F') {
6399 ch += c - ('A' - 10);
6400 }
6401 else {
6402 break;
6403 }
6404 }
6405 if (!count) {
6406 if (ch <= MAX_UNICODE) {
6407 WRITE_CHAR(ch);
6408 continue;
6409 }
6410 message = "\\Uxxxxxxxx out of range";
6411 }
6412
6413 endinpos = s-starts;
6414 writer.min_length = end - s + writer.pos;
6415 if (unicode_decode_call_errorhandler_writer(
6416 errors, &errorHandler,
6417 "rawunicodeescape", message,
6418 &starts, &end, &startinpos, &endinpos, &exc, &s,
6419 &writer)) {
6420 goto onError;
6421 }
6422 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6423 goto onError;
6424 }
6425
6426#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006427 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006428 Py_XDECREF(errorHandler);
6429 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006430 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006431
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006433 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006434 Py_XDECREF(errorHandler);
6435 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006436 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006437
Guido van Rossumd57fd912000-03-10 22:53:23 +00006438}
6439
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006440
Alexander Belopolsky40018472011-02-26 01:02:56 +00006441PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006442PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006443{
Victor Stinner62ec3312016-09-06 17:04:34 -07006444 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006445 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006446 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006447 int kind;
6448 void *data;
6449 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006450
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006451 if (!PyUnicode_Check(unicode)) {
6452 PyErr_BadArgument();
6453 return NULL;
6454 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006455 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006456 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006457 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006458 kind = PyUnicode_KIND(unicode);
6459 data = PyUnicode_DATA(unicode);
6460 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006461 if (kind == PyUnicode_1BYTE_KIND) {
6462 return PyBytes_FromStringAndSize(data, len);
6463 }
Victor Stinner0e368262011-11-10 20:12:49 +01006464
Victor Stinner62ec3312016-09-06 17:04:34 -07006465 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6466 bytes, and 1 byte characters 4. */
6467 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006468
Victor Stinner62ec3312016-09-06 17:04:34 -07006469 if (len > PY_SSIZE_T_MAX / expandsize) {
6470 return PyErr_NoMemory();
6471 }
6472 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6473 if (repr == NULL) {
6474 return NULL;
6475 }
6476 if (len == 0) {
6477 return repr;
6478 }
6479
6480 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006481 for (pos = 0; pos < len; pos++) {
6482 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006483
Victor Stinner62ec3312016-09-06 17:04:34 -07006484 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6485 if (ch < 0x100) {
6486 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006487 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006488 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6489 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006490 *p++ = '\\';
6491 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006492 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6493 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6494 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6495 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006496 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006497 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6498 else {
6499 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6500 *p++ = '\\';
6501 *p++ = 'U';
6502 *p++ = '0';
6503 *p++ = '0';
6504 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6505 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6506 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6507 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6508 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6509 *p++ = Py_hexdigits[ch & 15];
6510 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006511 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006512
Victor Stinner62ec3312016-09-06 17:04:34 -07006513 assert(p > PyBytes_AS_STRING(repr));
6514 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6515 return NULL;
6516 }
6517 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006518}
6519
Alexander Belopolsky40018472011-02-26 01:02:56 +00006520PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006521PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6522 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006523{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006524 PyObject *result;
6525 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6526 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006527 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006528 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6529 Py_DECREF(tmp);
6530 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006531}
6532
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006533/* --- Unicode Internal Codec ------------------------------------------- */
6534
Alexander Belopolsky40018472011-02-26 01:02:56 +00006535PyObject *
6536_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006537 Py_ssize_t size,
6538 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006539{
6540 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006541 Py_ssize_t startinpos;
6542 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006543 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006544 const char *end;
6545 const char *reason;
6546 PyObject *errorHandler = NULL;
6547 PyObject *exc = NULL;
6548
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006549 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006550 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006551 1))
6552 return NULL;
6553
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006554 if (size == 0)
6555 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006556
Victor Stinner8f674cc2013-04-17 23:02:17 +02006557 _PyUnicodeWriter_Init(&writer);
6558 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6559 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006560 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006561 }
6562 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006563
Victor Stinner8f674cc2013-04-17 23:02:17 +02006564 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006565 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006566 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006567 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006568 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006569 endinpos = end-starts;
6570 reason = "truncated input";
6571 goto error;
6572 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006573 /* We copy the raw representation one byte at a time because the
6574 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006575 ((char *) &uch)[0] = s[0];
6576 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006577#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006578 ((char *) &uch)[2] = s[2];
6579 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006580#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006581 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006582#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006583 /* We have to sanity check the raw data, otherwise doom looms for
6584 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006585 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006586 endinpos = s - starts + Py_UNICODE_SIZE;
6587 reason = "illegal code point (> 0x10FFFF)";
6588 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006589 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006590#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006591 s += Py_UNICODE_SIZE;
6592#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006593 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006594 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006595 Py_UNICODE uch2;
6596 ((char *) &uch2)[0] = s[0];
6597 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006598 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006599 {
Victor Stinner551ac952011-11-29 22:58:13 +01006600 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006601 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006602 }
6603 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006604#endif
6605
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006606 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006607 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006608 continue;
6609
6610 error:
6611 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006612 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006613 errors, &errorHandler,
6614 "unicode_internal", reason,
6615 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006616 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006617 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006618 }
6619
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006620 Py_XDECREF(errorHandler);
6621 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006622 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006623
Benjamin Peterson29060642009-01-31 22:14:21 +00006624 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006625 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006626 Py_XDECREF(errorHandler);
6627 Py_XDECREF(exc);
6628 return NULL;
6629}
6630
Guido van Rossumd57fd912000-03-10 22:53:23 +00006631/* --- Latin-1 Codec ------------------------------------------------------ */
6632
Alexander Belopolsky40018472011-02-26 01:02:56 +00006633PyObject *
6634PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006635 Py_ssize_t size,
6636 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006637{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006638 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006639 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006640}
6641
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006643static void
6644make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006645 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006646 PyObject *unicode,
6647 Py_ssize_t startpos, Py_ssize_t endpos,
6648 const char *reason)
6649{
6650 if (*exceptionObject == NULL) {
6651 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006652 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006653 encoding, unicode, startpos, endpos, reason);
6654 }
6655 else {
6656 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6657 goto onError;
6658 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6659 goto onError;
6660 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6661 goto onError;
6662 return;
6663 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006664 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006665 }
6666}
6667
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006669static void
6670raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006671 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006672 PyObject *unicode,
6673 Py_ssize_t startpos, Py_ssize_t endpos,
6674 const char *reason)
6675{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006676 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006677 encoding, unicode, startpos, endpos, reason);
6678 if (*exceptionObject != NULL)
6679 PyCodec_StrictErrors(*exceptionObject);
6680}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006681
6682/* error handling callback helper:
6683 build arguments, call the callback and check the arguments,
6684 put the result into newpos and return the replacement string, which
6685 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006686static PyObject *
6687unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006688 PyObject **errorHandler,
6689 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006690 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006691 Py_ssize_t startpos, Py_ssize_t endpos,
6692 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006693{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006694 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006695 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006696 PyObject *restuple;
6697 PyObject *resunicode;
6698
6699 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006700 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006701 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006702 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006703 }
6704
Benjamin Petersonbac79492012-01-14 13:34:47 -05006705 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006706 return NULL;
6707 len = PyUnicode_GET_LENGTH(unicode);
6708
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006709 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006710 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006711 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006712 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006713
6714 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006717 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006718 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006719 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 Py_DECREF(restuple);
6721 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006722 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006723 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 &resunicode, newpos)) {
6725 Py_DECREF(restuple);
6726 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006727 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006728 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6729 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6730 Py_DECREF(restuple);
6731 return NULL;
6732 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006733 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006734 *newpos = len + *newpos;
6735 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006736 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006737 Py_DECREF(restuple);
6738 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006739 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006740 Py_INCREF(resunicode);
6741 Py_DECREF(restuple);
6742 return resunicode;
6743}
6744
Alexander Belopolsky40018472011-02-26 01:02:56 +00006745static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006746unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006747 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006748 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006749{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006750 /* input state */
6751 Py_ssize_t pos=0, size;
6752 int kind;
6753 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006754 /* pointer into the output */
6755 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006756 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6757 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006758 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006759 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006760 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006761 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006762 /* output object */
6763 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006764
Benjamin Petersonbac79492012-01-14 13:34:47 -05006765 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006766 return NULL;
6767 size = PyUnicode_GET_LENGTH(unicode);
6768 kind = PyUnicode_KIND(unicode);
6769 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006770 /* allocate enough for a simple encoding without
6771 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006772 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006773 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006774
6775 _PyBytesWriter_Init(&writer);
6776 str = _PyBytesWriter_Alloc(&writer, size);
6777 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006778 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006779
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006780 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006781 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006782
Benjamin Peterson29060642009-01-31 22:14:21 +00006783 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006784 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006785 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006786 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006787 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006788 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006789 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006790 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006791 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006792 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006793 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006794 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006795
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006796 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006797 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006798
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006799 /* Only overallocate the buffer if it's not the last write */
6800 writer.overallocate = (collend < size);
6801
Benjamin Peterson29060642009-01-31 22:14:21 +00006802 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006803 if (error_handler == _Py_ERROR_UNKNOWN)
6804 error_handler = get_error_handler(errors);
6805
6806 switch (error_handler) {
6807 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006808 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006809 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006810
6811 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006812 memset(str, '?', collend - collstart);
6813 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006814 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006815 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006816 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006817 break;
Victor Stinner50149202015-09-22 00:26:54 +02006818
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006819 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006820 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006821 writer.min_size -= (collend - collstart);
6822 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006823 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006824 if (str == NULL)
6825 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006826 pos = collend;
6827 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006828
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006829 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006830 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006831 writer.min_size -= (collend - collstart);
6832 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006833 unicode, collstart, collend);
6834 if (str == NULL)
6835 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006836 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006837 break;
Victor Stinner50149202015-09-22 00:26:54 +02006838
Victor Stinnerc3713e92015-09-29 12:32:13 +02006839 case _Py_ERROR_SURROGATEESCAPE:
6840 for (i = collstart; i < collend; ++i) {
6841 ch = PyUnicode_READ(kind, data, i);
6842 if (ch < 0xdc80 || 0xdcff < ch) {
6843 /* Not a UTF-8b surrogate */
6844 break;
6845 }
6846 *str++ = (char)(ch - 0xdc00);
6847 ++pos;
6848 }
6849 if (i >= collend)
6850 break;
6851 collstart = pos;
6852 assert(collstart != collend);
6853 /* fallback to general error handling */
6854
Benjamin Peterson29060642009-01-31 22:14:21 +00006855 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006856 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6857 encoding, reason, unicode, &exc,
6858 collstart, collend, &newpos);
6859 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006861
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006862 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006863 writer.min_size -= 1;
6864
Victor Stinner6bd525b2015-10-09 13:10:05 +02006865 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006866 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006867 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006868 PyBytes_AS_STRING(rep),
6869 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006870 if (str == NULL)
6871 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006872 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006873 else {
6874 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006875
Victor Stinner6bd525b2015-10-09 13:10:05 +02006876 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006877 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006878
6879 if (PyUnicode_IS_ASCII(rep)) {
6880 /* Fast path: all characters are smaller than limit */
6881 assert(limit >= 128);
6882 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6883 str = _PyBytesWriter_WriteBytes(&writer, str,
6884 PyUnicode_DATA(rep),
6885 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006886 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006887 else {
6888 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6889
6890 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6891 if (str == NULL)
6892 goto onError;
6893
6894 /* check if there is anything unencodable in the
6895 replacement and copy it to the output */
6896 for (i = 0; repsize-->0; ++i, ++str) {
6897 ch = PyUnicode_READ_CHAR(rep, i);
6898 if (ch >= limit) {
6899 raise_encode_exception(&exc, encoding, unicode,
6900 pos, pos+1, reason);
6901 goto onError;
6902 }
6903 *str = (char)ch;
6904 }
6905 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006906 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006907 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006908 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006909 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006910
6911 /* If overallocation was disabled, ensure that it was the last
6912 write. Otherwise, we missed an optimization */
6913 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006914 }
6915 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006916
Victor Stinner50149202015-09-22 00:26:54 +02006917 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006918 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006919 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006920
6921 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006922 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006923 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006924 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006925 Py_XDECREF(exc);
6926 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006927}
6928
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006929/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006930PyObject *
6931PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006932 Py_ssize_t size,
6933 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006934{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006935 PyObject *result;
6936 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6937 if (unicode == NULL)
6938 return NULL;
6939 result = unicode_encode_ucs1(unicode, errors, 256);
6940 Py_DECREF(unicode);
6941 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006942}
6943
Alexander Belopolsky40018472011-02-26 01:02:56 +00006944PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006945_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006946{
6947 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006948 PyErr_BadArgument();
6949 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006950 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006951 if (PyUnicode_READY(unicode) == -1)
6952 return NULL;
6953 /* Fast path: if it is a one-byte string, construct
6954 bytes object directly. */
6955 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6956 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6957 PyUnicode_GET_LENGTH(unicode));
6958 /* Non-Latin-1 characters present. Defer to above function to
6959 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006960 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006961}
6962
6963PyObject*
6964PyUnicode_AsLatin1String(PyObject *unicode)
6965{
6966 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006967}
6968
6969/* --- 7-bit ASCII Codec -------------------------------------------------- */
6970
Alexander Belopolsky40018472011-02-26 01:02:56 +00006971PyObject *
6972PyUnicode_DecodeASCII(const char *s,
6973 Py_ssize_t size,
6974 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006975{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006976 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006977 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006978 int kind;
6979 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006980 Py_ssize_t startinpos;
6981 Py_ssize_t endinpos;
6982 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006983 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006984 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006985 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006986 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006987
Guido van Rossumd57fd912000-03-10 22:53:23 +00006988 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006989 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006990
Guido van Rossumd57fd912000-03-10 22:53:23 +00006991 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006992 if (size == 1 && (unsigned char)s[0] < 128)
6993 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006994
Victor Stinner8f674cc2013-04-17 23:02:17 +02006995 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006996 writer.min_length = size;
6997 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006998 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006999
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007000 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007001 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007002 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007003 writer.pos = outpos;
7004 if (writer.pos == size)
7005 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007006
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007007 s += writer.pos;
7008 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007009 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02007010 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00007011 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007012 PyUnicode_WRITE(kind, data, writer.pos, c);
7013 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007014 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007015 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00007016 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007017
7018 /* byte outsize range 0x00..0x7f: call the error handler */
7019
7020 if (error_handler == _Py_ERROR_UNKNOWN)
7021 error_handler = get_error_handler(errors);
7022
7023 switch (error_handler)
7024 {
7025 case _Py_ERROR_REPLACE:
7026 case _Py_ERROR_SURROGATEESCAPE:
7027 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02007028 but we may switch to UCS2 at the first write */
7029 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7030 goto onError;
7031 kind = writer.kind;
7032 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007033
7034 if (error_handler == _Py_ERROR_REPLACE)
7035 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7036 else
7037 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7038 writer.pos++;
7039 ++s;
7040 break;
7041
7042 case _Py_ERROR_IGNORE:
7043 ++s;
7044 break;
7045
7046 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007047 startinpos = s-starts;
7048 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007049 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007050 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007051 "ascii", "ordinal not in range(128)",
7052 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007053 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007054 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007055 kind = writer.kind;
7056 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007057 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007058 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007059 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007060 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007061 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007062
Benjamin Peterson29060642009-01-31 22:14:21 +00007063 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007064 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007065 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007066 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007067 return NULL;
7068}
7069
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007070/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007071PyObject *
7072PyUnicode_EncodeASCII(const Py_UNICODE *p,
7073 Py_ssize_t size,
7074 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007075{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007076 PyObject *result;
7077 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7078 if (unicode == NULL)
7079 return NULL;
7080 result = unicode_encode_ucs1(unicode, errors, 128);
7081 Py_DECREF(unicode);
7082 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007083}
7084
Alexander Belopolsky40018472011-02-26 01:02:56 +00007085PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007086_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007087{
7088 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007089 PyErr_BadArgument();
7090 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007091 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007092 if (PyUnicode_READY(unicode) == -1)
7093 return NULL;
7094 /* Fast path: if it is an ASCII-only string, construct bytes object
7095 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007096 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007097 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7098 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007099 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007100}
7101
7102PyObject *
7103PyUnicode_AsASCIIString(PyObject *unicode)
7104{
7105 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007106}
7107
Steve Dowercc16be82016-09-08 10:35:16 -07007108#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007109
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007110/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007111
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007112#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007113#define NEED_RETRY
7114#endif
7115
Victor Stinner3a50e702011-10-18 21:21:00 +02007116#ifndef WC_ERR_INVALID_CHARS
7117# define WC_ERR_INVALID_CHARS 0x0080
7118#endif
7119
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007120static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007121code_page_name(UINT code_page, PyObject **obj)
7122{
7123 *obj = NULL;
7124 if (code_page == CP_ACP)
7125 return "mbcs";
7126 if (code_page == CP_UTF7)
7127 return "CP_UTF7";
7128 if (code_page == CP_UTF8)
7129 return "CP_UTF8";
7130
7131 *obj = PyBytes_FromFormat("cp%u", code_page);
7132 if (*obj == NULL)
7133 return NULL;
7134 return PyBytes_AS_STRING(*obj);
7135}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007136
Victor Stinner3a50e702011-10-18 21:21:00 +02007137static DWORD
7138decode_code_page_flags(UINT code_page)
7139{
7140 if (code_page == CP_UTF7) {
7141 /* The CP_UTF7 decoder only supports flags=0 */
7142 return 0;
7143 }
7144 else
7145 return MB_ERR_INVALID_CHARS;
7146}
7147
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007148/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007149 * Decode a byte string from a Windows code page into unicode object in strict
7150 * mode.
7151 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007152 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7153 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007154 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007155static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007156decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007157 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007158 const char *in,
7159 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007160{
Victor Stinner3a50e702011-10-18 21:21:00 +02007161 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007162 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007164
7165 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007166 assert(insize > 0);
7167 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7168 if (outsize <= 0)
7169 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007170
7171 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007172 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007173 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007174 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007175 if (*v == NULL)
7176 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007177 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007178 }
7179 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007180 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007181 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007182 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007183 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007184 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007185 }
7186
7187 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007188 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7189 if (outsize <= 0)
7190 goto error;
7191 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007192
Victor Stinner3a50e702011-10-18 21:21:00 +02007193error:
7194 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7195 return -2;
7196 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007197 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007198}
7199
Victor Stinner3a50e702011-10-18 21:21:00 +02007200/*
7201 * Decode a byte string from a code page into unicode object with an error
7202 * handler.
7203 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007204 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 * UnicodeDecodeError exception and returns -1 on error.
7206 */
7207static int
7208decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007209 PyObject **v,
7210 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007211 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007212{
7213 const char *startin = in;
7214 const char *endin = in + size;
7215 const DWORD flags = decode_code_page_flags(code_page);
7216 /* Ideally, we should get reason from FormatMessage. This is the Windows
7217 2000 English version of the message. */
7218 const char *reason = "No mapping for the Unicode character exists "
7219 "in the target code page.";
7220 /* each step cannot decode more than 1 character, but a character can be
7221 represented as a surrogate pair */
7222 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007223 int insize;
7224 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007225 PyObject *errorHandler = NULL;
7226 PyObject *exc = NULL;
7227 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007228 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007229 DWORD err;
7230 int ret = -1;
7231
7232 assert(size > 0);
7233
7234 encoding = code_page_name(code_page, &encoding_obj);
7235 if (encoding == NULL)
7236 return -1;
7237
Victor Stinner7d00cc12014-03-17 23:08:06 +01007238 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007239 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7240 UnicodeDecodeError. */
7241 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7242 if (exc != NULL) {
7243 PyCodec_StrictErrors(exc);
7244 Py_CLEAR(exc);
7245 }
7246 goto error;
7247 }
7248
7249 if (*v == NULL) {
7250 /* Create unicode object */
7251 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7252 PyErr_NoMemory();
7253 goto error;
7254 }
Victor Stinnerab595942011-12-17 04:59:06 +01007255 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007256 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007257 if (*v == NULL)
7258 goto error;
7259 startout = PyUnicode_AS_UNICODE(*v);
7260 }
7261 else {
7262 /* Extend unicode object */
7263 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7264 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7265 PyErr_NoMemory();
7266 goto error;
7267 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007268 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007269 goto error;
7270 startout = PyUnicode_AS_UNICODE(*v) + n;
7271 }
7272
7273 /* Decode the byte string character per character */
7274 out = startout;
7275 while (in < endin)
7276 {
7277 /* Decode a character */
7278 insize = 1;
7279 do
7280 {
7281 outsize = MultiByteToWideChar(code_page, flags,
7282 in, insize,
7283 buffer, Py_ARRAY_LENGTH(buffer));
7284 if (outsize > 0)
7285 break;
7286 err = GetLastError();
7287 if (err != ERROR_NO_UNICODE_TRANSLATION
7288 && err != ERROR_INSUFFICIENT_BUFFER)
7289 {
7290 PyErr_SetFromWindowsErr(0);
7291 goto error;
7292 }
7293 insize++;
7294 }
7295 /* 4=maximum length of a UTF-8 sequence */
7296 while (insize <= 4 && (in + insize) <= endin);
7297
7298 if (outsize <= 0) {
7299 Py_ssize_t startinpos, endinpos, outpos;
7300
Victor Stinner7d00cc12014-03-17 23:08:06 +01007301 /* last character in partial decode? */
7302 if (in + insize >= endin && !final)
7303 break;
7304
Victor Stinner3a50e702011-10-18 21:21:00 +02007305 startinpos = in - startin;
7306 endinpos = startinpos + 1;
7307 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007308 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007309 errors, &errorHandler,
7310 encoding, reason,
7311 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007312 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007313 {
7314 goto error;
7315 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007316 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007317 }
7318 else {
7319 in += insize;
7320 memcpy(out, buffer, outsize * sizeof(wchar_t));
7321 out += outsize;
7322 }
7323 }
7324
7325 /* write a NUL character at the end */
7326 *out = 0;
7327
7328 /* Extend unicode object */
7329 outsize = out - startout;
7330 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007331 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007332 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007333 /* (in - startin) <= size and size is an int */
7334 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007335
7336error:
7337 Py_XDECREF(encoding_obj);
7338 Py_XDECREF(errorHandler);
7339 Py_XDECREF(exc);
7340 return ret;
7341}
7342
Victor Stinner3a50e702011-10-18 21:21:00 +02007343static PyObject *
7344decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007345 const char *s, Py_ssize_t size,
7346 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007347{
Victor Stinner76a31a62011-11-04 00:05:13 +01007348 PyObject *v = NULL;
7349 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007350
Victor Stinner3a50e702011-10-18 21:21:00 +02007351 if (code_page < 0) {
7352 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7353 return NULL;
7354 }
7355
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007356 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007357 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007358
Victor Stinner76a31a62011-11-04 00:05:13 +01007359 do
7360 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007361#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007362 if (size > INT_MAX) {
7363 chunk_size = INT_MAX;
7364 final = 0;
7365 done = 0;
7366 }
7367 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007368#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007369 {
7370 chunk_size = (int)size;
7371 final = (consumed == NULL);
7372 done = 1;
7373 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007374
Victor Stinner76a31a62011-11-04 00:05:13 +01007375 if (chunk_size == 0 && done) {
7376 if (v != NULL)
7377 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007378 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007379 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007380
Victor Stinner76a31a62011-11-04 00:05:13 +01007381 converted = decode_code_page_strict(code_page, &v,
7382 s, chunk_size);
7383 if (converted == -2)
7384 converted = decode_code_page_errors(code_page, &v,
7385 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007386 errors, final);
7387 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007388
7389 if (converted < 0) {
7390 Py_XDECREF(v);
7391 return NULL;
7392 }
7393
7394 if (consumed)
7395 *consumed += converted;
7396
7397 s += converted;
7398 size -= converted;
7399 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007400
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007401 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007402}
7403
Alexander Belopolsky40018472011-02-26 01:02:56 +00007404PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007405PyUnicode_DecodeCodePageStateful(int code_page,
7406 const char *s,
7407 Py_ssize_t size,
7408 const char *errors,
7409 Py_ssize_t *consumed)
7410{
7411 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7412}
7413
7414PyObject *
7415PyUnicode_DecodeMBCSStateful(const char *s,
7416 Py_ssize_t size,
7417 const char *errors,
7418 Py_ssize_t *consumed)
7419{
7420 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7421}
7422
7423PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007424PyUnicode_DecodeMBCS(const char *s,
7425 Py_ssize_t size,
7426 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007427{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007428 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7429}
7430
Victor Stinner3a50e702011-10-18 21:21:00 +02007431static DWORD
7432encode_code_page_flags(UINT code_page, const char *errors)
7433{
7434 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007435 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007436 }
7437 else if (code_page == CP_UTF7) {
7438 /* CP_UTF7 only supports flags=0 */
7439 return 0;
7440 }
7441 else {
7442 if (errors != NULL && strcmp(errors, "replace") == 0)
7443 return 0;
7444 else
7445 return WC_NO_BEST_FIT_CHARS;
7446 }
7447}
7448
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007449/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007450 * Encode a Unicode string to a Windows code page into a byte string in strict
7451 * mode.
7452 *
7453 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007454 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007455 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007456static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007457encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007458 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007460{
Victor Stinner554f3f02010-06-16 23:33:54 +00007461 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007462 BOOL *pusedDefaultChar = &usedDefaultChar;
7463 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007464 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007465 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007466 const DWORD flags = encode_code_page_flags(code_page, NULL);
7467 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007468 /* Create a substring so that we can get the UTF-16 representation
7469 of just the slice under consideration. */
7470 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007471
Martin v. Löwis3d325192011-11-04 18:23:06 +01007472 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007473
Victor Stinner3a50e702011-10-18 21:21:00 +02007474 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007475 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007476 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007477 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007478
Victor Stinner2fc507f2011-11-04 20:06:39 +01007479 substring = PyUnicode_Substring(unicode, offset, offset+len);
7480 if (substring == NULL)
7481 return -1;
7482 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7483 if (p == NULL) {
7484 Py_DECREF(substring);
7485 return -1;
7486 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007487 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007488
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007489 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007490 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007491 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 NULL, 0,
7493 NULL, pusedDefaultChar);
7494 if (outsize <= 0)
7495 goto error;
7496 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007497 if (pusedDefaultChar && *pusedDefaultChar) {
7498 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007499 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007500 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007501
Victor Stinner3a50e702011-10-18 21:21:00 +02007502 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007503 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007504 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007505 if (*outbytes == NULL) {
7506 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007507 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007508 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007509 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007510 }
7511 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007512 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007513 const Py_ssize_t n = PyBytes_Size(*outbytes);
7514 if (outsize > PY_SSIZE_T_MAX - n) {
7515 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007516 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007517 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007518 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007519 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7520 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007521 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007522 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007523 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007524 }
7525
7526 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007527 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007528 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007529 out, outsize,
7530 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007531 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007532 if (outsize <= 0)
7533 goto error;
7534 if (pusedDefaultChar && *pusedDefaultChar)
7535 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007536 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007537
Victor Stinner3a50e702011-10-18 21:21:00 +02007538error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007539 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007540 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7541 return -2;
7542 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007543 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007544}
7545
Victor Stinner3a50e702011-10-18 21:21:00 +02007546/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007547 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007548 * error handler.
7549 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007550 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007551 * -1 on other error.
7552 */
7553static int
7554encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007555 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007556 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007557{
Victor Stinner3a50e702011-10-18 21:21:00 +02007558 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007559 Py_ssize_t pos = unicode_offset;
7560 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007561 /* Ideally, we should get reason from FormatMessage. This is the Windows
7562 2000 English version of the message. */
7563 const char *reason = "invalid character";
7564 /* 4=maximum length of a UTF-8 sequence */
7565 char buffer[4];
7566 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7567 Py_ssize_t outsize;
7568 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007569 PyObject *errorHandler = NULL;
7570 PyObject *exc = NULL;
7571 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007572 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007573 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007574 PyObject *rep;
7575 int ret = -1;
7576
7577 assert(insize > 0);
7578
7579 encoding = code_page_name(code_page, &encoding_obj);
7580 if (encoding == NULL)
7581 return -1;
7582
7583 if (errors == NULL || strcmp(errors, "strict") == 0) {
7584 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7585 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007586 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007587 if (exc != NULL) {
7588 PyCodec_StrictErrors(exc);
7589 Py_DECREF(exc);
7590 }
7591 Py_XDECREF(encoding_obj);
7592 return -1;
7593 }
7594
7595 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7596 pusedDefaultChar = &usedDefaultChar;
7597 else
7598 pusedDefaultChar = NULL;
7599
7600 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7601 PyErr_NoMemory();
7602 goto error;
7603 }
7604 outsize = insize * Py_ARRAY_LENGTH(buffer);
7605
7606 if (*outbytes == NULL) {
7607 /* Create string object */
7608 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7609 if (*outbytes == NULL)
7610 goto error;
7611 out = PyBytes_AS_STRING(*outbytes);
7612 }
7613 else {
7614 /* Extend string object */
7615 Py_ssize_t n = PyBytes_Size(*outbytes);
7616 if (n > PY_SSIZE_T_MAX - outsize) {
7617 PyErr_NoMemory();
7618 goto error;
7619 }
7620 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7621 goto error;
7622 out = PyBytes_AS_STRING(*outbytes) + n;
7623 }
7624
7625 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007626 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007627 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007628 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7629 wchar_t chars[2];
7630 int charsize;
7631 if (ch < 0x10000) {
7632 chars[0] = (wchar_t)ch;
7633 charsize = 1;
7634 }
7635 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007636 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7637 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007638 charsize = 2;
7639 }
7640
Victor Stinner3a50e702011-10-18 21:21:00 +02007641 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007642 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007643 buffer, Py_ARRAY_LENGTH(buffer),
7644 NULL, pusedDefaultChar);
7645 if (outsize > 0) {
7646 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7647 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007648 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007649 memcpy(out, buffer, outsize);
7650 out += outsize;
7651 continue;
7652 }
7653 }
7654 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7655 PyErr_SetFromWindowsErr(0);
7656 goto error;
7657 }
7658
Victor Stinner3a50e702011-10-18 21:21:00 +02007659 rep = unicode_encode_call_errorhandler(
7660 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007661 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007662 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007663 if (rep == NULL)
7664 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007665 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007666
7667 if (PyBytes_Check(rep)) {
7668 outsize = PyBytes_GET_SIZE(rep);
7669 if (outsize != 1) {
7670 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7671 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7672 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7673 Py_DECREF(rep);
7674 goto error;
7675 }
7676 out = PyBytes_AS_STRING(*outbytes) + offset;
7677 }
7678 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7679 out += outsize;
7680 }
7681 else {
7682 Py_ssize_t i;
7683 enum PyUnicode_Kind kind;
7684 void *data;
7685
Benjamin Petersonbac79492012-01-14 13:34:47 -05007686 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007687 Py_DECREF(rep);
7688 goto error;
7689 }
7690
7691 outsize = PyUnicode_GET_LENGTH(rep);
7692 if (outsize != 1) {
7693 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7694 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7695 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7696 Py_DECREF(rep);
7697 goto error;
7698 }
7699 out = PyBytes_AS_STRING(*outbytes) + offset;
7700 }
7701 kind = PyUnicode_KIND(rep);
7702 data = PyUnicode_DATA(rep);
7703 for (i=0; i < outsize; i++) {
7704 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7705 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007706 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007707 encoding, unicode,
7708 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007709 "unable to encode error handler result to ASCII");
7710 Py_DECREF(rep);
7711 goto error;
7712 }
7713 *out = (unsigned char)ch;
7714 out++;
7715 }
7716 }
7717 Py_DECREF(rep);
7718 }
7719 /* write a NUL byte */
7720 *out = 0;
7721 outsize = out - PyBytes_AS_STRING(*outbytes);
7722 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7723 if (_PyBytes_Resize(outbytes, outsize) < 0)
7724 goto error;
7725 ret = 0;
7726
7727error:
7728 Py_XDECREF(encoding_obj);
7729 Py_XDECREF(errorHandler);
7730 Py_XDECREF(exc);
7731 return ret;
7732}
7733
Victor Stinner3a50e702011-10-18 21:21:00 +02007734static PyObject *
7735encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007736 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007737 const char *errors)
7738{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007739 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007740 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007741 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007742 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007743
Victor Stinner29dacf22015-01-26 16:41:32 +01007744 if (!PyUnicode_Check(unicode)) {
7745 PyErr_BadArgument();
7746 return NULL;
7747 }
7748
Benjamin Petersonbac79492012-01-14 13:34:47 -05007749 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007750 return NULL;
7751 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007752
Victor Stinner3a50e702011-10-18 21:21:00 +02007753 if (code_page < 0) {
7754 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7755 return NULL;
7756 }
7757
Martin v. Löwis3d325192011-11-04 18:23:06 +01007758 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007759 return PyBytes_FromStringAndSize(NULL, 0);
7760
Victor Stinner7581cef2011-11-03 22:32:33 +01007761 offset = 0;
7762 do
7763 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007764#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007765 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007766 chunks. */
7767 if (len > INT_MAX/2) {
7768 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007769 done = 0;
7770 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007771 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007772#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007773 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007774 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007775 done = 1;
7776 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007777
Victor Stinner76a31a62011-11-04 00:05:13 +01007778 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007779 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007780 errors);
7781 if (ret == -2)
7782 ret = encode_code_page_errors(code_page, &outbytes,
7783 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007784 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007785 if (ret < 0) {
7786 Py_XDECREF(outbytes);
7787 return NULL;
7788 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007789
Victor Stinner7581cef2011-11-03 22:32:33 +01007790 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007791 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007792 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007793
Victor Stinner3a50e702011-10-18 21:21:00 +02007794 return outbytes;
7795}
7796
7797PyObject *
7798PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7799 Py_ssize_t size,
7800 const char *errors)
7801{
Victor Stinner7581cef2011-11-03 22:32:33 +01007802 PyObject *unicode, *res;
7803 unicode = PyUnicode_FromUnicode(p, size);
7804 if (unicode == NULL)
7805 return NULL;
7806 res = encode_code_page(CP_ACP, unicode, errors);
7807 Py_DECREF(unicode);
7808 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007809}
7810
7811PyObject *
7812PyUnicode_EncodeCodePage(int code_page,
7813 PyObject *unicode,
7814 const char *errors)
7815{
Victor Stinner7581cef2011-11-03 22:32:33 +01007816 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007817}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007818
Alexander Belopolsky40018472011-02-26 01:02:56 +00007819PyObject *
7820PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007821{
Victor Stinner7581cef2011-11-03 22:32:33 +01007822 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007823}
7824
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007825#undef NEED_RETRY
7826
Steve Dowercc16be82016-09-08 10:35:16 -07007827#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007828
Guido van Rossumd57fd912000-03-10 22:53:23 +00007829/* --- Character Mapping Codec -------------------------------------------- */
7830
Victor Stinnerfb161b12013-04-18 01:44:27 +02007831static int
7832charmap_decode_string(const char *s,
7833 Py_ssize_t size,
7834 PyObject *mapping,
7835 const char *errors,
7836 _PyUnicodeWriter *writer)
7837{
7838 const char *starts = s;
7839 const char *e;
7840 Py_ssize_t startinpos, endinpos;
7841 PyObject *errorHandler = NULL, *exc = NULL;
7842 Py_ssize_t maplen;
7843 enum PyUnicode_Kind mapkind;
7844 void *mapdata;
7845 Py_UCS4 x;
7846 unsigned char ch;
7847
7848 if (PyUnicode_READY(mapping) == -1)
7849 return -1;
7850
7851 maplen = PyUnicode_GET_LENGTH(mapping);
7852 mapdata = PyUnicode_DATA(mapping);
7853 mapkind = PyUnicode_KIND(mapping);
7854
7855 e = s + size;
7856
7857 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7858 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7859 * is disabled in encoding aliases, latin1 is preferred because
7860 * its implementation is faster. */
7861 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7862 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7863 Py_UCS4 maxchar = writer->maxchar;
7864
7865 assert (writer->kind == PyUnicode_1BYTE_KIND);
7866 while (s < e) {
7867 ch = *s;
7868 x = mapdata_ucs1[ch];
7869 if (x > maxchar) {
7870 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7871 goto onError;
7872 maxchar = writer->maxchar;
7873 outdata = (Py_UCS1 *)writer->data;
7874 }
7875 outdata[writer->pos] = x;
7876 writer->pos++;
7877 ++s;
7878 }
7879 return 0;
7880 }
7881
7882 while (s < e) {
7883 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7884 enum PyUnicode_Kind outkind = writer->kind;
7885 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7886 if (outkind == PyUnicode_1BYTE_KIND) {
7887 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7888 Py_UCS4 maxchar = writer->maxchar;
7889 while (s < e) {
7890 ch = *s;
7891 x = mapdata_ucs2[ch];
7892 if (x > maxchar)
7893 goto Error;
7894 outdata[writer->pos] = x;
7895 writer->pos++;
7896 ++s;
7897 }
7898 break;
7899 }
7900 else if (outkind == PyUnicode_2BYTE_KIND) {
7901 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7902 while (s < e) {
7903 ch = *s;
7904 x = mapdata_ucs2[ch];
7905 if (x == 0xFFFE)
7906 goto Error;
7907 outdata[writer->pos] = x;
7908 writer->pos++;
7909 ++s;
7910 }
7911 break;
7912 }
7913 }
7914 ch = *s;
7915
7916 if (ch < maplen)
7917 x = PyUnicode_READ(mapkind, mapdata, ch);
7918 else
7919 x = 0xfffe; /* invalid value */
7920Error:
7921 if (x == 0xfffe)
7922 {
7923 /* undefined mapping */
7924 startinpos = s-starts;
7925 endinpos = startinpos+1;
7926 if (unicode_decode_call_errorhandler_writer(
7927 errors, &errorHandler,
7928 "charmap", "character maps to <undefined>",
7929 &starts, &e, &startinpos, &endinpos, &exc, &s,
7930 writer)) {
7931 goto onError;
7932 }
7933 continue;
7934 }
7935
7936 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7937 goto onError;
7938 ++s;
7939 }
7940 Py_XDECREF(errorHandler);
7941 Py_XDECREF(exc);
7942 return 0;
7943
7944onError:
7945 Py_XDECREF(errorHandler);
7946 Py_XDECREF(exc);
7947 return -1;
7948}
7949
7950static int
7951charmap_decode_mapping(const char *s,
7952 Py_ssize_t size,
7953 PyObject *mapping,
7954 const char *errors,
7955 _PyUnicodeWriter *writer)
7956{
7957 const char *starts = s;
7958 const char *e;
7959 Py_ssize_t startinpos, endinpos;
7960 PyObject *errorHandler = NULL, *exc = NULL;
7961 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007962 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007963
7964 e = s + size;
7965
7966 while (s < e) {
7967 ch = *s;
7968
7969 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7970 key = PyLong_FromLong((long)ch);
7971 if (key == NULL)
7972 goto onError;
7973
7974 item = PyObject_GetItem(mapping, key);
7975 Py_DECREF(key);
7976 if (item == NULL) {
7977 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7978 /* No mapping found means: mapping is undefined. */
7979 PyErr_Clear();
7980 goto Undefined;
7981 } else
7982 goto onError;
7983 }
7984
7985 /* Apply mapping */
7986 if (item == Py_None)
7987 goto Undefined;
7988 if (PyLong_Check(item)) {
7989 long value = PyLong_AS_LONG(item);
7990 if (value == 0xFFFE)
7991 goto Undefined;
7992 if (value < 0 || value > MAX_UNICODE) {
7993 PyErr_Format(PyExc_TypeError,
7994 "character mapping must be in range(0x%lx)",
7995 (unsigned long)MAX_UNICODE + 1);
7996 goto onError;
7997 }
7998
7999 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8000 goto onError;
8001 }
8002 else if (PyUnicode_Check(item)) {
8003 if (PyUnicode_READY(item) == -1)
8004 goto onError;
8005 if (PyUnicode_GET_LENGTH(item) == 1) {
8006 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8007 if (value == 0xFFFE)
8008 goto Undefined;
8009 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8010 goto onError;
8011 }
8012 else {
8013 writer->overallocate = 1;
8014 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8015 goto onError;
8016 }
8017 }
8018 else {
8019 /* wrong return value */
8020 PyErr_SetString(PyExc_TypeError,
8021 "character mapping must return integer, None or str");
8022 goto onError;
8023 }
8024 Py_CLEAR(item);
8025 ++s;
8026 continue;
8027
8028Undefined:
8029 /* undefined mapping */
8030 Py_CLEAR(item);
8031 startinpos = s-starts;
8032 endinpos = startinpos+1;
8033 if (unicode_decode_call_errorhandler_writer(
8034 errors, &errorHandler,
8035 "charmap", "character maps to <undefined>",
8036 &starts, &e, &startinpos, &endinpos, &exc, &s,
8037 writer)) {
8038 goto onError;
8039 }
8040 }
8041 Py_XDECREF(errorHandler);
8042 Py_XDECREF(exc);
8043 return 0;
8044
8045onError:
8046 Py_XDECREF(item);
8047 Py_XDECREF(errorHandler);
8048 Py_XDECREF(exc);
8049 return -1;
8050}
8051
Alexander Belopolsky40018472011-02-26 01:02:56 +00008052PyObject *
8053PyUnicode_DecodeCharmap(const char *s,
8054 Py_ssize_t size,
8055 PyObject *mapping,
8056 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008057{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008058 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008059
Guido van Rossumd57fd912000-03-10 22:53:23 +00008060 /* Default to Latin-1 */
8061 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008063
Guido van Rossumd57fd912000-03-10 22:53:23 +00008064 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008065 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008066 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008067 writer.min_length = size;
8068 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008069 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008070
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008071 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008072 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8073 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008074 }
8075 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008076 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8077 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008078 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008079 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008080
Benjamin Peterson29060642009-01-31 22:14:21 +00008081 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008082 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008083 return NULL;
8084}
8085
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008086/* Charmap encoding: the lookup table */
8087
Alexander Belopolsky40018472011-02-26 01:02:56 +00008088struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008089 PyObject_HEAD
8090 unsigned char level1[32];
8091 int count2, count3;
8092 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008093};
8094
8095static PyObject*
8096encoding_map_size(PyObject *obj, PyObject* args)
8097{
8098 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008099 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008100 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008101}
8102
8103static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008104 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 PyDoc_STR("Return the size (in bytes) of this object") },
8106 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008107};
8108
8109static void
8110encoding_map_dealloc(PyObject* o)
8111{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008112 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113}
8114
8115static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008116 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 "EncodingMap", /*tp_name*/
8118 sizeof(struct encoding_map), /*tp_basicsize*/
8119 0, /*tp_itemsize*/
8120 /* methods */
8121 encoding_map_dealloc, /*tp_dealloc*/
8122 0, /*tp_print*/
8123 0, /*tp_getattr*/
8124 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008125 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 0, /*tp_repr*/
8127 0, /*tp_as_number*/
8128 0, /*tp_as_sequence*/
8129 0, /*tp_as_mapping*/
8130 0, /*tp_hash*/
8131 0, /*tp_call*/
8132 0, /*tp_str*/
8133 0, /*tp_getattro*/
8134 0, /*tp_setattro*/
8135 0, /*tp_as_buffer*/
8136 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8137 0, /*tp_doc*/
8138 0, /*tp_traverse*/
8139 0, /*tp_clear*/
8140 0, /*tp_richcompare*/
8141 0, /*tp_weaklistoffset*/
8142 0, /*tp_iter*/
8143 0, /*tp_iternext*/
8144 encoding_map_methods, /*tp_methods*/
8145 0, /*tp_members*/
8146 0, /*tp_getset*/
8147 0, /*tp_base*/
8148 0, /*tp_dict*/
8149 0, /*tp_descr_get*/
8150 0, /*tp_descr_set*/
8151 0, /*tp_dictoffset*/
8152 0, /*tp_init*/
8153 0, /*tp_alloc*/
8154 0, /*tp_new*/
8155 0, /*tp_free*/
8156 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008157};
8158
8159PyObject*
8160PyUnicode_BuildEncodingMap(PyObject* string)
8161{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008162 PyObject *result;
8163 struct encoding_map *mresult;
8164 int i;
8165 int need_dict = 0;
8166 unsigned char level1[32];
8167 unsigned char level2[512];
8168 unsigned char *mlevel1, *mlevel2, *mlevel3;
8169 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008170 int kind;
8171 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008172 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008173 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008174
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008175 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008176 PyErr_BadArgument();
8177 return NULL;
8178 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008179 kind = PyUnicode_KIND(string);
8180 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008181 length = PyUnicode_GET_LENGTH(string);
8182 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008183 memset(level1, 0xFF, sizeof level1);
8184 memset(level2, 0xFF, sizeof level2);
8185
8186 /* If there isn't a one-to-one mapping of NULL to \0,
8187 or if there are non-BMP characters, we need to use
8188 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008189 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008191 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008192 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008193 ch = PyUnicode_READ(kind, data, i);
8194 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008195 need_dict = 1;
8196 break;
8197 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008198 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008199 /* unmapped character */
8200 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008201 l1 = ch >> 11;
8202 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008203 if (level1[l1] == 0xFF)
8204 level1[l1] = count2++;
8205 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008206 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008207 }
8208
8209 if (count2 >= 0xFF || count3 >= 0xFF)
8210 need_dict = 1;
8211
8212 if (need_dict) {
8213 PyObject *result = PyDict_New();
8214 PyObject *key, *value;
8215 if (!result)
8216 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008217 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008218 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008219 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008220 if (!key || !value)
8221 goto failed1;
8222 if (PyDict_SetItem(result, key, value) == -1)
8223 goto failed1;
8224 Py_DECREF(key);
8225 Py_DECREF(value);
8226 }
8227 return result;
8228 failed1:
8229 Py_XDECREF(key);
8230 Py_XDECREF(value);
8231 Py_DECREF(result);
8232 return NULL;
8233 }
8234
8235 /* Create a three-level trie */
8236 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8237 16*count2 + 128*count3 - 1);
8238 if (!result)
8239 return PyErr_NoMemory();
8240 PyObject_Init(result, &EncodingMapType);
8241 mresult = (struct encoding_map*)result;
8242 mresult->count2 = count2;
8243 mresult->count3 = count3;
8244 mlevel1 = mresult->level1;
8245 mlevel2 = mresult->level23;
8246 mlevel3 = mresult->level23 + 16*count2;
8247 memcpy(mlevel1, level1, 32);
8248 memset(mlevel2, 0xFF, 16*count2);
8249 memset(mlevel3, 0, 128*count3);
8250 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008251 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008252 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008253 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8254 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008255 /* unmapped character */
8256 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008257 o1 = ch>>11;
8258 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008259 i2 = 16*mlevel1[o1] + o2;
8260 if (mlevel2[i2] == 0xFF)
8261 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008262 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008263 i3 = 128*mlevel2[i2] + o3;
8264 mlevel3[i3] = i;
8265 }
8266 return result;
8267}
8268
8269static int
Victor Stinner22168992011-11-20 17:09:18 +01008270encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008271{
8272 struct encoding_map *map = (struct encoding_map*)mapping;
8273 int l1 = c>>11;
8274 int l2 = (c>>7) & 0xF;
8275 int l3 = c & 0x7F;
8276 int i;
8277
Victor Stinner22168992011-11-20 17:09:18 +01008278 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008279 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008280 if (c == 0)
8281 return 0;
8282 /* level 1*/
8283 i = map->level1[l1];
8284 if (i == 0xFF) {
8285 return -1;
8286 }
8287 /* level 2*/
8288 i = map->level23[16*i+l2];
8289 if (i == 0xFF) {
8290 return -1;
8291 }
8292 /* level 3 */
8293 i = map->level23[16*map->count2 + 128*i + l3];
8294 if (i == 0) {
8295 return -1;
8296 }
8297 return i;
8298}
8299
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008300/* Lookup the character ch in the mapping. If the character
8301 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008302 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008303static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008304charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008305{
Christian Heimes217cfd12007-12-02 14:31:20 +00008306 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008307 PyObject *x;
8308
8309 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008311 x = PyObject_GetItem(mapping, w);
8312 Py_DECREF(w);
8313 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8315 /* No mapping found means: mapping is undefined. */
8316 PyErr_Clear();
8317 x = Py_None;
8318 Py_INCREF(x);
8319 return x;
8320 } else
8321 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008322 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008323 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008324 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008325 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 long value = PyLong_AS_LONG(x);
8327 if (value < 0 || value > 255) {
8328 PyErr_SetString(PyExc_TypeError,
8329 "character mapping must be in range(256)");
8330 Py_DECREF(x);
8331 return NULL;
8332 }
8333 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008334 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008335 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008336 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008337 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008338 /* wrong return value */
8339 PyErr_Format(PyExc_TypeError,
8340 "character mapping must return integer, bytes or None, not %.400s",
8341 x->ob_type->tp_name);
8342 Py_DECREF(x);
8343 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008344 }
8345}
8346
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008347static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008348charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008349{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008350 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8351 /* exponentially overallocate to minimize reallocations */
8352 if (requiredsize < 2*outsize)
8353 requiredsize = 2*outsize;
8354 if (_PyBytes_Resize(outobj, requiredsize))
8355 return -1;
8356 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008357}
8358
Benjamin Peterson14339b62009-01-31 16:36:08 +00008359typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008360 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008361} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008363 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364 space is available. Return a new reference to the object that
8365 was put in the output buffer, or Py_None, if the mapping was undefined
8366 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008367 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008368static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008369charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008370 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008372 PyObject *rep;
8373 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008374 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008375
Christian Heimes90aa7642007-12-19 02:45:37 +00008376 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008377 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008379 if (res == -1)
8380 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 if (outsize<requiredsize)
8382 if (charmapencode_resize(outobj, outpos, requiredsize))
8383 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008384 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 outstart[(*outpos)++] = (char)res;
8386 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008387 }
8388
8389 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008390 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008392 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 Py_DECREF(rep);
8394 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008395 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 if (PyLong_Check(rep)) {
8397 Py_ssize_t requiredsize = *outpos+1;
8398 if (outsize<requiredsize)
8399 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8400 Py_DECREF(rep);
8401 return enc_EXCEPTION;
8402 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008403 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008405 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 else {
8407 const char *repchars = PyBytes_AS_STRING(rep);
8408 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8409 Py_ssize_t requiredsize = *outpos+repsize;
8410 if (outsize<requiredsize)
8411 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8412 Py_DECREF(rep);
8413 return enc_EXCEPTION;
8414 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008415 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 memcpy(outstart + *outpos, repchars, repsize);
8417 *outpos += repsize;
8418 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008419 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008420 Py_DECREF(rep);
8421 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422}
8423
8424/* handle an error in PyUnicode_EncodeCharmap
8425 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008426static int
8427charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008428 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008430 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008431 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008432{
8433 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008434 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008435 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008436 enum PyUnicode_Kind kind;
8437 void *data;
8438 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008439 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008440 Py_ssize_t collstartpos = *inpos;
8441 Py_ssize_t collendpos = *inpos+1;
8442 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008443 char *encoding = "charmap";
8444 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008445 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008446 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008447 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008448
Benjamin Petersonbac79492012-01-14 13:34:47 -05008449 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008450 return -1;
8451 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452 /* find all unencodable characters */
8453 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008454 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008455 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008456 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008457 val = encoding_map_lookup(ch, mapping);
8458 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 break;
8460 ++collendpos;
8461 continue;
8462 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008463
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008464 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8465 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 if (rep==NULL)
8467 return -1;
8468 else if (rep!=Py_None) {
8469 Py_DECREF(rep);
8470 break;
8471 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008472 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474 }
8475 /* cache callback name lookup
8476 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008477 if (*error_handler == _Py_ERROR_UNKNOWN)
8478 *error_handler = get_error_handler(errors);
8479
8480 switch (*error_handler) {
8481 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008482 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008483 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008484
8485 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008486 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 x = charmapencode_output('?', mapping, res, respos);
8488 if (x==enc_EXCEPTION) {
8489 return -1;
8490 }
8491 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008492 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 return -1;
8494 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008495 }
8496 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008497 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008498 *inpos = collendpos;
8499 break;
Victor Stinner50149202015-09-22 00:26:54 +02008500
8501 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008502 /* generate replacement (temporarily (mis)uses p) */
8503 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 char buffer[2+29+1+1];
8505 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008506 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 for (cp = buffer; *cp; ++cp) {
8508 x = charmapencode_output(*cp, mapping, res, respos);
8509 if (x==enc_EXCEPTION)
8510 return -1;
8511 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008512 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 return -1;
8514 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008515 }
8516 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008517 *inpos = collendpos;
8518 break;
Victor Stinner50149202015-09-22 00:26:54 +02008519
Benjamin Peterson14339b62009-01-31 16:36:08 +00008520 default:
Victor Stinner50149202015-09-22 00:26:54 +02008521 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008522 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008524 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008526 if (PyBytes_Check(repunicode)) {
8527 /* Directly copy bytes result to output. */
8528 Py_ssize_t outsize = PyBytes_Size(*res);
8529 Py_ssize_t requiredsize;
8530 repsize = PyBytes_Size(repunicode);
8531 requiredsize = *respos + repsize;
8532 if (requiredsize > outsize)
8533 /* Make room for all additional bytes. */
8534 if (charmapencode_resize(res, respos, requiredsize)) {
8535 Py_DECREF(repunicode);
8536 return -1;
8537 }
8538 memcpy(PyBytes_AsString(*res) + *respos,
8539 PyBytes_AsString(repunicode), repsize);
8540 *respos += repsize;
8541 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008542 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008543 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008544 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008545 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008546 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008547 Py_DECREF(repunicode);
8548 return -1;
8549 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008550 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008551 data = PyUnicode_DATA(repunicode);
8552 kind = PyUnicode_KIND(repunicode);
8553 for (index = 0; index < repsize; index++) {
8554 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8555 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008556 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008557 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 return -1;
8559 }
8560 else if (x==enc_FAILED) {
8561 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008562 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008563 return -1;
8564 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008565 }
8566 *inpos = newpos;
8567 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 }
8569 return 0;
8570}
8571
Alexander Belopolsky40018472011-02-26 01:02:56 +00008572PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008573_PyUnicode_EncodeCharmap(PyObject *unicode,
8574 PyObject *mapping,
8575 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008576{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 /* output object */
8578 PyObject *res = NULL;
8579 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008580 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008581 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008582 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008583 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008584 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008585 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008586 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008587 void *data;
8588 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008589
Benjamin Petersonbac79492012-01-14 13:34:47 -05008590 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008591 return NULL;
8592 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008593 data = PyUnicode_DATA(unicode);
8594 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008595
Guido van Rossumd57fd912000-03-10 22:53:23 +00008596 /* Default to Latin-1 */
8597 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008598 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008599
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008600 /* allocate enough for a simple encoding without
8601 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008602 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008603 if (res == NULL)
8604 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008605 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008606 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008607
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008608 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008609 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008610 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008611 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 if (x==enc_EXCEPTION) /* error */
8613 goto onError;
8614 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008615 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008617 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008618 &res, &respos)) {
8619 goto onError;
8620 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008621 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008622 else
8623 /* done with this character => adjust input position */
8624 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008625 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008626
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008628 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008629 if (_PyBytes_Resize(&res, respos) < 0)
8630 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008631
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008632 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008633 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008634 return res;
8635
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008637 Py_XDECREF(res);
8638 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008639 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008640 return NULL;
8641}
8642
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008643/* Deprecated */
8644PyObject *
8645PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8646 Py_ssize_t size,
8647 PyObject *mapping,
8648 const char *errors)
8649{
8650 PyObject *result;
8651 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8652 if (unicode == NULL)
8653 return NULL;
8654 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8655 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008656 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008657}
8658
Alexander Belopolsky40018472011-02-26 01:02:56 +00008659PyObject *
8660PyUnicode_AsCharmapString(PyObject *unicode,
8661 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008662{
8663 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008664 PyErr_BadArgument();
8665 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008666 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008667 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008668}
8669
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008670/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008671static void
8672make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008673 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008674 Py_ssize_t startpos, Py_ssize_t endpos,
8675 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008676{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008677 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 *exceptionObject = _PyUnicodeTranslateError_Create(
8679 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008680 }
8681 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008682 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8683 goto onError;
8684 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8685 goto onError;
8686 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8687 goto onError;
8688 return;
8689 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008690 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008691 }
8692}
8693
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008694/* error handling callback helper:
8695 build arguments, call the callback and check the arguments,
8696 put the result into newpos and return the replacement string, which
8697 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008698static PyObject *
8699unicode_translate_call_errorhandler(const char *errors,
8700 PyObject **errorHandler,
8701 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008702 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008703 Py_ssize_t startpos, Py_ssize_t endpos,
8704 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008705{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008706 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008707
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008708 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008709 PyObject *restuple;
8710 PyObject *resunicode;
8711
8712 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008714 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008716 }
8717
8718 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008719 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008720 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008722
8723 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008724 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008725 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008726 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008727 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008728 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 Py_DECREF(restuple);
8730 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008731 }
8732 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008733 &resunicode, &i_newpos)) {
8734 Py_DECREF(restuple);
8735 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008736 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008737 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008738 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008739 else
8740 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008741 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008742 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008743 Py_DECREF(restuple);
8744 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008745 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008746 Py_INCREF(resunicode);
8747 Py_DECREF(restuple);
8748 return resunicode;
8749}
8750
8751/* Lookup the character ch in the mapping and put the result in result,
8752 which must be decrefed by the caller.
8753 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008754static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008755charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008756{
Christian Heimes217cfd12007-12-02 14:31:20 +00008757 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008758 PyObject *x;
8759
8760 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008761 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008762 x = PyObject_GetItem(mapping, w);
8763 Py_DECREF(w);
8764 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008765 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8766 /* No mapping found means: use 1:1 mapping. */
8767 PyErr_Clear();
8768 *result = NULL;
8769 return 0;
8770 } else
8771 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008772 }
8773 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 *result = x;
8775 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008776 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008777 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008778 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008779 if (value < 0 || value > MAX_UNICODE) {
8780 PyErr_Format(PyExc_ValueError,
8781 "character mapping must be in range(0x%x)",
8782 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008783 Py_DECREF(x);
8784 return -1;
8785 }
8786 *result = x;
8787 return 0;
8788 }
8789 else if (PyUnicode_Check(x)) {
8790 *result = x;
8791 return 0;
8792 }
8793 else {
8794 /* wrong return value */
8795 PyErr_SetString(PyExc_TypeError,
8796 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008797 Py_DECREF(x);
8798 return -1;
8799 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008800}
Victor Stinner1194ea02014-04-04 19:37:40 +02008801
8802/* lookup the character, write the result into the writer.
8803 Return 1 if the result was written into the writer, return 0 if the mapping
8804 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008805static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008806charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8807 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008808{
Victor Stinner1194ea02014-04-04 19:37:40 +02008809 PyObject *item;
8810
8811 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008812 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008813
8814 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008815 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008816 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008817 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008818 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008819 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008820 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008821
8822 if (item == Py_None) {
8823 Py_DECREF(item);
8824 return 0;
8825 }
8826
8827 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008828 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8829 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8830 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008831 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8832 Py_DECREF(item);
8833 return -1;
8834 }
8835 Py_DECREF(item);
8836 return 1;
8837 }
8838
8839 if (!PyUnicode_Check(item)) {
8840 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008841 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008842 }
8843
8844 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8845 Py_DECREF(item);
8846 return -1;
8847 }
8848
8849 Py_DECREF(item);
8850 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008851}
8852
Victor Stinner89a76ab2014-04-05 11:44:04 +02008853static int
8854unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8855 Py_UCS1 *translate)
8856{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008857 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008858 int ret = 0;
8859
Victor Stinner89a76ab2014-04-05 11:44:04 +02008860 if (charmaptranslate_lookup(ch, mapping, &item)) {
8861 return -1;
8862 }
8863
8864 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008865 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008866 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008867 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008868 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008869 /* not found => default to 1:1 mapping */
8870 translate[ch] = ch;
8871 return 1;
8872 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008873 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008874 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008875 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8876 used it */
8877 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008878 /* invalid character or character outside ASCII:
8879 skip the fast translate */
8880 goto exit;
8881 }
8882 translate[ch] = (Py_UCS1)replace;
8883 }
8884 else if (PyUnicode_Check(item)) {
8885 Py_UCS4 replace;
8886
8887 if (PyUnicode_READY(item) == -1) {
8888 Py_DECREF(item);
8889 return -1;
8890 }
8891 if (PyUnicode_GET_LENGTH(item) != 1)
8892 goto exit;
8893
8894 replace = PyUnicode_READ_CHAR(item, 0);
8895 if (replace > 127)
8896 goto exit;
8897 translate[ch] = (Py_UCS1)replace;
8898 }
8899 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008900 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008901 goto exit;
8902 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008903 ret = 1;
8904
Benjamin Peterson1365de72014-04-07 20:15:41 -04008905 exit:
8906 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008907 return ret;
8908}
8909
8910/* Fast path for ascii => ascii translation. Return 1 if the whole string
8911 was translated into writer, return 0 if the input string was partially
8912 translated into writer, raise an exception and return -1 on error. */
8913static int
8914unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008915 _PyUnicodeWriter *writer, int ignore,
8916 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008917{
Victor Stinner872b2912014-04-05 14:27:07 +02008918 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008919 Py_ssize_t len;
8920 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008921 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008922
Victor Stinner89a76ab2014-04-05 11:44:04 +02008923 len = PyUnicode_GET_LENGTH(input);
8924
Victor Stinner872b2912014-04-05 14:27:07 +02008925 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008926
8927 in = PyUnicode_1BYTE_DATA(input);
8928 end = in + len;
8929
8930 assert(PyUnicode_IS_ASCII(writer->buffer));
8931 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8932 out = PyUnicode_1BYTE_DATA(writer->buffer);
8933
Victor Stinner872b2912014-04-05 14:27:07 +02008934 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008935 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008936 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008937 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008938 int translate = unicode_fast_translate_lookup(mapping, ch,
8939 ascii_table);
8940 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008941 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008942 if (translate == 0)
8943 goto exit;
8944 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008945 }
Victor Stinner872b2912014-04-05 14:27:07 +02008946 if (ch2 == 0xfe) {
8947 if (ignore)
8948 continue;
8949 goto exit;
8950 }
8951 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008952 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008953 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008954 }
Victor Stinner872b2912014-04-05 14:27:07 +02008955 res = 1;
8956
8957exit:
8958 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008959 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008960 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008961}
8962
Victor Stinner3222da22015-10-01 22:07:32 +02008963static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008964_PyUnicode_TranslateCharmap(PyObject *input,
8965 PyObject *mapping,
8966 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008967{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008968 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008969 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008970 Py_ssize_t size, i;
8971 int kind;
8972 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008973 _PyUnicodeWriter writer;
8974 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008975 char *reason = "character maps to <undefined>";
8976 PyObject *errorHandler = NULL;
8977 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008978 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008979 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008980
Guido van Rossumd57fd912000-03-10 22:53:23 +00008981 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008982 PyErr_BadArgument();
8983 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008984 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008985
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008986 if (PyUnicode_READY(input) == -1)
8987 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008988 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008989 kind = PyUnicode_KIND(input);
8990 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008991
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008992 if (size == 0)
8993 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008994
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008995 /* allocate enough for a simple 1:1 translation without
8996 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008997 _PyUnicodeWriter_Init(&writer);
8998 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008999 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009000
Victor Stinner872b2912014-04-05 14:27:07 +02009001 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9002
Victor Stinner33798672016-03-01 21:59:58 +01009003 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009004 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01009005 if (PyUnicode_IS_ASCII(input)) {
9006 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9007 if (res < 0) {
9008 _PyUnicodeWriter_Dealloc(&writer);
9009 return NULL;
9010 }
9011 if (res == 1)
9012 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009013 }
Victor Stinner33798672016-03-01 21:59:58 +01009014 else {
9015 i = 0;
9016 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009017
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009018 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009019 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009020 int translate;
9021 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9022 Py_ssize_t newpos;
9023 /* startpos for collecting untranslatable chars */
9024 Py_ssize_t collstart;
9025 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009026 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009027
Victor Stinner1194ea02014-04-04 19:37:40 +02009028 ch = PyUnicode_READ(kind, data, i);
9029 translate = charmaptranslate_output(ch, mapping, &writer);
9030 if (translate < 0)
9031 goto onError;
9032
9033 if (translate != 0) {
9034 /* it worked => adjust input pointer */
9035 ++i;
9036 continue;
9037 }
9038
9039 /* untranslatable character */
9040 collstart = i;
9041 collend = i+1;
9042
9043 /* find all untranslatable characters */
9044 while (collend < size) {
9045 PyObject *x;
9046 ch = PyUnicode_READ(kind, data, collend);
9047 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009048 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009049 Py_XDECREF(x);
9050 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009051 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009052 ++collend;
9053 }
9054
9055 if (ignore) {
9056 i = collend;
9057 }
9058 else {
9059 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9060 reason, input, &exc,
9061 collstart, collend, &newpos);
9062 if (repunicode == NULL)
9063 goto onError;
9064 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009065 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009066 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009067 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009068 Py_DECREF(repunicode);
9069 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009070 }
9071 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009072 Py_XDECREF(exc);
9073 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009074 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009075
Benjamin Peterson29060642009-01-31 22:14:21 +00009076 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009077 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009078 Py_XDECREF(exc);
9079 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009080 return NULL;
9081}
9082
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009083/* Deprecated. Use PyUnicode_Translate instead. */
9084PyObject *
9085PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9086 Py_ssize_t size,
9087 PyObject *mapping,
9088 const char *errors)
9089{
Christian Heimes5f520f42012-09-11 14:03:25 +02009090 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9092 if (!unicode)
9093 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009094 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9095 Py_DECREF(unicode);
9096 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009097}
9098
Alexander Belopolsky40018472011-02-26 01:02:56 +00009099PyObject *
9100PyUnicode_Translate(PyObject *str,
9101 PyObject *mapping,
9102 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009103{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009104 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009105 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009106 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009107}
Tim Petersced69f82003-09-16 20:30:58 +00009108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009109static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009110fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009111{
9112 /* No need to call PyUnicode_READY(self) because this function is only
9113 called as a callback from fixup() which does it already. */
9114 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9115 const int kind = PyUnicode_KIND(self);
9116 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009117 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009118 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009119 Py_ssize_t i;
9120
9121 for (i = 0; i < len; ++i) {
9122 ch = PyUnicode_READ(kind, data, i);
9123 fixed = 0;
9124 if (ch > 127) {
9125 if (Py_UNICODE_ISSPACE(ch))
9126 fixed = ' ';
9127 else {
9128 const int decimal = Py_UNICODE_TODECIMAL(ch);
9129 if (decimal >= 0)
9130 fixed = '0' + decimal;
9131 }
9132 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009133 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009134 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135 PyUnicode_WRITE(kind, data, i, fixed);
9136 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009137 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009138 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009139 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009140 }
9141
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009142 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009143}
9144
9145PyObject *
9146_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9147{
9148 if (!PyUnicode_Check(unicode)) {
9149 PyErr_BadInternalCall();
9150 return NULL;
9151 }
9152 if (PyUnicode_READY(unicode) == -1)
9153 return NULL;
9154 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9155 /* If the string is already ASCII, just return the same string */
9156 Py_INCREF(unicode);
9157 return unicode;
9158 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009159 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009160}
9161
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009162PyObject *
9163PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9164 Py_ssize_t length)
9165{
Victor Stinnerf0124502011-11-21 23:12:56 +01009166 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009167 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009168 Py_UCS4 maxchar;
9169 enum PyUnicode_Kind kind;
9170 void *data;
9171
Victor Stinner99d7ad02012-02-22 13:37:39 +01009172 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009173 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009174 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009175 if (ch > 127) {
9176 int decimal = Py_UNICODE_TODECIMAL(ch);
9177 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009178 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009179 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009180 }
9181 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009182
9183 /* Copy to a new string */
9184 decimal = PyUnicode_New(length, maxchar);
9185 if (decimal == NULL)
9186 return decimal;
9187 kind = PyUnicode_KIND(decimal);
9188 data = PyUnicode_DATA(decimal);
9189 /* Iterate over code points */
9190 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009191 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009192 if (ch > 127) {
9193 int decimal = Py_UNICODE_TODECIMAL(ch);
9194 if (decimal >= 0)
9195 ch = '0' + decimal;
9196 }
9197 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009199 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009200}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009201/* --- Decimal Encoder ---------------------------------------------------- */
9202
Alexander Belopolsky40018472011-02-26 01:02:56 +00009203int
9204PyUnicode_EncodeDecimal(Py_UNICODE *s,
9205 Py_ssize_t length,
9206 char *output,
9207 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009208{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009209 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009210 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009211 enum PyUnicode_Kind kind;
9212 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009213
9214 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009215 PyErr_BadArgument();
9216 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009217 }
9218
Victor Stinner42bf7752011-11-21 22:52:58 +01009219 unicode = PyUnicode_FromUnicode(s, length);
9220 if (unicode == NULL)
9221 return -1;
9222
Benjamin Petersonbac79492012-01-14 13:34:47 -05009223 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009224 Py_DECREF(unicode);
9225 return -1;
9226 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009227 kind = PyUnicode_KIND(unicode);
9228 data = PyUnicode_DATA(unicode);
9229
Victor Stinnerb84d7232011-11-22 01:50:07 +01009230 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009231 PyObject *exc;
9232 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009233 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009234 Py_ssize_t startpos;
9235
9236 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009237
Benjamin Peterson29060642009-01-31 22:14:21 +00009238 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009239 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009240 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009241 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009242 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009243 decimal = Py_UNICODE_TODECIMAL(ch);
9244 if (decimal >= 0) {
9245 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009246 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009247 continue;
9248 }
9249 if (0 < ch && ch < 256) {
9250 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009251 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009252 continue;
9253 }
Victor Stinner6345be92011-11-25 20:09:01 +01009254
Victor Stinner42bf7752011-11-21 22:52:58 +01009255 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009256 exc = NULL;
9257 raise_encode_exception(&exc, "decimal", unicode,
9258 startpos, startpos+1,
9259 "invalid decimal Unicode string");
9260 Py_XDECREF(exc);
9261 Py_DECREF(unicode);
9262 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009263 }
9264 /* 0-terminate the output string */
9265 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009266 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009267 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009268}
9269
Guido van Rossumd57fd912000-03-10 22:53:23 +00009270/* --- Helpers ------------------------------------------------------------ */
9271
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009272/* helper macro to fixup start/end slice values */
9273#define ADJUST_INDICES(start, end, len) \
9274 if (end > len) \
9275 end = len; \
9276 else if (end < 0) { \
9277 end += len; \
9278 if (end < 0) \
9279 end = 0; \
9280 } \
9281 if (start < 0) { \
9282 start += len; \
9283 if (start < 0) \
9284 start = 0; \
9285 }
9286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009288any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009289 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009290 Py_ssize_t end,
9291 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009292{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009293 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 void *buf1, *buf2;
9295 Py_ssize_t len1, len2, result;
9296
9297 kind1 = PyUnicode_KIND(s1);
9298 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009299 if (kind1 < kind2)
9300 return -1;
9301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009302 len1 = PyUnicode_GET_LENGTH(s1);
9303 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009304 ADJUST_INDICES(start, end, len1);
9305 if (end - start < len2)
9306 return -1;
9307
9308 buf1 = PyUnicode_DATA(s1);
9309 buf2 = PyUnicode_DATA(s2);
9310 if (len2 == 1) {
9311 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9312 result = findchar((const char *)buf1 + kind1*start,
9313 kind1, end - start, ch, direction);
9314 if (result == -1)
9315 return -1;
9316 else
9317 return start + result;
9318 }
9319
9320 if (kind2 != kind1) {
9321 buf2 = _PyUnicode_AsKind(s2, kind1);
9322 if (!buf2)
9323 return -2;
9324 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009325
Victor Stinner794d5672011-10-10 03:21:36 +02009326 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009327 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009328 case PyUnicode_1BYTE_KIND:
9329 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9330 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9331 else
9332 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9333 break;
9334 case PyUnicode_2BYTE_KIND:
9335 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9336 break;
9337 case PyUnicode_4BYTE_KIND:
9338 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9339 break;
9340 default:
9341 assert(0); result = -2;
9342 }
9343 }
9344 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009345 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009346 case PyUnicode_1BYTE_KIND:
9347 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9348 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9349 else
9350 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9351 break;
9352 case PyUnicode_2BYTE_KIND:
9353 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9354 break;
9355 case PyUnicode_4BYTE_KIND:
9356 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9357 break;
9358 default:
9359 assert(0); result = -2;
9360 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009361 }
9362
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009363 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009364 PyMem_Free(buf2);
9365
9366 return result;
9367}
9368
9369Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009370_PyUnicode_InsertThousandsGrouping(
9371 PyObject *unicode, Py_ssize_t index,
9372 Py_ssize_t n_buffer,
9373 void *digits, Py_ssize_t n_digits,
9374 Py_ssize_t min_width,
9375 const char *grouping, PyObject *thousands_sep,
9376 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377{
Victor Stinner41a863c2012-02-24 00:37:51 +01009378 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009379 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009380 Py_ssize_t thousands_sep_len;
9381 Py_ssize_t len;
9382
9383 if (unicode != NULL) {
9384 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009385 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009386 }
9387 else {
9388 kind = PyUnicode_1BYTE_KIND;
9389 data = NULL;
9390 }
9391 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9392 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9393 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9394 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009395 if (thousands_sep_kind < kind) {
9396 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9397 if (!thousands_sep_data)
9398 return -1;
9399 }
9400 else {
9401 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9402 if (!data)
9403 return -1;
9404 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009405 }
9406
Benjamin Petersonead6b532011-12-20 17:23:42 -06009407 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009408 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009409 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009410 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009411 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009412 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009413 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009414 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009415 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009416 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009417 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009418 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009419 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009420 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009421 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009422 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009423 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009424 (Py_UCS2 *) 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_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009427 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009428 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009429 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009430 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009431 break;
9432 default:
9433 assert(0);
9434 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009435 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009436 if (unicode != NULL && thousands_sep_kind != kind) {
9437 if (thousands_sep_kind < kind)
9438 PyMem_Free(thousands_sep_data);
9439 else
9440 PyMem_Free(data);
9441 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009442 if (unicode == NULL) {
9443 *maxchar = 127;
9444 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009445 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009446 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009447 }
9448 }
9449 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450}
9451
9452
Alexander Belopolsky40018472011-02-26 01:02:56 +00009453Py_ssize_t
9454PyUnicode_Count(PyObject *str,
9455 PyObject *substr,
9456 Py_ssize_t start,
9457 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009458{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009459 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009460 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461 void *buf1 = NULL, *buf2 = NULL;
9462 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009463
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009464 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009465 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009466
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009467 kind1 = PyUnicode_KIND(str);
9468 kind2 = PyUnicode_KIND(substr);
9469 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009470 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009471
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009472 len1 = PyUnicode_GET_LENGTH(str);
9473 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009474 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009475 if (end - start < len2)
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 buf1 = PyUnicode_DATA(str);
9479 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009480 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009481 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009482 if (!buf2)
9483 goto onError;
9484 }
9485
9486 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009488 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009489 result = asciilib_count(
9490 ((Py_UCS1*)buf1) + start, end - start,
9491 buf2, len2, PY_SSIZE_T_MAX
9492 );
9493 else
9494 result = ucs1lib_count(
9495 ((Py_UCS1*)buf1) + start, end - start,
9496 buf2, len2, PY_SSIZE_T_MAX
9497 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498 break;
9499 case PyUnicode_2BYTE_KIND:
9500 result = ucs2lib_count(
9501 ((Py_UCS2*)buf1) + start, end - start,
9502 buf2, len2, PY_SSIZE_T_MAX
9503 );
9504 break;
9505 case PyUnicode_4BYTE_KIND:
9506 result = ucs4lib_count(
9507 ((Py_UCS4*)buf1) + start, end - start,
9508 buf2, len2, PY_SSIZE_T_MAX
9509 );
9510 break;
9511 default:
9512 assert(0); result = 0;
9513 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009514
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009515 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 PyMem_Free(buf2);
9517
Guido van Rossumd57fd912000-03-10 22:53:23 +00009518 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009520 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009521 PyMem_Free(buf2);
9522 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009523}
9524
Alexander Belopolsky40018472011-02-26 01:02:56 +00009525Py_ssize_t
9526PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009527 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009528 Py_ssize_t start,
9529 Py_ssize_t end,
9530 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009531{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009532 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009533 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009534
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009535 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009536}
9537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009538Py_ssize_t
9539PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9540 Py_ssize_t start, Py_ssize_t end,
9541 int direction)
9542{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009543 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009544 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009545 if (PyUnicode_READY(str) == -1)
9546 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009547 if (start < 0 || end < 0) {
9548 PyErr_SetString(PyExc_IndexError, "string index out of range");
9549 return -2;
9550 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009551 if (end > PyUnicode_GET_LENGTH(str))
9552 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009553 if (start >= end)
9554 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009555 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009556 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9557 kind, end-start, ch, direction);
9558 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009559 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009560 else
9561 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009562}
9563
Alexander Belopolsky40018472011-02-26 01:02:56 +00009564static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009565tailmatch(PyObject *self,
9566 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009567 Py_ssize_t start,
9568 Py_ssize_t end,
9569 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009570{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009571 int kind_self;
9572 int kind_sub;
9573 void *data_self;
9574 void *data_sub;
9575 Py_ssize_t offset;
9576 Py_ssize_t i;
9577 Py_ssize_t end_sub;
9578
9579 if (PyUnicode_READY(self) == -1 ||
9580 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009581 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009582
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009583 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9584 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009585 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009586 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009587
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009588 if (PyUnicode_GET_LENGTH(substring) == 0)
9589 return 1;
9590
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009591 kind_self = PyUnicode_KIND(self);
9592 data_self = PyUnicode_DATA(self);
9593 kind_sub = PyUnicode_KIND(substring);
9594 data_sub = PyUnicode_DATA(substring);
9595 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9596
9597 if (direction > 0)
9598 offset = end;
9599 else
9600 offset = start;
9601
9602 if (PyUnicode_READ(kind_self, data_self, offset) ==
9603 PyUnicode_READ(kind_sub, data_sub, 0) &&
9604 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9605 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9606 /* If both are of the same kind, memcmp is sufficient */
9607 if (kind_self == kind_sub) {
9608 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009609 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009610 data_sub,
9611 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009612 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009614 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009615 else {
9616 /* We do not need to compare 0 and len(substring)-1 because
9617 the if statement above ensured already that they are equal
9618 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009619 for (i = 1; i < end_sub; ++i) {
9620 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9621 PyUnicode_READ(kind_sub, data_sub, i))
9622 return 0;
9623 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009624 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626 }
9627
9628 return 0;
9629}
9630
Alexander Belopolsky40018472011-02-26 01:02:56 +00009631Py_ssize_t
9632PyUnicode_Tailmatch(PyObject *str,
9633 PyObject *substr,
9634 Py_ssize_t start,
9635 Py_ssize_t end,
9636 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009637{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009638 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009639 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009640
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009641 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009642}
9643
Guido van Rossumd57fd912000-03-10 22:53:23 +00009644/* Apply fixfct filter to the Unicode object self and return a
9645 reference to the modified object */
9646
Alexander Belopolsky40018472011-02-26 01:02:56 +00009647static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009648fixup(PyObject *self,
9649 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 PyObject *u;
9652 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009653 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009655 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009656 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009657 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009658 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009660 /* fix functions return the new maximum character in a string,
9661 if the kind of the resulting unicode object does not change,
9662 everything is fine. Otherwise we need to change the string kind
9663 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009664 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009665
9666 if (maxchar_new == 0) {
9667 /* no changes */;
9668 if (PyUnicode_CheckExact(self)) {
9669 Py_DECREF(u);
9670 Py_INCREF(self);
9671 return self;
9672 }
9673 else
9674 return u;
9675 }
9676
Victor Stinnere6abb482012-05-02 01:15:40 +02009677 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678
Victor Stinnereaab6042011-12-11 22:22:39 +01009679 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009680 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009681
9682 /* In case the maximum character changed, we need to
9683 convert the string to the new category. */
9684 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9685 if (v == NULL) {
9686 Py_DECREF(u);
9687 return NULL;
9688 }
9689 if (maxchar_new > maxchar_old) {
9690 /* If the maxchar increased so that the kind changed, not all
9691 characters are representable anymore and we need to fix the
9692 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009693 _PyUnicode_FastCopyCharacters(v, 0,
9694 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009695 maxchar_old = fixfct(v);
9696 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009697 }
9698 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009699 _PyUnicode_FastCopyCharacters(v, 0,
9700 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009701 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009702 Py_DECREF(u);
9703 assert(_PyUnicode_CheckConsistency(v, 1));
9704 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009705}
9706
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009707static PyObject *
9708ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009709{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009710 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9711 char *resdata, *data = PyUnicode_DATA(self);
9712 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009713
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009714 res = PyUnicode_New(len, 127);
9715 if (res == NULL)
9716 return NULL;
9717 resdata = PyUnicode_DATA(res);
9718 if (lower)
9719 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009720 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009721 _Py_bytes_upper(resdata, data, len);
9722 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009723}
9724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009725static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009726handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009727{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009728 Py_ssize_t j;
9729 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009730 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009731 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009732
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009733 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9734
9735 where ! is a negation and \p{xxx} is a character with property xxx.
9736 */
9737 for (j = i - 1; j >= 0; j--) {
9738 c = PyUnicode_READ(kind, data, j);
9739 if (!_PyUnicode_IsCaseIgnorable(c))
9740 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009741 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009742 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9743 if (final_sigma) {
9744 for (j = i + 1; j < length; j++) {
9745 c = PyUnicode_READ(kind, data, j);
9746 if (!_PyUnicode_IsCaseIgnorable(c))
9747 break;
9748 }
9749 final_sigma = j == length || !_PyUnicode_IsCased(c);
9750 }
9751 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009752}
9753
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009754static int
9755lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9756 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009757{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009758 /* Obscure special case. */
9759 if (c == 0x3A3) {
9760 mapped[0] = handle_capital_sigma(kind, data, length, i);
9761 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009762 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009763 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009764}
9765
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009766static Py_ssize_t
9767do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009768{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009769 Py_ssize_t i, k = 0;
9770 int n_res, j;
9771 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009772
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009773 c = PyUnicode_READ(kind, data, 0);
9774 n_res = _PyUnicode_ToUpperFull(c, mapped);
9775 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009776 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009777 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009778 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009779 for (i = 1; i < length; i++) {
9780 c = PyUnicode_READ(kind, data, i);
9781 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9782 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009783 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009784 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009785 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009786 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009787 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009788}
9789
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009790static Py_ssize_t
9791do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9792 Py_ssize_t i, k = 0;
9793
9794 for (i = 0; i < length; i++) {
9795 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9796 int n_res, j;
9797 if (Py_UNICODE_ISUPPER(c)) {
9798 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9799 }
9800 else if (Py_UNICODE_ISLOWER(c)) {
9801 n_res = _PyUnicode_ToUpperFull(c, mapped);
9802 }
9803 else {
9804 n_res = 1;
9805 mapped[0] = c;
9806 }
9807 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009808 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009809 res[k++] = mapped[j];
9810 }
9811 }
9812 return k;
9813}
9814
9815static Py_ssize_t
9816do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9817 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009818{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009819 Py_ssize_t i, k = 0;
9820
9821 for (i = 0; i < length; i++) {
9822 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9823 int n_res, j;
9824 if (lower)
9825 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9826 else
9827 n_res = _PyUnicode_ToUpperFull(c, mapped);
9828 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009829 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009830 res[k++] = mapped[j];
9831 }
9832 }
9833 return k;
9834}
9835
9836static Py_ssize_t
9837do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9838{
9839 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9840}
9841
9842static Py_ssize_t
9843do_lower(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, 1);
9846}
9847
Benjamin Petersone51757f2012-01-12 21:10:29 -05009848static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009849do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9850{
9851 Py_ssize_t i, k = 0;
9852
9853 for (i = 0; i < length; i++) {
9854 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9855 Py_UCS4 mapped[3];
9856 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9857 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009858 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009859 res[k++] = mapped[j];
9860 }
9861 }
9862 return k;
9863}
9864
9865static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009866do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9867{
9868 Py_ssize_t i, k = 0;
9869 int previous_is_cased;
9870
9871 previous_is_cased = 0;
9872 for (i = 0; i < length; i++) {
9873 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9874 Py_UCS4 mapped[3];
9875 int n_res, j;
9876
9877 if (previous_is_cased)
9878 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9879 else
9880 n_res = _PyUnicode_ToTitleFull(c, mapped);
9881
9882 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009883 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009884 res[k++] = mapped[j];
9885 }
9886
9887 previous_is_cased = _PyUnicode_IsCased(c);
9888 }
9889 return k;
9890}
9891
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009892static PyObject *
9893case_operation(PyObject *self,
9894 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9895{
9896 PyObject *res = NULL;
9897 Py_ssize_t length, newlength = 0;
9898 int kind, outkind;
9899 void *data, *outdata;
9900 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9901
Benjamin Petersoneea48462012-01-16 14:28:50 -05009902 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009903
9904 kind = PyUnicode_KIND(self);
9905 data = PyUnicode_DATA(self);
9906 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009907 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009908 PyErr_SetString(PyExc_OverflowError, "string is too long");
9909 return NULL;
9910 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009911 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009912 if (tmp == NULL)
9913 return PyErr_NoMemory();
9914 newlength = perform(kind, data, length, tmp, &maxchar);
9915 res = PyUnicode_New(newlength, maxchar);
9916 if (res == NULL)
9917 goto leave;
9918 tmpend = tmp + newlength;
9919 outdata = PyUnicode_DATA(res);
9920 outkind = PyUnicode_KIND(res);
9921 switch (outkind) {
9922 case PyUnicode_1BYTE_KIND:
9923 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9924 break;
9925 case PyUnicode_2BYTE_KIND:
9926 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9927 break;
9928 case PyUnicode_4BYTE_KIND:
9929 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9930 break;
9931 default:
9932 assert(0);
9933 break;
9934 }
9935 leave:
9936 PyMem_FREE(tmp);
9937 return res;
9938}
9939
Tim Peters8ce9f162004-08-27 01:49:32 +00009940PyObject *
9941PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009942{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009943 PyObject *res;
9944 PyObject *fseq;
9945 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009946 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009947
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009948 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009949 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009950 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009951 }
9952
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009953 /* NOTE: the following code can't call back into Python code,
9954 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009955 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009956
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009957 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009958 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009959 res = _PyUnicode_JoinArray(separator, items, seqlen);
9960 Py_DECREF(fseq);
9961 return res;
9962}
9963
9964PyObject *
9965_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9966{
9967 PyObject *res = NULL; /* the result */
9968 PyObject *sep = NULL;
9969 Py_ssize_t seplen;
9970 PyObject *item;
9971 Py_ssize_t sz, i, res_offset;
9972 Py_UCS4 maxchar;
9973 Py_UCS4 item_maxchar;
9974 int use_memcpy;
9975 unsigned char *res_data = NULL, *sep_data = NULL;
9976 PyObject *last_obj;
9977 unsigned int kind = 0;
9978
Tim Peters05eba1f2004-08-27 21:32:02 +00009979 /* If empty sequence, return u"". */
9980 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009981 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009982 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009983
Tim Peters05eba1f2004-08-27 21:32:02 +00009984 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009985 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009986 if (seqlen == 1) {
9987 if (PyUnicode_CheckExact(items[0])) {
9988 res = items[0];
9989 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009990 return res;
9991 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009992 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009993 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009994 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009995 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009996 /* Set up sep and seplen */
9997 if (separator == NULL) {
9998 /* fall back to a blank space separator */
9999 sep = PyUnicode_FromOrdinal(' ');
10000 if (!sep)
10001 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +020010002 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +020010003 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +000010004 }
Victor Stinneracf47b82011-10-06 12:32:37 +020010005 else {
10006 if (!PyUnicode_Check(separator)) {
10007 PyErr_Format(PyExc_TypeError,
10008 "separator: expected str instance,"
10009 " %.80s found",
10010 Py_TYPE(separator)->tp_name);
10011 goto onError;
10012 }
10013 if (PyUnicode_READY(separator))
10014 goto onError;
10015 sep = separator;
10016 seplen = PyUnicode_GET_LENGTH(separator);
10017 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10018 /* inc refcount to keep this code path symmetric with the
10019 above case of a blank separator */
10020 Py_INCREF(sep);
10021 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010022 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +000010023 }
10024
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010025 /* There are at least two things to join, or else we have a subclass
10026 * of str in the sequence.
10027 * Do a pre-pass to figure out the total amount of space we'll
10028 * need (sz), and see whether all argument are strings.
10029 */
10030 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +020010031#ifdef Py_DEBUG
10032 use_memcpy = 0;
10033#else
10034 use_memcpy = 1;
10035#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010036 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +080010037 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010038 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010039 if (!PyUnicode_Check(item)) {
10040 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +020010041 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +000010042 " %.80s found",
10043 i, Py_TYPE(item)->tp_name);
10044 goto onError;
10045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 if (PyUnicode_READY(item) == -1)
10047 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010048 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010050 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010051 if (i != 0) {
10052 add_sz += seplen;
10053 }
10054 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010055 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010056 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010057 goto onError;
10058 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010059 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010060 if (use_memcpy && last_obj != NULL) {
10061 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10062 use_memcpy = 0;
10063 }
10064 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010065 }
Tim Petersced69f82003-09-16 20:30:58 +000010066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010068 if (res == NULL)
10069 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010070
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010071 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010072#ifdef Py_DEBUG
10073 use_memcpy = 0;
10074#else
10075 if (use_memcpy) {
10076 res_data = PyUnicode_1BYTE_DATA(res);
10077 kind = PyUnicode_KIND(res);
10078 if (seplen != 0)
10079 sep_data = PyUnicode_1BYTE_DATA(sep);
10080 }
10081#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010082 if (use_memcpy) {
10083 for (i = 0; i < seqlen; ++i) {
10084 Py_ssize_t itemlen;
10085 item = items[i];
10086
10087 /* Copy item, and maybe the separator. */
10088 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010089 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010090 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010091 kind * seplen);
10092 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010093 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010094
10095 itemlen = PyUnicode_GET_LENGTH(item);
10096 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010097 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010098 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010099 kind * itemlen);
10100 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010101 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010102 }
10103 assert(res_data == PyUnicode_1BYTE_DATA(res)
10104 + kind * PyUnicode_GET_LENGTH(res));
10105 }
10106 else {
10107 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10108 Py_ssize_t itemlen;
10109 item = items[i];
10110
10111 /* Copy item, and maybe the separator. */
10112 if (i && seplen != 0) {
10113 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10114 res_offset += seplen;
10115 }
10116
10117 itemlen = PyUnicode_GET_LENGTH(item);
10118 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010119 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010120 res_offset += itemlen;
10121 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010122 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010123 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010124 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010127 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010129
Benjamin Peterson29060642009-01-31 22:14:21 +000010130 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010132 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010133 return NULL;
10134}
10135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136#define FILL(kind, data, value, start, length) \
10137 do { \
10138 Py_ssize_t i_ = 0; \
10139 assert(kind != PyUnicode_WCHAR_KIND); \
10140 switch ((kind)) { \
10141 case PyUnicode_1BYTE_KIND: { \
10142 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010143 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 break; \
10145 } \
10146 case PyUnicode_2BYTE_KIND: { \
10147 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10148 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10149 break; \
10150 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010151 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10153 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10154 break; \
10155 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010156 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 } \
10158 } while (0)
10159
Victor Stinnerd3f08822012-05-29 12:57:52 +020010160void
10161_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10162 Py_UCS4 fill_char)
10163{
10164 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10165 const void *data = PyUnicode_DATA(unicode);
10166 assert(PyUnicode_IS_READY(unicode));
10167 assert(unicode_modifiable(unicode));
10168 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10169 assert(start >= 0);
10170 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10171 FILL(kind, data, fill_char, start, length);
10172}
10173
Victor Stinner3fe55312012-01-04 00:33:50 +010010174Py_ssize_t
10175PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10176 Py_UCS4 fill_char)
10177{
10178 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010179
10180 if (!PyUnicode_Check(unicode)) {
10181 PyErr_BadInternalCall();
10182 return -1;
10183 }
10184 if (PyUnicode_READY(unicode) == -1)
10185 return -1;
10186 if (unicode_check_modifiable(unicode))
10187 return -1;
10188
Victor Stinnerd3f08822012-05-29 12:57:52 +020010189 if (start < 0) {
10190 PyErr_SetString(PyExc_IndexError, "string index out of range");
10191 return -1;
10192 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010193 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10194 PyErr_SetString(PyExc_ValueError,
10195 "fill character is bigger than "
10196 "the string maximum character");
10197 return -1;
10198 }
10199
10200 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10201 length = Py_MIN(maxlen, length);
10202 if (length <= 0)
10203 return 0;
10204
Victor Stinnerd3f08822012-05-29 12:57:52 +020010205 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010206 return length;
10207}
10208
Victor Stinner9310abb2011-10-05 00:59:23 +020010209static PyObject *
10210pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010211 Py_ssize_t left,
10212 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 PyObject *u;
10216 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010217 int kind;
10218 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010219
10220 if (left < 0)
10221 left = 0;
10222 if (right < 0)
10223 right = 0;
10224
Victor Stinnerc4b49542011-12-11 22:44:26 +010010225 if (left == 0 && right == 0)
10226 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10229 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010230 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10231 return NULL;
10232 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010234 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010236 if (!u)
10237 return NULL;
10238
10239 kind = PyUnicode_KIND(u);
10240 data = PyUnicode_DATA(u);
10241 if (left)
10242 FILL(kind, data, fill, 0, left);
10243 if (right)
10244 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010245 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010246 assert(_PyUnicode_CheckConsistency(u, 1));
10247 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010248}
10249
Alexander Belopolsky40018472011-02-26 01:02:56 +000010250PyObject *
10251PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010252{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010253 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010254
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010255 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010256 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010257
Benjamin Petersonead6b532011-12-20 17:23:42 -060010258 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010260 if (PyUnicode_IS_ASCII(string))
10261 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010262 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010263 PyUnicode_GET_LENGTH(string), keepends);
10264 else
10265 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010266 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010267 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 break;
10269 case PyUnicode_2BYTE_KIND:
10270 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010271 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 PyUnicode_GET_LENGTH(string), keepends);
10273 break;
10274 case PyUnicode_4BYTE_KIND:
10275 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010276 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 PyUnicode_GET_LENGTH(string), keepends);
10278 break;
10279 default:
10280 assert(0);
10281 list = 0;
10282 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010283 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010284}
10285
Alexander Belopolsky40018472011-02-26 01:02:56 +000010286static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010287split(PyObject *self,
10288 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010289 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010291 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 void *buf1, *buf2;
10293 Py_ssize_t len1, len2;
10294 PyObject* out;
10295
Guido van Rossumd57fd912000-03-10 22:53:23 +000010296 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010297 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 if (PyUnicode_READY(self) == -1)
10300 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010303 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010305 if (PyUnicode_IS_ASCII(self))
10306 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010307 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010308 PyUnicode_GET_LENGTH(self), maxcount
10309 );
10310 else
10311 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010312 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010313 PyUnicode_GET_LENGTH(self), maxcount
10314 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 case PyUnicode_2BYTE_KIND:
10316 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010317 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 PyUnicode_GET_LENGTH(self), maxcount
10319 );
10320 case PyUnicode_4BYTE_KIND:
10321 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010322 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 PyUnicode_GET_LENGTH(self), maxcount
10324 );
10325 default:
10326 assert(0);
10327 return NULL;
10328 }
10329
10330 if (PyUnicode_READY(substring) == -1)
10331 return NULL;
10332
10333 kind1 = PyUnicode_KIND(self);
10334 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010335 len1 = PyUnicode_GET_LENGTH(self);
10336 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010337 if (kind1 < kind2 || len1 < len2) {
10338 out = PyList_New(1);
10339 if (out == NULL)
10340 return NULL;
10341 Py_INCREF(self);
10342 PyList_SET_ITEM(out, 0, self);
10343 return out;
10344 }
10345 buf1 = PyUnicode_DATA(self);
10346 buf2 = PyUnicode_DATA(substring);
10347 if (kind2 != kind1) {
10348 buf2 = _PyUnicode_AsKind(substring, kind1);
10349 if (!buf2)
10350 return NULL;
10351 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010353 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010355 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10356 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010357 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010358 else
10359 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010360 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 break;
10362 case PyUnicode_2BYTE_KIND:
10363 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010364 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 break;
10366 case PyUnicode_4BYTE_KIND:
10367 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010368 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 break;
10370 default:
10371 out = NULL;
10372 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010373 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010374 PyMem_Free(buf2);
10375 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010376}
10377
Alexander Belopolsky40018472011-02-26 01:02:56 +000010378static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010379rsplit(PyObject *self,
10380 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010381 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010382{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010383 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 void *buf1, *buf2;
10385 Py_ssize_t len1, len2;
10386 PyObject* out;
10387
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010388 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010389 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 if (PyUnicode_READY(self) == -1)
10392 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010393
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010394 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010395 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010397 if (PyUnicode_IS_ASCII(self))
10398 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010399 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010400 PyUnicode_GET_LENGTH(self), maxcount
10401 );
10402 else
10403 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010404 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010405 PyUnicode_GET_LENGTH(self), maxcount
10406 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 case PyUnicode_2BYTE_KIND:
10408 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010409 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 PyUnicode_GET_LENGTH(self), maxcount
10411 );
10412 case PyUnicode_4BYTE_KIND:
10413 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010414 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 PyUnicode_GET_LENGTH(self), maxcount
10416 );
10417 default:
10418 assert(0);
10419 return NULL;
10420 }
10421
10422 if (PyUnicode_READY(substring) == -1)
10423 return NULL;
10424
10425 kind1 = PyUnicode_KIND(self);
10426 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 len1 = PyUnicode_GET_LENGTH(self);
10428 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010429 if (kind1 < kind2 || len1 < len2) {
10430 out = PyList_New(1);
10431 if (out == NULL)
10432 return NULL;
10433 Py_INCREF(self);
10434 PyList_SET_ITEM(out, 0, self);
10435 return out;
10436 }
10437 buf1 = PyUnicode_DATA(self);
10438 buf2 = PyUnicode_DATA(substring);
10439 if (kind2 != kind1) {
10440 buf2 = _PyUnicode_AsKind(substring, kind1);
10441 if (!buf2)
10442 return NULL;
10443 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010445 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010447 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10448 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010449 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010450 else
10451 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010452 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010453 break;
10454 case PyUnicode_2BYTE_KIND:
10455 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010456 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457 break;
10458 case PyUnicode_4BYTE_KIND:
10459 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010460 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 break;
10462 default:
10463 out = NULL;
10464 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010465 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 PyMem_Free(buf2);
10467 return out;
10468}
10469
10470static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010471anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10472 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010474 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010476 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10477 return asciilib_find(buf1, len1, buf2, len2, offset);
10478 else
10479 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010480 case PyUnicode_2BYTE_KIND:
10481 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10482 case PyUnicode_4BYTE_KIND:
10483 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10484 }
10485 assert(0);
10486 return -1;
10487}
10488
10489static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010490anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10491 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010493 switch (kind) {
10494 case PyUnicode_1BYTE_KIND:
10495 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10496 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10497 else
10498 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10499 case PyUnicode_2BYTE_KIND:
10500 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10501 case PyUnicode_4BYTE_KIND:
10502 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10503 }
10504 assert(0);
10505 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010506}
10507
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010508static void
10509replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10510 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10511{
10512 int kind = PyUnicode_KIND(u);
10513 void *data = PyUnicode_DATA(u);
10514 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10515 if (kind == PyUnicode_1BYTE_KIND) {
10516 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10517 (Py_UCS1 *)data + len,
10518 u1, u2, maxcount);
10519 }
10520 else if (kind == PyUnicode_2BYTE_KIND) {
10521 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10522 (Py_UCS2 *)data + len,
10523 u1, u2, maxcount);
10524 }
10525 else {
10526 assert(kind == PyUnicode_4BYTE_KIND);
10527 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10528 (Py_UCS4 *)data + len,
10529 u1, u2, maxcount);
10530 }
10531}
10532
Alexander Belopolsky40018472011-02-26 01:02:56 +000010533static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534replace(PyObject *self, PyObject *str1,
10535 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010536{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 PyObject *u;
10538 char *sbuf = PyUnicode_DATA(self);
10539 char *buf1 = PyUnicode_DATA(str1);
10540 char *buf2 = PyUnicode_DATA(str2);
10541 int srelease = 0, release1 = 0, release2 = 0;
10542 int skind = PyUnicode_KIND(self);
10543 int kind1 = PyUnicode_KIND(str1);
10544 int kind2 = PyUnicode_KIND(str2);
10545 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10546 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10547 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010548 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010549 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010550
10551 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010552 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010554 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010555
Victor Stinner59de0ee2011-10-07 10:01:28 +020010556 if (str1 == str2)
10557 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558
Victor Stinner49a0a212011-10-12 23:46:10 +020010559 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010560 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10561 if (maxchar < maxchar_str1)
10562 /* substring too wide to be present */
10563 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010564 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10565 /* Replacing str1 with str2 may cause a maxchar reduction in the
10566 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010567 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010568 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010569
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010571 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010573 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010575 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010576 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010577 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010578
Victor Stinner69ed0f42013-04-09 21:48:24 +020010579 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010580 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010581 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010582 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010583 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010585 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010587
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010588 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10589 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010590 }
10591 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 int rkind = skind;
10593 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010594 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010595
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 if (kind1 < rkind) {
10597 /* widen substring */
10598 buf1 = _PyUnicode_AsKind(str1, rkind);
10599 if (!buf1) goto error;
10600 release1 = 1;
10601 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010602 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010603 if (i < 0)
10604 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 if (rkind > kind2) {
10606 /* widen replacement */
10607 buf2 = _PyUnicode_AsKind(str2, rkind);
10608 if (!buf2) goto error;
10609 release2 = 1;
10610 }
10611 else if (rkind < kind2) {
10612 /* widen self and buf1 */
10613 rkind = kind2;
10614 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010615 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 sbuf = _PyUnicode_AsKind(self, rkind);
10617 if (!sbuf) goto error;
10618 srelease = 1;
10619 buf1 = _PyUnicode_AsKind(str1, rkind);
10620 if (!buf1) goto error;
10621 release1 = 1;
10622 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010623 u = PyUnicode_New(slen, maxchar);
10624 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010626 assert(PyUnicode_KIND(u) == rkind);
10627 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010628
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010629 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010630 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010631 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010632 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010633 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010635
10636 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010637 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010638 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010639 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010640 if (i == -1)
10641 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010642 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010643 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010644 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010646 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010648 }
10649 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010650 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010651 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 int rkind = skind;
10653 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010656 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 buf1 = _PyUnicode_AsKind(str1, rkind);
10658 if (!buf1) goto error;
10659 release1 = 1;
10660 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010661 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010662 if (n == 0)
10663 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010664 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010665 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 buf2 = _PyUnicode_AsKind(str2, rkind);
10667 if (!buf2) goto error;
10668 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010669 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010670 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010671 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 rkind = kind2;
10673 sbuf = _PyUnicode_AsKind(self, rkind);
10674 if (!sbuf) goto error;
10675 srelease = 1;
10676 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010677 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 buf1 = _PyUnicode_AsKind(str1, rkind);
10679 if (!buf1) goto error;
10680 release1 = 1;
10681 }
10682 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10683 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010684 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010685 PyErr_SetString(PyExc_OverflowError,
10686 "replace string is too long");
10687 goto error;
10688 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010689 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010690 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010691 _Py_INCREF_UNICODE_EMPTY();
10692 if (!unicode_empty)
10693 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010694 u = unicode_empty;
10695 goto done;
10696 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010697 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 PyErr_SetString(PyExc_OverflowError,
10699 "replace string is too long");
10700 goto error;
10701 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010702 u = PyUnicode_New(new_size, maxchar);
10703 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010704 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010705 assert(PyUnicode_KIND(u) == rkind);
10706 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 ires = i = 0;
10708 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010709 while (n-- > 0) {
10710 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010711 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010712 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010713 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010714 if (j == -1)
10715 break;
10716 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010717 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010718 memcpy(res + rkind * ires,
10719 sbuf + rkind * i,
10720 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010721 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010722 }
10723 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010724 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010725 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010726 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010727 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010728 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010729 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010730 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010731 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010733 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010734 memcpy(res + rkind * ires,
10735 sbuf + rkind * i,
10736 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010737 }
10738 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010739 /* interleave */
10740 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010741 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010742 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010743 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010744 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010745 if (--n <= 0)
10746 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010747 memcpy(res + rkind * ires,
10748 sbuf + rkind * i,
10749 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010750 ires++;
10751 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010752 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010753 memcpy(res + rkind * ires,
10754 sbuf + rkind * i,
10755 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010756 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010757 }
10758
10759 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010760 unicode_adjust_maxchar(&u);
10761 if (u == NULL)
10762 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010764
10765 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010766 if (srelease)
10767 PyMem_FREE(sbuf);
10768 if (release1)
10769 PyMem_FREE(buf1);
10770 if (release2)
10771 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010772 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010774
Benjamin Peterson29060642009-01-31 22:14:21 +000010775 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010776 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010777 if (srelease)
10778 PyMem_FREE(sbuf);
10779 if (release1)
10780 PyMem_FREE(buf1);
10781 if (release2)
10782 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010783 return unicode_result_unchanged(self);
10784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785 error:
10786 if (srelease && sbuf)
10787 PyMem_FREE(sbuf);
10788 if (release1 && buf1)
10789 PyMem_FREE(buf1);
10790 if (release2 && buf2)
10791 PyMem_FREE(buf2);
10792 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010793}
10794
10795/* --- Unicode Object Methods --------------------------------------------- */
10796
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010797PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010798 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010799\n\
10800Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010801characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802
10803static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010804unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010805{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010806 if (PyUnicode_READY(self) == -1)
10807 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010808 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010809}
10810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010811PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010812 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813\n\
10814Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010815have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816
10817static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010818unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010819{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010820 if (PyUnicode_READY(self) == -1)
10821 return NULL;
10822 if (PyUnicode_GET_LENGTH(self) == 0)
10823 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010824 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010825}
10826
Benjamin Petersond5890c82012-01-14 13:23:30 -050010827PyDoc_STRVAR(casefold__doc__,
10828 "S.casefold() -> str\n\
10829\n\
10830Return a version of S suitable for caseless comparisons.");
10831
10832static PyObject *
10833unicode_casefold(PyObject *self)
10834{
10835 if (PyUnicode_READY(self) == -1)
10836 return NULL;
10837 if (PyUnicode_IS_ASCII(self))
10838 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010839 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010840}
10841
10842
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010843/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010844
10845static int
10846convert_uc(PyObject *obj, void *addr)
10847{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010848 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010849
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010850 if (!PyUnicode_Check(obj)) {
10851 PyErr_Format(PyExc_TypeError,
10852 "The fill character must be a unicode character, "
10853 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010854 return 0;
10855 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010856 if (PyUnicode_READY(obj) < 0)
10857 return 0;
10858 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010859 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010860 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010861 return 0;
10862 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010863 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010864 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010865}
10866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010867PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010868 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010870Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010871done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010872
10873static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010874unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010876 Py_ssize_t marg, left;
10877 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010878 Py_UCS4 fillchar = ' ';
10879
Victor Stinnere9a29352011-10-01 02:14:59 +020010880 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010881 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010882
Benjamin Petersonbac79492012-01-14 13:34:47 -050010883 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884 return NULL;
10885
Victor Stinnerc4b49542011-12-11 22:44:26 +010010886 if (PyUnicode_GET_LENGTH(self) >= width)
10887 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888
Victor Stinnerc4b49542011-12-11 22:44:26 +010010889 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010890 left = marg / 2 + (marg & width & 1);
10891
Victor Stinner9310abb2011-10-05 00:59:23 +020010892 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010893}
10894
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010895/* This function assumes that str1 and str2 are readied by the caller. */
10896
Marc-André Lemburge5034372000-08-08 08:04:29 +000010897static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010898unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010899{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010900#define COMPARE(TYPE1, TYPE2) \
10901 do { \
10902 TYPE1* p1 = (TYPE1 *)data1; \
10903 TYPE2* p2 = (TYPE2 *)data2; \
10904 TYPE1* end = p1 + len; \
10905 Py_UCS4 c1, c2; \
10906 for (; p1 != end; p1++, p2++) { \
10907 c1 = *p1; \
10908 c2 = *p2; \
10909 if (c1 != c2) \
10910 return (c1 < c2) ? -1 : 1; \
10911 } \
10912 } \
10913 while (0)
10914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010915 int kind1, kind2;
10916 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010917 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010919 kind1 = PyUnicode_KIND(str1);
10920 kind2 = PyUnicode_KIND(str2);
10921 data1 = PyUnicode_DATA(str1);
10922 data2 = PyUnicode_DATA(str2);
10923 len1 = PyUnicode_GET_LENGTH(str1);
10924 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010925 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010926
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010927 switch(kind1) {
10928 case PyUnicode_1BYTE_KIND:
10929 {
10930 switch(kind2) {
10931 case PyUnicode_1BYTE_KIND:
10932 {
10933 int cmp = memcmp(data1, data2, len);
10934 /* normalize result of memcmp() into the range [-1; 1] */
10935 if (cmp < 0)
10936 return -1;
10937 if (cmp > 0)
10938 return 1;
10939 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010940 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010941 case PyUnicode_2BYTE_KIND:
10942 COMPARE(Py_UCS1, Py_UCS2);
10943 break;
10944 case PyUnicode_4BYTE_KIND:
10945 COMPARE(Py_UCS1, Py_UCS4);
10946 break;
10947 default:
10948 assert(0);
10949 }
10950 break;
10951 }
10952 case PyUnicode_2BYTE_KIND:
10953 {
10954 switch(kind2) {
10955 case PyUnicode_1BYTE_KIND:
10956 COMPARE(Py_UCS2, Py_UCS1);
10957 break;
10958 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010959 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010960 COMPARE(Py_UCS2, Py_UCS2);
10961 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010962 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010963 case PyUnicode_4BYTE_KIND:
10964 COMPARE(Py_UCS2, Py_UCS4);
10965 break;
10966 default:
10967 assert(0);
10968 }
10969 break;
10970 }
10971 case PyUnicode_4BYTE_KIND:
10972 {
10973 switch(kind2) {
10974 case PyUnicode_1BYTE_KIND:
10975 COMPARE(Py_UCS4, Py_UCS1);
10976 break;
10977 case PyUnicode_2BYTE_KIND:
10978 COMPARE(Py_UCS4, Py_UCS2);
10979 break;
10980 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010981 {
10982#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10983 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10984 /* normalize result of wmemcmp() into the range [-1; 1] */
10985 if (cmp < 0)
10986 return -1;
10987 if (cmp > 0)
10988 return 1;
10989#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010990 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010991#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010992 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010993 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010994 default:
10995 assert(0);
10996 }
10997 break;
10998 }
10999 default:
11000 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000011001 }
11002
Victor Stinner770e19e2012-10-04 22:59:45 +020011003 if (len1 == len2)
11004 return 0;
11005 if (len1 < len2)
11006 return -1;
11007 else
11008 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011009
11010#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000011011}
11012
Benjamin Peterson621b4302016-09-09 13:54:34 -070011013static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020011014unicode_compare_eq(PyObject *str1, PyObject *str2)
11015{
11016 int kind;
11017 void *data1, *data2;
11018 Py_ssize_t len;
11019 int cmp;
11020
Victor Stinnere5567ad2012-10-23 02:48:49 +020011021 len = PyUnicode_GET_LENGTH(str1);
11022 if (PyUnicode_GET_LENGTH(str2) != len)
11023 return 0;
11024 kind = PyUnicode_KIND(str1);
11025 if (PyUnicode_KIND(str2) != kind)
11026 return 0;
11027 data1 = PyUnicode_DATA(str1);
11028 data2 = PyUnicode_DATA(str2);
11029
11030 cmp = memcmp(data1, data2, len * kind);
11031 return (cmp == 0);
11032}
11033
11034
Alexander Belopolsky40018472011-02-26 01:02:56 +000011035int
11036PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011037{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011038 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11039 if (PyUnicode_READY(left) == -1 ||
11040 PyUnicode_READY(right) == -1)
11041 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011042
11043 /* a string is equal to itself */
11044 if (left == right)
11045 return 0;
11046
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011047 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011048 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011049 PyErr_Format(PyExc_TypeError,
11050 "Can't compare %.100s and %.100s",
11051 left->ob_type->tp_name,
11052 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011053 return -1;
11054}
11055
Martin v. Löwis5b222132007-06-10 09:51:05 +000011056int
11057PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11058{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011059 Py_ssize_t i;
11060 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011061 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011062 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011063
Victor Stinner910337b2011-10-03 03:20:16 +020011064 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011065 if (!PyUnicode_IS_READY(uni)) {
11066 const wchar_t *ws = _PyUnicode_WSTR(uni);
11067 /* Compare Unicode string and source character set string */
11068 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11069 if (chr != ustr[i])
11070 return (chr < ustr[i]) ? -1 : 1;
11071 }
11072 /* This check keeps Python strings that end in '\0' from comparing equal
11073 to C strings identical up to that point. */
11074 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11075 return 1; /* uni is longer */
11076 if (ustr[i])
11077 return -1; /* str is longer */
11078 return 0;
11079 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011080 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011081 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011082 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011083 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011084 size_t len, len2 = strlen(str);
11085 int cmp;
11086
11087 len = Py_MIN(len1, len2);
11088 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011089 if (cmp != 0) {
11090 if (cmp < 0)
11091 return -1;
11092 else
11093 return 1;
11094 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011095 if (len1 > len2)
11096 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011097 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011098 return -1; /* str is longer */
11099 return 0;
11100 }
11101 else {
11102 void *data = PyUnicode_DATA(uni);
11103 /* Compare Unicode string and source character set string */
11104 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011105 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011106 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11107 /* This check keeps Python strings that end in '\0' from comparing equal
11108 to C strings identical up to that point. */
11109 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11110 return 1; /* uni is longer */
11111 if (str[i])
11112 return -1; /* str is longer */
11113 return 0;
11114 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011115}
11116
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011117static int
11118non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11119{
11120 size_t i, len;
11121 const wchar_t *p;
11122 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11123 if (strlen(str) != len)
11124 return 0;
11125 p = _PyUnicode_WSTR(unicode);
11126 assert(p);
11127 for (i = 0; i < len; i++) {
11128 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011129 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011130 return 0;
11131 }
11132 return 1;
11133}
11134
11135int
11136_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11137{
11138 size_t len;
11139 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011140 assert(str);
11141#ifndef NDEBUG
11142 for (const char *p = str; *p; p++) {
11143 assert((unsigned char)*p < 128);
11144 }
11145#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011146 if (PyUnicode_READY(unicode) == -1) {
11147 /* Memory error or bad data */
11148 PyErr_Clear();
11149 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11150 }
11151 if (!PyUnicode_IS_ASCII(unicode))
11152 return 0;
11153 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11154 return strlen(str) == len &&
11155 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11156}
11157
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011158int
11159_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11160{
11161 PyObject *right_uni;
11162 Py_hash_t hash;
11163
11164 assert(_PyUnicode_CHECK(left));
11165 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011166#ifndef NDEBUG
11167 for (const char *p = right->string; *p; p++) {
11168 assert((unsigned char)*p < 128);
11169 }
11170#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011171
11172 if (PyUnicode_READY(left) == -1) {
11173 /* memory error or bad data */
11174 PyErr_Clear();
11175 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11176 }
11177
11178 if (!PyUnicode_IS_ASCII(left))
11179 return 0;
11180
11181 right_uni = _PyUnicode_FromId(right); /* borrowed */
11182 if (right_uni == NULL) {
11183 /* memory error or bad data */
11184 PyErr_Clear();
11185 return _PyUnicode_EqualToASCIIString(left, right->string);
11186 }
11187
11188 if (left == right_uni)
11189 return 1;
11190
11191 if (PyUnicode_CHECK_INTERNED(left))
11192 return 0;
11193
11194 assert(_PyUnicode_HASH(right_uni) != 1);
11195 hash = _PyUnicode_HASH(left);
11196 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11197 return 0;
11198
11199 return unicode_compare_eq(left, right_uni);
11200}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011201
Benjamin Peterson29060642009-01-31 22:14:21 +000011202#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011203 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011204
Alexander Belopolsky40018472011-02-26 01:02:56 +000011205PyObject *
11206PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011207{
11208 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011209 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011210
Victor Stinnere5567ad2012-10-23 02:48:49 +020011211 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11212 Py_RETURN_NOTIMPLEMENTED;
11213
11214 if (PyUnicode_READY(left) == -1 ||
11215 PyUnicode_READY(right) == -1)
11216 return NULL;
11217
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011218 if (left == right) {
11219 switch (op) {
11220 case Py_EQ:
11221 case Py_LE:
11222 case Py_GE:
11223 /* a string is equal to itself */
11224 v = Py_True;
11225 break;
11226 case Py_NE:
11227 case Py_LT:
11228 case Py_GT:
11229 v = Py_False;
11230 break;
11231 default:
11232 PyErr_BadArgument();
11233 return NULL;
11234 }
11235 }
11236 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011237 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011238 result ^= (op == Py_NE);
11239 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011240 }
11241 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011242 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011243
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011244 /* Convert the return value to a Boolean */
11245 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011246 case Py_LE:
11247 v = TEST_COND(result <= 0);
11248 break;
11249 case Py_GE:
11250 v = TEST_COND(result >= 0);
11251 break;
11252 case Py_LT:
11253 v = TEST_COND(result == -1);
11254 break;
11255 case Py_GT:
11256 v = TEST_COND(result == 1);
11257 break;
11258 default:
11259 PyErr_BadArgument();
11260 return NULL;
11261 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011262 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011263 Py_INCREF(v);
11264 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011265}
11266
Alexander Belopolsky40018472011-02-26 01:02:56 +000011267int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011268_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11269{
11270 return unicode_eq(aa, bb);
11271}
11272
11273int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011274PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011275{
Victor Stinner77282cb2013-04-14 19:22:47 +020011276 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011277 void *buf1, *buf2;
11278 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011279 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011280
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011281 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011282 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011283 "'in <string>' requires string as left operand, not %.100s",
11284 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011285 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011286 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011287 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011288 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011289 if (ensure_unicode(str) < 0)
11290 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011292 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011293 kind2 = PyUnicode_KIND(substr);
11294 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011295 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011296 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011297 len2 = PyUnicode_GET_LENGTH(substr);
11298 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011299 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011300 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011301 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011302 if (len2 == 1) {
11303 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11304 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011305 return result;
11306 }
11307 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011308 buf2 = _PyUnicode_AsKind(substr, kind1);
11309 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011310 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011311 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312
Victor Stinner77282cb2013-04-14 19:22:47 +020011313 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 case PyUnicode_1BYTE_KIND:
11315 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11316 break;
11317 case PyUnicode_2BYTE_KIND:
11318 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11319 break;
11320 case PyUnicode_4BYTE_KIND:
11321 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11322 break;
11323 default:
11324 result = -1;
11325 assert(0);
11326 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011327
Victor Stinner77282cb2013-04-14 19:22:47 +020011328 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011329 PyMem_Free(buf2);
11330
Guido van Rossum403d68b2000-03-13 15:55:09 +000011331 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011332}
11333
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334/* Concat to string or Unicode object giving a new Unicode object. */
11335
Alexander Belopolsky40018472011-02-26 01:02:56 +000011336PyObject *
11337PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011339 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011340 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011341 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011343 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11344 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345
11346 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011347 if (left == unicode_empty)
11348 return PyUnicode_FromObject(right);
11349 if (right == unicode_empty)
11350 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011352 left_len = PyUnicode_GET_LENGTH(left);
11353 right_len = PyUnicode_GET_LENGTH(right);
11354 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011355 PyErr_SetString(PyExc_OverflowError,
11356 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011357 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011358 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011359 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011360
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011361 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11362 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011363 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011364
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011366 result = PyUnicode_New(new_len, maxchar);
11367 if (result == NULL)
11368 return NULL;
11369 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11370 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11371 assert(_PyUnicode_CheckConsistency(result, 1));
11372 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373}
11374
Walter Dörwald1ab83302007-05-18 17:15:44 +000011375void
Victor Stinner23e56682011-10-03 03:54:37 +020011376PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011377{
Victor Stinner23e56682011-10-03 03:54:37 +020011378 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011379 Py_UCS4 maxchar, maxchar2;
11380 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011381
11382 if (p_left == NULL) {
11383 if (!PyErr_Occurred())
11384 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011385 return;
11386 }
Victor Stinner23e56682011-10-03 03:54:37 +020011387 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011388 if (right == NULL || left == NULL
11389 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011390 if (!PyErr_Occurred())
11391 PyErr_BadInternalCall();
11392 goto error;
11393 }
11394
Benjamin Petersonbac79492012-01-14 13:34:47 -050011395 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011396 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011397 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011398 goto error;
11399
Victor Stinner488fa492011-12-12 00:01:39 +010011400 /* Shortcuts */
11401 if (left == unicode_empty) {
11402 Py_DECREF(left);
11403 Py_INCREF(right);
11404 *p_left = right;
11405 return;
11406 }
11407 if (right == unicode_empty)
11408 return;
11409
11410 left_len = PyUnicode_GET_LENGTH(left);
11411 right_len = PyUnicode_GET_LENGTH(right);
11412 if (left_len > PY_SSIZE_T_MAX - right_len) {
11413 PyErr_SetString(PyExc_OverflowError,
11414 "strings are too large to concat");
11415 goto error;
11416 }
11417 new_len = left_len + right_len;
11418
11419 if (unicode_modifiable(left)
11420 && PyUnicode_CheckExact(right)
11421 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011422 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11423 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011424 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011425 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011426 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11427 {
11428 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011429 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011430 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011431
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011432 /* copy 'right' into the newly allocated area of 'left' */
11433 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011434 }
Victor Stinner488fa492011-12-12 00:01:39 +010011435 else {
11436 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11437 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011438 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011439
Victor Stinner488fa492011-12-12 00:01:39 +010011440 /* Concat the two Unicode strings */
11441 res = PyUnicode_New(new_len, maxchar);
11442 if (res == NULL)
11443 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011444 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11445 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011446 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011447 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011448 }
11449 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011450 return;
11451
11452error:
Victor Stinner488fa492011-12-12 00:01:39 +010011453 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011454}
11455
11456void
11457PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11458{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011459 PyUnicode_Append(pleft, right);
11460 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011461}
11462
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011463/*
11464Wraps stringlib_parse_args_finds() and additionally ensures that the
11465first argument is a unicode object.
11466*/
11467
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011468static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011469parse_args_finds_unicode(const char * function_name, PyObject *args,
11470 PyObject **substring,
11471 Py_ssize_t *start, Py_ssize_t *end)
11472{
11473 if(stringlib_parse_args_finds(function_name, args, substring,
11474 start, end)) {
11475 if (ensure_unicode(*substring) < 0)
11476 return 0;
11477 return 1;
11478 }
11479 return 0;
11480}
11481
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011482PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011485Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011486string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011487interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488
11489static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011490unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011492 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011493 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011494 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011496 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011497 void *buf1, *buf2;
11498 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011500 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011501 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011503 kind1 = PyUnicode_KIND(self);
11504 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011505 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011506 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011507
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011508 len1 = PyUnicode_GET_LENGTH(self);
11509 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011511 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011512 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011513
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011514 buf1 = PyUnicode_DATA(self);
11515 buf2 = PyUnicode_DATA(substring);
11516 if (kind2 != kind1) {
11517 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011518 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011519 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011520 }
11521 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011522 case PyUnicode_1BYTE_KIND:
11523 iresult = ucs1lib_count(
11524 ((Py_UCS1*)buf1) + start, end - start,
11525 buf2, len2, PY_SSIZE_T_MAX
11526 );
11527 break;
11528 case PyUnicode_2BYTE_KIND:
11529 iresult = ucs2lib_count(
11530 ((Py_UCS2*)buf1) + start, end - start,
11531 buf2, len2, PY_SSIZE_T_MAX
11532 );
11533 break;
11534 case PyUnicode_4BYTE_KIND:
11535 iresult = ucs4lib_count(
11536 ((Py_UCS4*)buf1) + start, end - start,
11537 buf2, len2, PY_SSIZE_T_MAX
11538 );
11539 break;
11540 default:
11541 assert(0); iresult = 0;
11542 }
11543
11544 result = PyLong_FromSsize_t(iresult);
11545
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011546 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549 return result;
11550}
11551
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011552PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011553 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011555Encode S using the codec registered for encoding. Default encoding\n\
11556is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011557handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011558a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11559'xmlcharrefreplace' as well as any other name registered with\n\
11560codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561
11562static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011563unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011565 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566 char *encoding = NULL;
11567 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011568
Benjamin Peterson308d6372009-09-18 21:42:35 +000011569 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11570 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011572 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011573}
11574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011575PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011576 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577\n\
11578Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011579If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580
11581static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011582unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011584 Py_ssize_t i, j, line_pos, src_len, incr;
11585 Py_UCS4 ch;
11586 PyObject *u;
11587 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011588 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011590 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011591 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592
Ezio Melotti745d54d2013-11-16 19:10:57 +020011593 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11594 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011595 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596
Antoine Pitrou22425222011-10-04 19:10:51 +020011597 if (PyUnicode_READY(self) == -1)
11598 return NULL;
11599
Thomas Wouters7e474022000-07-16 12:04:32 +000011600 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011601 src_len = PyUnicode_GET_LENGTH(self);
11602 i = j = line_pos = 0;
11603 kind = PyUnicode_KIND(self);
11604 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011605 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011606 for (; i < src_len; i++) {
11607 ch = PyUnicode_READ(kind, src_data, i);
11608 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011609 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011610 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011611 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011612 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011613 goto overflow;
11614 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011615 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011616 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011617 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011619 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011620 goto overflow;
11621 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011623 if (ch == '\n' || ch == '\r')
11624 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011626 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011627 if (!found)
11628 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011629
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011631 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011632 if (!u)
11633 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011634 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011635
Antoine Pitroue71d5742011-10-04 15:55:09 +020011636 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011637
Antoine Pitroue71d5742011-10-04 15:55:09 +020011638 for (; i < src_len; i++) {
11639 ch = PyUnicode_READ(kind, src_data, i);
11640 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011641 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011642 incr = tabsize - (line_pos % tabsize);
11643 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011644 FILL(kind, dest_data, ' ', j, incr);
11645 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011646 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011647 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011648 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011649 line_pos++;
11650 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011651 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011652 if (ch == '\n' || ch == '\r')
11653 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011654 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011655 }
11656 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011657 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011658
Antoine Pitroue71d5742011-10-04 15:55:09 +020011659 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011660 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11661 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662}
11663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011664PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011665 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666\n\
11667Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011668such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011669arguments start and end are interpreted as in slice notation.\n\
11670\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011671Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672
11673static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011676 /* initialize variables to prevent gcc warning */
11677 PyObject *substring = NULL;
11678 Py_ssize_t start = 0;
11679 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011680 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011682 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011685 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011687
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011688 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011689
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 if (result == -2)
11691 return NULL;
11692
Christian Heimes217cfd12007-12-02 14:31:20 +000011693 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694}
11695
11696static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011697unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011699 void *data;
11700 enum PyUnicode_Kind kind;
11701 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011702
11703 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11704 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011706 }
11707 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11708 PyErr_SetString(PyExc_IndexError, "string index out of range");
11709 return NULL;
11710 }
11711 kind = PyUnicode_KIND(self);
11712 data = PyUnicode_DATA(self);
11713 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011714 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715}
11716
Guido van Rossumc2504932007-09-18 19:42:40 +000011717/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011718 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011719static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011720unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721{
Guido van Rossumc2504932007-09-18 19:42:40 +000011722 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011723 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011724
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011725#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011726 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011727#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011728 if (_PyUnicode_HASH(self) != -1)
11729 return _PyUnicode_HASH(self);
11730 if (PyUnicode_READY(self) == -1)
11731 return -1;
11732 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011733 /*
11734 We make the hash of the empty string be 0, rather than using
11735 (prefix ^ suffix), since this slightly obfuscates the hash secret
11736 */
11737 if (len == 0) {
11738 _PyUnicode_HASH(self) = 0;
11739 return 0;
11740 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011741 x = _Py_HashBytes(PyUnicode_DATA(self),
11742 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011744 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745}
11746
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011747PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011748 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749\n\
Mariatta577fc042017-04-09 15:17:06 -070011750Return the lowest index in S where substring sub is found, \n\
11751such that sub is contained within S[start:end]. Optional\n\
11752arguments start and end are interpreted as in slice notation.\n\
11753\n\
11754Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755
11756static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011757unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011759 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011760 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011761 PyObject *substring = NULL;
11762 Py_ssize_t start = 0;
11763 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011765 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011767
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011768 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011771 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011772
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011773 if (result == -2)
11774 return NULL;
11775
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776 if (result < 0) {
11777 PyErr_SetString(PyExc_ValueError, "substring not found");
11778 return NULL;
11779 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011780
Christian Heimes217cfd12007-12-02 14:31:20 +000011781 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782}
11783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011784PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011785 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011787Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011788at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789
11790static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011791unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011793 Py_ssize_t i, length;
11794 int kind;
11795 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796 int cased;
11797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 if (PyUnicode_READY(self) == -1)
11799 return NULL;
11800 length = PyUnicode_GET_LENGTH(self);
11801 kind = PyUnicode_KIND(self);
11802 data = PyUnicode_DATA(self);
11803
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805 if (length == 1)
11806 return PyBool_FromLong(
11807 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011808
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011809 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011811 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011812
Guido van Rossumd57fd912000-03-10 22:53:23 +000011813 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011814 for (i = 0; i < length; i++) {
11815 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011816
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11818 return PyBool_FromLong(0);
11819 else if (!cased && Py_UNICODE_ISLOWER(ch))
11820 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011822 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011823}
11824
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011825PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011826 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011828Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011829at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830
11831static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011832unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011834 Py_ssize_t i, length;
11835 int kind;
11836 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837 int cased;
11838
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011839 if (PyUnicode_READY(self) == -1)
11840 return NULL;
11841 length = PyUnicode_GET_LENGTH(self);
11842 kind = PyUnicode_KIND(self);
11843 data = PyUnicode_DATA(self);
11844
Guido van Rossumd57fd912000-03-10 22:53:23 +000011845 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 if (length == 1)
11847 return PyBool_FromLong(
11848 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011850 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011851 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011852 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011853
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011855 for (i = 0; i < length; i++) {
11856 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011857
Benjamin Peterson29060642009-01-31 22:14:21 +000011858 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11859 return PyBool_FromLong(0);
11860 else if (!cased && Py_UNICODE_ISUPPER(ch))
11861 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011863 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011864}
11865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011866PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011867 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011869Return True if S is a titlecased string and there is at least one\n\
11870character in S, i.e. upper- and titlecase characters may only\n\
11871follow uncased characters and lowercase characters only cased ones.\n\
11872Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873
11874static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011875unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011877 Py_ssize_t i, length;
11878 int kind;
11879 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880 int cased, previous_is_cased;
11881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 if (PyUnicode_READY(self) == -1)
11883 return NULL;
11884 length = PyUnicode_GET_LENGTH(self);
11885 kind = PyUnicode_KIND(self);
11886 data = PyUnicode_DATA(self);
11887
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 if (length == 1) {
11890 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11891 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11892 (Py_UNICODE_ISUPPER(ch) != 0));
11893 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011895 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011896 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011897 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011898
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899 cased = 0;
11900 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901 for (i = 0; i < length; i++) {
11902 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011903
Benjamin Peterson29060642009-01-31 22:14:21 +000011904 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11905 if (previous_is_cased)
11906 return PyBool_FromLong(0);
11907 previous_is_cased = 1;
11908 cased = 1;
11909 }
11910 else if (Py_UNICODE_ISLOWER(ch)) {
11911 if (!previous_is_cased)
11912 return PyBool_FromLong(0);
11913 previous_is_cased = 1;
11914 cased = 1;
11915 }
11916 else
11917 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011918 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011919 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920}
11921
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011922PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011923 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011925Return True if all characters in S are whitespace\n\
11926and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927
11928static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011929unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931 Py_ssize_t i, length;
11932 int kind;
11933 void *data;
11934
11935 if (PyUnicode_READY(self) == -1)
11936 return NULL;
11937 length = PyUnicode_GET_LENGTH(self);
11938 kind = PyUnicode_KIND(self);
11939 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011942 if (length == 1)
11943 return PyBool_FromLong(
11944 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011946 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011948 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011950 for (i = 0; i < length; i++) {
11951 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011952 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011953 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011955 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011956}
11957
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011958PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011959 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011960\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011961Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011962and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011963
11964static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011965unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011966{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011967 Py_ssize_t i, length;
11968 int kind;
11969 void *data;
11970
11971 if (PyUnicode_READY(self) == -1)
11972 return NULL;
11973 length = PyUnicode_GET_LENGTH(self);
11974 kind = PyUnicode_KIND(self);
11975 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011976
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011977 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011978 if (length == 1)
11979 return PyBool_FromLong(
11980 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011981
11982 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011984 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011985
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011986 for (i = 0; i < length; i++) {
11987 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011988 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011989 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011990 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011991}
11992
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011993PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011994 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011995\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011996Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011997and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011998
11999static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012000unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012001{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 int kind;
12003 void *data;
12004 Py_ssize_t len, i;
12005
12006 if (PyUnicode_READY(self) == -1)
12007 return NULL;
12008
12009 kind = PyUnicode_KIND(self);
12010 data = PyUnicode_DATA(self);
12011 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012012
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012013 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 if (len == 1) {
12015 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12016 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12017 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012018
12019 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012020 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012021 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023 for (i = 0; i < len; i++) {
12024 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012025 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000012026 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012027 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012028 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012029}
12030
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012031PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012032 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000012034Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012035False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012036
12037static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012038unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012039{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 Py_ssize_t i, length;
12041 int kind;
12042 void *data;
12043
12044 if (PyUnicode_READY(self) == -1)
12045 return NULL;
12046 length = PyUnicode_GET_LENGTH(self);
12047 kind = PyUnicode_KIND(self);
12048 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012049
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012051 if (length == 1)
12052 return PyBool_FromLong(
12053 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012054
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012055 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012056 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012057 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012059 for (i = 0; i < length; i++) {
12060 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012061 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012062 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012063 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012064}
12065
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012066PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012067 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012068\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000012069Return True if all characters in S are digits\n\
12070and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012071
12072static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012073unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012074{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012075 Py_ssize_t i, length;
12076 int kind;
12077 void *data;
12078
12079 if (PyUnicode_READY(self) == -1)
12080 return NULL;
12081 length = PyUnicode_GET_LENGTH(self);
12082 kind = PyUnicode_KIND(self);
12083 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012084
Guido van Rossumd57fd912000-03-10 22:53:23 +000012085 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012086 if (length == 1) {
12087 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12088 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12089 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012091 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012092 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012093 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012094
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012095 for (i = 0; i < length; i++) {
12096 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012097 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012099 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012100}
12101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012102PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012103 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000012105Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012106False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012107
12108static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012109unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012111 Py_ssize_t i, length;
12112 int kind;
12113 void *data;
12114
12115 if (PyUnicode_READY(self) == -1)
12116 return NULL;
12117 length = PyUnicode_GET_LENGTH(self);
12118 kind = PyUnicode_KIND(self);
12119 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120
Guido van Rossumd57fd912000-03-10 22:53:23 +000012121 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012122 if (length == 1)
12123 return PyBool_FromLong(
12124 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012126 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012128 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012129
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012130 for (i = 0; i < length; i++) {
12131 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012132 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012134 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012135}
12136
Martin v. Löwis47383402007-08-15 07:32:56 +000012137int
12138PyUnicode_IsIdentifier(PyObject *self)
12139{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012140 int kind;
12141 void *data;
12142 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012143 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012144
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012145 if (PyUnicode_READY(self) == -1) {
12146 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012147 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012148 }
12149
12150 /* Special case for empty strings */
12151 if (PyUnicode_GET_LENGTH(self) == 0)
12152 return 0;
12153 kind = PyUnicode_KIND(self);
12154 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012155
12156 /* PEP 3131 says that the first character must be in
12157 XID_Start and subsequent characters in XID_Continue,
12158 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012159 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012160 letters, digits, underscore). However, given the current
12161 definition of XID_Start and XID_Continue, it is sufficient
12162 to check just for these, except that _ must be allowed
12163 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012164 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012165 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012166 return 0;
12167
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012168 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012169 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012170 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012171 return 1;
12172}
12173
12174PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012175 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012176\n\
12177Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012178to the language definition.\n\
12179\n\
12180Use keyword.iskeyword() to test for reserved identifiers\n\
12181such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012182
12183static PyObject*
12184unicode_isidentifier(PyObject *self)
12185{
12186 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12187}
12188
Georg Brandl559e5d72008-06-11 18:37:52 +000012189PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012190 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012191\n\
12192Return True if all characters in S are considered\n\
12193printable in repr() or S is empty, False otherwise.");
12194
12195static PyObject*
12196unicode_isprintable(PyObject *self)
12197{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012198 Py_ssize_t i, length;
12199 int kind;
12200 void *data;
12201
12202 if (PyUnicode_READY(self) == -1)
12203 return NULL;
12204 length = PyUnicode_GET_LENGTH(self);
12205 kind = PyUnicode_KIND(self);
12206 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012207
12208 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 if (length == 1)
12210 return PyBool_FromLong(
12211 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 for (i = 0; i < length; i++) {
12214 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012215 Py_RETURN_FALSE;
12216 }
12217 }
12218 Py_RETURN_TRUE;
12219}
12220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012221PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012222 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223\n\
12224Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012225iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226
12227static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012228unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012229{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012230 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231}
12232
Martin v. Löwis18e16552006-02-15 17:27:45 +000012233static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012234unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012235{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236 if (PyUnicode_READY(self) == -1)
12237 return -1;
12238 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012239}
12240
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012241PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012242 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012244Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012245done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012246
12247static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012248unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012250 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012251 Py_UCS4 fillchar = ' ';
12252
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012253 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254 return NULL;
12255
Benjamin Petersonbac79492012-01-14 13:34:47 -050012256 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012257 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012258
Victor Stinnerc4b49542011-12-11 22:44:26 +010012259 if (PyUnicode_GET_LENGTH(self) >= width)
12260 return unicode_result_unchanged(self);
12261
12262 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263}
12264
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012265PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012266 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012268Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012269
12270static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012271unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012273 if (PyUnicode_READY(self) == -1)
12274 return NULL;
12275 if (PyUnicode_IS_ASCII(self))
12276 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012277 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278}
12279
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012280#define LEFTSTRIP 0
12281#define RIGHTSTRIP 1
12282#define BOTHSTRIP 2
12283
12284/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012285static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012286
12287#define STRIPNAME(i) (stripformat[i]+3)
12288
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012289/* externally visible for str.strip(unicode) */
12290PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012291_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012292{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012293 void *data;
12294 int kind;
12295 Py_ssize_t i, j, len;
12296 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012297 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012298
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012299 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12300 return NULL;
12301
12302 kind = PyUnicode_KIND(self);
12303 data = PyUnicode_DATA(self);
12304 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012305 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12307 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012308 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012309
Benjamin Peterson14339b62009-01-31 16:36:08 +000012310 i = 0;
12311 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012312 while (i < len) {
12313 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12314 if (!BLOOM(sepmask, ch))
12315 break;
12316 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12317 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012318 i++;
12319 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012320 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012321
Benjamin Peterson14339b62009-01-31 16:36:08 +000012322 j = len;
12323 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012324 j--;
12325 while (j >= i) {
12326 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12327 if (!BLOOM(sepmask, ch))
12328 break;
12329 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12330 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012331 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012332 }
12333
Benjamin Peterson29060642009-01-31 22:14:21 +000012334 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012335 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012336
Victor Stinner7931d9a2011-11-04 00:22:48 +010012337 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012338}
12339
12340PyObject*
12341PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12342{
12343 unsigned char *data;
12344 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012345 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012346
Victor Stinnerde636f32011-10-01 03:55:54 +020012347 if (PyUnicode_READY(self) == -1)
12348 return NULL;
12349
Victor Stinner684d5fd2012-05-03 02:32:34 +020012350 length = PyUnicode_GET_LENGTH(self);
12351 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012352
Victor Stinner684d5fd2012-05-03 02:32:34 +020012353 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012354 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355
Victor Stinnerde636f32011-10-01 03:55:54 +020012356 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012357 PyErr_SetString(PyExc_IndexError, "string index out of range");
12358 return NULL;
12359 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012360 if (start >= length || end < start)
12361 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012362
Victor Stinner684d5fd2012-05-03 02:32:34 +020012363 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012364 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012365 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012366 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012367 }
12368 else {
12369 kind = PyUnicode_KIND(self);
12370 data = PyUnicode_1BYTE_DATA(self);
12371 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012372 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012373 length);
12374 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012375}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012376
12377static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012378do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012379{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380 Py_ssize_t len, i, j;
12381
12382 if (PyUnicode_READY(self) == -1)
12383 return NULL;
12384
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012385 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012386
Victor Stinnercc7af722013-04-09 22:39:24 +020012387 if (PyUnicode_IS_ASCII(self)) {
12388 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12389
12390 i = 0;
12391 if (striptype != RIGHTSTRIP) {
12392 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012393 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012394 if (!_Py_ascii_whitespace[ch])
12395 break;
12396 i++;
12397 }
12398 }
12399
12400 j = len;
12401 if (striptype != LEFTSTRIP) {
12402 j--;
12403 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012404 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012405 if (!_Py_ascii_whitespace[ch])
12406 break;
12407 j--;
12408 }
12409 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012410 }
12411 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012412 else {
12413 int kind = PyUnicode_KIND(self);
12414 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012415
Victor Stinnercc7af722013-04-09 22:39:24 +020012416 i = 0;
12417 if (striptype != RIGHTSTRIP) {
12418 while (i < len) {
12419 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12420 if (!Py_UNICODE_ISSPACE(ch))
12421 break;
12422 i++;
12423 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012424 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012425
12426 j = len;
12427 if (striptype != LEFTSTRIP) {
12428 j--;
12429 while (j >= i) {
12430 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12431 if (!Py_UNICODE_ISSPACE(ch))
12432 break;
12433 j--;
12434 }
12435 j++;
12436 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012437 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012438
Victor Stinner7931d9a2011-11-04 00:22:48 +010012439 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012440}
12441
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012442
12443static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012444do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012445{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012446 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012447
Serhiy Storchakac6792272013-10-19 21:03:34 +030012448 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012449 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012450
Benjamin Peterson14339b62009-01-31 16:36:08 +000012451 if (sep != NULL && sep != Py_None) {
12452 if (PyUnicode_Check(sep))
12453 return _PyUnicode_XStrip(self, striptype, sep);
12454 else {
12455 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012456 "%s arg must be None or str",
12457 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012458 return NULL;
12459 }
12460 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012461
Benjamin Peterson14339b62009-01-31 16:36:08 +000012462 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012463}
12464
12465
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012466PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012467 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012468\n\
12469Return a copy of the string S with leading and trailing\n\
12470whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012471If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012472
12473static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012474unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012475{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012476 if (PyTuple_GET_SIZE(args) == 0)
12477 return do_strip(self, BOTHSTRIP); /* Common case */
12478 else
12479 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012480}
12481
12482
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012483PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012484 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012485\n\
12486Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012487If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012488
12489static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012490unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012491{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012492 if (PyTuple_GET_SIZE(args) == 0)
12493 return do_strip(self, LEFTSTRIP); /* Common case */
12494 else
12495 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012496}
12497
12498
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012499PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012500 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012501\n\
12502Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012503If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012504
12505static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012506unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012507{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012508 if (PyTuple_GET_SIZE(args) == 0)
12509 return do_strip(self, RIGHTSTRIP); /* Common case */
12510 else
12511 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012512}
12513
12514
Guido van Rossumd57fd912000-03-10 22:53:23 +000012515static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012516unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012517{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012518 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012519 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520
Serhiy Storchaka05997252013-01-26 12:14:02 +020012521 if (len < 1)
12522 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523
Victor Stinnerc4b49542011-12-11 22:44:26 +010012524 /* no repeat, return original string */
12525 if (len == 1)
12526 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012527
Benjamin Petersonbac79492012-01-14 13:34:47 -050012528 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012529 return NULL;
12530
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012531 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012532 PyErr_SetString(PyExc_OverflowError,
12533 "repeated string is too long");
12534 return NULL;
12535 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012536 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012537
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012538 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539 if (!u)
12540 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012541 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543 if (PyUnicode_GET_LENGTH(str) == 1) {
12544 const int kind = PyUnicode_KIND(str);
12545 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012546 if (kind == PyUnicode_1BYTE_KIND) {
12547 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012548 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012549 }
12550 else if (kind == PyUnicode_2BYTE_KIND) {
12551 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012552 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012553 ucs2[n] = fill_char;
12554 } else {
12555 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12556 assert(kind == PyUnicode_4BYTE_KIND);
12557 for (n = 0; n < len; ++n)
12558 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012559 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 }
12561 else {
12562 /* number of characters copied this far */
12563 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012564 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012566 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012568 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012569 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012570 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012571 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012572 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012573 }
12574
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012575 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012576 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012577}
12578
Alexander Belopolsky40018472011-02-26 01:02:56 +000012579PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012580PyUnicode_Replace(PyObject *str,
12581 PyObject *substr,
12582 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012583 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012585 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12586 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012587 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012588 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589}
12590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012591PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012592 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012593\n\
12594Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012595old replaced by new. If the optional argument count is\n\
12596given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012597
12598static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012599unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012601 PyObject *str1;
12602 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012603 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012604
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012605 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012607 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012608 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012609 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610}
12611
Alexander Belopolsky40018472011-02-26 01:02:56 +000012612static PyObject *
12613unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012614{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012615 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012616 Py_ssize_t isize;
12617 Py_ssize_t osize, squote, dquote, i, o;
12618 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012619 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012620 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012621
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012622 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012623 return NULL;
12624
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012625 isize = PyUnicode_GET_LENGTH(unicode);
12626 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012627
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012628 /* Compute length of output, quote characters, and
12629 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012630 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012631 max = 127;
12632 squote = dquote = 0;
12633 ikind = PyUnicode_KIND(unicode);
12634 for (i = 0; i < isize; i++) {
12635 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012636 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012637 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012638 case '\'': squote++; break;
12639 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012640 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012641 incr = 2;
12642 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012643 default:
12644 /* Fast-path ASCII */
12645 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012646 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012647 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012648 ;
12649 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012650 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012651 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012652 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012654 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012655 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012656 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012657 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012658 if (osize > PY_SSIZE_T_MAX - incr) {
12659 PyErr_SetString(PyExc_OverflowError,
12660 "string is too long to generate repr");
12661 return NULL;
12662 }
12663 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012664 }
12665
12666 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012667 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012668 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012669 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012670 if (dquote)
12671 /* Both squote and dquote present. Use squote,
12672 and escape them */
12673 osize += squote;
12674 else
12675 quote = '"';
12676 }
Victor Stinner55c08782013-04-14 18:45:39 +020012677 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012678
12679 repr = PyUnicode_New(osize, max);
12680 if (repr == NULL)
12681 return NULL;
12682 okind = PyUnicode_KIND(repr);
12683 odata = PyUnicode_DATA(repr);
12684
12685 PyUnicode_WRITE(okind, odata, 0, quote);
12686 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012687 if (unchanged) {
12688 _PyUnicode_FastCopyCharacters(repr, 1,
12689 unicode, 0,
12690 isize);
12691 }
12692 else {
12693 for (i = 0, o = 1; i < isize; i++) {
12694 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012695
Victor Stinner55c08782013-04-14 18:45:39 +020012696 /* Escape quotes and backslashes */
12697 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012698 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012699 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012700 continue;
12701 }
12702
12703 /* Map special whitespace to '\t', \n', '\r' */
12704 if (ch == '\t') {
12705 PyUnicode_WRITE(okind, odata, o++, '\\');
12706 PyUnicode_WRITE(okind, odata, o++, 't');
12707 }
12708 else if (ch == '\n') {
12709 PyUnicode_WRITE(okind, odata, o++, '\\');
12710 PyUnicode_WRITE(okind, odata, o++, 'n');
12711 }
12712 else if (ch == '\r') {
12713 PyUnicode_WRITE(okind, odata, o++, '\\');
12714 PyUnicode_WRITE(okind, odata, o++, 'r');
12715 }
12716
12717 /* Map non-printable US ASCII to '\xhh' */
12718 else if (ch < ' ' || ch == 0x7F) {
12719 PyUnicode_WRITE(okind, odata, o++, '\\');
12720 PyUnicode_WRITE(okind, odata, o++, 'x');
12721 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12722 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12723 }
12724
12725 /* Copy ASCII characters as-is */
12726 else if (ch < 0x7F) {
12727 PyUnicode_WRITE(okind, odata, o++, ch);
12728 }
12729
12730 /* Non-ASCII characters */
12731 else {
12732 /* Map Unicode whitespace and control characters
12733 (categories Z* and C* except ASCII space)
12734 */
12735 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12736 PyUnicode_WRITE(okind, odata, o++, '\\');
12737 /* Map 8-bit characters to '\xhh' */
12738 if (ch <= 0xff) {
12739 PyUnicode_WRITE(okind, odata, o++, 'x');
12740 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12741 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12742 }
12743 /* Map 16-bit characters to '\uxxxx' */
12744 else if (ch <= 0xffff) {
12745 PyUnicode_WRITE(okind, odata, o++, 'u');
12746 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12747 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12748 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12749 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12750 }
12751 /* Map 21-bit characters to '\U00xxxxxx' */
12752 else {
12753 PyUnicode_WRITE(okind, odata, o++, 'U');
12754 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12755 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12756 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12757 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12758 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12759 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12760 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12761 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12762 }
12763 }
12764 /* Copy characters as-is */
12765 else {
12766 PyUnicode_WRITE(okind, odata, o++, ch);
12767 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012768 }
12769 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012770 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012771 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012772 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012773 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012774}
12775
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012776PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012777 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778\n\
12779Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012780such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012781arguments start and end are interpreted as in slice notation.\n\
12782\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012783Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784
12785static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012786unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012788 /* initialize variables to prevent gcc warning */
12789 PyObject *substring = NULL;
12790 Py_ssize_t start = 0;
12791 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012792 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012794 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012795 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012797 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012798 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012799
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012800 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012802 if (result == -2)
12803 return NULL;
12804
Christian Heimes217cfd12007-12-02 14:31:20 +000012805 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806}
12807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012808PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012809 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810\n\
Mariatta577fc042017-04-09 15:17:06 -070012811Return the highest index in S where substring sub is found,\n\
12812such that sub is contained within S[start:end]. Optional\n\
12813arguments start and end are interpreted as in slice notation.\n\
12814\n\
12815Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816
12817static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012818unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012819{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012820 /* initialize variables to prevent gcc warning */
12821 PyObject *substring = NULL;
12822 Py_ssize_t start = 0;
12823 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012824 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012826 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012827 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012829 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012830 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012831
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012832 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012834 if (result == -2)
12835 return NULL;
12836
Guido van Rossumd57fd912000-03-10 22:53:23 +000012837 if (result < 0) {
12838 PyErr_SetString(PyExc_ValueError, "substring not found");
12839 return NULL;
12840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012841
Christian Heimes217cfd12007-12-02 14:31:20 +000012842 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843}
12844
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012845PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012846 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012847\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012848Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012849done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012850
12851static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012852unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012854 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012855 Py_UCS4 fillchar = ' ';
12856
Victor Stinnere9a29352011-10-01 02:14:59 +020012857 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012858 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012859
Benjamin Petersonbac79492012-01-14 13:34:47 -050012860 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012861 return NULL;
12862
Victor Stinnerc4b49542011-12-11 22:44:26 +010012863 if (PyUnicode_GET_LENGTH(self) >= width)
12864 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012865
Victor Stinnerc4b49542011-12-11 22:44:26 +010012866 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012867}
12868
Alexander Belopolsky40018472011-02-26 01:02:56 +000012869PyObject *
12870PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012871{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012872 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012873 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012874
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012875 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012876}
12877
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012878PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012879 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012880\n\
12881Return a list of the words in S, using sep as the\n\
12882delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012883splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012884whitespace string is a separator and empty strings are\n\
12885removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886
12887static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012888unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012889{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012890 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012892 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012893
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012894 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12895 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012896 return NULL;
12897
12898 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012899 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012900
12901 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012902 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012903
12904 PyErr_Format(PyExc_TypeError,
12905 "must be str or None, not %.100s",
12906 Py_TYPE(substring)->tp_name);
12907 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012908}
12909
Thomas Wouters477c8d52006-05-27 19:21:47 +000012910PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012911PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012912{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012913 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012914 int kind1, kind2;
12915 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012916 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012917
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012918 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012919 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012920
Victor Stinner14f8f022011-10-05 20:58:25 +020012921 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012922 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012923 len1 = PyUnicode_GET_LENGTH(str_obj);
12924 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012925 if (kind1 < kind2 || len1 < len2) {
12926 _Py_INCREF_UNICODE_EMPTY();
12927 if (!unicode_empty)
12928 out = NULL;
12929 else {
12930 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12931 Py_DECREF(unicode_empty);
12932 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012933 return out;
12934 }
12935 buf1 = PyUnicode_DATA(str_obj);
12936 buf2 = PyUnicode_DATA(sep_obj);
12937 if (kind2 != kind1) {
12938 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12939 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012940 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012941 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012942
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012943 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012944 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012945 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12946 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12947 else
12948 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012949 break;
12950 case PyUnicode_2BYTE_KIND:
12951 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12952 break;
12953 case PyUnicode_4BYTE_KIND:
12954 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12955 break;
12956 default:
12957 assert(0);
12958 out = 0;
12959 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012960
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012961 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012962 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012963
12964 return out;
12965}
12966
12967
12968PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012969PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012970{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012971 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012972 int kind1, kind2;
12973 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012974 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012975
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012976 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012977 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012978
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012979 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012980 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012981 len1 = PyUnicode_GET_LENGTH(str_obj);
12982 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012983 if (kind1 < kind2 || len1 < len2) {
12984 _Py_INCREF_UNICODE_EMPTY();
12985 if (!unicode_empty)
12986 out = NULL;
12987 else {
12988 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12989 Py_DECREF(unicode_empty);
12990 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012991 return out;
12992 }
12993 buf1 = PyUnicode_DATA(str_obj);
12994 buf2 = PyUnicode_DATA(sep_obj);
12995 if (kind2 != kind1) {
12996 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12997 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012998 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012999 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013001 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013003 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13004 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13005 else
13006 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013007 break;
13008 case PyUnicode_2BYTE_KIND:
13009 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13010 break;
13011 case PyUnicode_4BYTE_KIND:
13012 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13013 break;
13014 default:
13015 assert(0);
13016 out = 0;
13017 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013018
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013019 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013020 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013021
13022 return out;
13023}
13024
13025PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013026 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013027\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013028Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013029the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013030found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013031
13032static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013033unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013034{
Victor Stinner9310abb2011-10-05 00:59:23 +020013035 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013036}
13037
13038PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000013039 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013040\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000013041Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000013042the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013043separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013044
13045static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013046unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013047{
Victor Stinner9310abb2011-10-05 00:59:23 +020013048 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013049}
13050
Alexander Belopolsky40018472011-02-26 01:02:56 +000013051PyObject *
13052PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013053{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013054 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013055 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013056
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013057 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013058}
13059
13060PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013061 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013062\n\
13063Return a list of the words in S, using sep as the\n\
13064delimiter string, starting at the end of the string and\n\
13065working to the front. If maxsplit is given, at most maxsplit\n\
13066splits are done. If sep is not specified, any whitespace string\n\
13067is a separator.");
13068
13069static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013070unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013071{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013072 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013073 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013074 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013075
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013076 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
13077 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013078 return NULL;
13079
13080 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000013081 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013082
13083 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020013084 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013085
13086 PyErr_Format(PyExc_TypeError,
13087 "must be str or None, not %.100s",
13088 Py_TYPE(substring)->tp_name);
13089 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013090}
13091
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013092PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013093 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013094\n\
13095Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000013096Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013097is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013098
13099static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013100unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013101{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013102 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000013103 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013105 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
13106 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013107 return NULL;
13108
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013109 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110}
13111
13112static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013113PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013115 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116}
13117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013118PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013119 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120\n\
13121Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013122and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013123
13124static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013125unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013126{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013127 if (PyUnicode_READY(self) == -1)
13128 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013129 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130}
13131
Larry Hastings61272b72014-01-07 12:41:53 -080013132/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013133
Larry Hastings31826802013-10-19 00:09:25 -070013134@staticmethod
13135str.maketrans as unicode_maketrans
13136
13137 x: object
13138
13139 y: unicode=NULL
13140
13141 z: unicode=NULL
13142
13143 /
13144
13145Return a translation table usable for str.translate().
13146
13147If there is only one argument, it must be a dictionary mapping Unicode
13148ordinals (integers) or characters to Unicode ordinals, strings or None.
13149Character keys will be then converted to ordinals.
13150If there are two arguments, they must be strings of equal length, and
13151in the resulting dictionary, each character in x will be mapped to the
13152character at the same position in y. If there is a third argument, it
13153must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013154[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013155
Larry Hastings31826802013-10-19 00:09:25 -070013156static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013157unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013158/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013159{
Georg Brandlceee0772007-11-27 23:48:05 +000013160 PyObject *new = NULL, *key, *value;
13161 Py_ssize_t i = 0;
13162 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013163
Georg Brandlceee0772007-11-27 23:48:05 +000013164 new = PyDict_New();
13165 if (!new)
13166 return NULL;
13167 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013168 int x_kind, y_kind, z_kind;
13169 void *x_data, *y_data, *z_data;
13170
Georg Brandlceee0772007-11-27 23:48:05 +000013171 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013172 if (!PyUnicode_Check(x)) {
13173 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13174 "be a string if there is a second argument");
13175 goto err;
13176 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013177 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013178 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13179 "arguments must have equal length");
13180 goto err;
13181 }
13182 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013183 x_kind = PyUnicode_KIND(x);
13184 y_kind = PyUnicode_KIND(y);
13185 x_data = PyUnicode_DATA(x);
13186 y_data = PyUnicode_DATA(y);
13187 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13188 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013189 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013190 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013191 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013192 if (!value) {
13193 Py_DECREF(key);
13194 goto err;
13195 }
Georg Brandlceee0772007-11-27 23:48:05 +000013196 res = PyDict_SetItem(new, key, value);
13197 Py_DECREF(key);
13198 Py_DECREF(value);
13199 if (res < 0)
13200 goto err;
13201 }
13202 /* create entries for deleting chars in z */
13203 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013204 z_kind = PyUnicode_KIND(z);
13205 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013206 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013207 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013208 if (!key)
13209 goto err;
13210 res = PyDict_SetItem(new, key, Py_None);
13211 Py_DECREF(key);
13212 if (res < 0)
13213 goto err;
13214 }
13215 }
13216 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013217 int kind;
13218 void *data;
13219
Georg Brandlceee0772007-11-27 23:48:05 +000013220 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013221 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013222 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13223 "to maketrans it must be a dict");
13224 goto err;
13225 }
13226 /* copy entries into the new dict, converting string keys to int keys */
13227 while (PyDict_Next(x, &i, &key, &value)) {
13228 if (PyUnicode_Check(key)) {
13229 /* convert string keys to integer keys */
13230 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013231 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013232 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13233 "table must be of length 1");
13234 goto err;
13235 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013236 kind = PyUnicode_KIND(key);
13237 data = PyUnicode_DATA(key);
13238 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013239 if (!newkey)
13240 goto err;
13241 res = PyDict_SetItem(new, newkey, value);
13242 Py_DECREF(newkey);
13243 if (res < 0)
13244 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013245 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013246 /* just keep integer keys */
13247 if (PyDict_SetItem(new, key, value) < 0)
13248 goto err;
13249 } else {
13250 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13251 "be strings or integers");
13252 goto err;
13253 }
13254 }
13255 }
13256 return new;
13257 err:
13258 Py_DECREF(new);
13259 return NULL;
13260}
13261
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013262PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013263 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013264\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013265Return a copy of the string S in which each character has been mapped\n\
13266through the given translation table. The table must implement\n\
13267lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13268mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13269this operation raises LookupError, the character is left untouched.\n\
13270Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013271
13272static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013273unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013274{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013275 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013276}
13277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013278PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013279 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013280\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013281Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013282
13283static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013284unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013285{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013286 if (PyUnicode_READY(self) == -1)
13287 return NULL;
13288 if (PyUnicode_IS_ASCII(self))
13289 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013290 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013291}
13292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013293PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013295\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013296Pad a numeric string S with zeros on the left, to fill a field\n\
13297of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013298
13299static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013300unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013301{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013302 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013303 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013304 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013305 int kind;
13306 void *data;
13307 Py_UCS4 chr;
13308
Martin v. Löwis18e16552006-02-15 17:27:45 +000013309 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013310 return NULL;
13311
Benjamin Petersonbac79492012-01-14 13:34:47 -050013312 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013313 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013314
Victor Stinnerc4b49542011-12-11 22:44:26 +010013315 if (PyUnicode_GET_LENGTH(self) >= width)
13316 return unicode_result_unchanged(self);
13317
13318 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013319
13320 u = pad(self, fill, 0, '0');
13321
Walter Dörwald068325e2002-04-15 13:36:47 +000013322 if (u == NULL)
13323 return NULL;
13324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013325 kind = PyUnicode_KIND(u);
13326 data = PyUnicode_DATA(u);
13327 chr = PyUnicode_READ(kind, data, fill);
13328
13329 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013330 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013331 PyUnicode_WRITE(kind, data, 0, chr);
13332 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013333 }
13334
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013335 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013336 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013337}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013338
13339#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013340static PyObject *
13341unicode__decimal2ascii(PyObject *self)
13342{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013343 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013344}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345#endif
13346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013347PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013348 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013349\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013350Return True if S starts with the specified prefix, False otherwise.\n\
13351With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013352With optional end, stop comparing S at that position.\n\
13353prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013354
13355static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013356unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013357 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013358{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013359 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013360 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013361 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013362 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013363 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013364
Jesus Ceaac451502011-04-20 17:09:23 +020013365 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013366 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013367 if (PyTuple_Check(subobj)) {
13368 Py_ssize_t i;
13369 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013370 substring = PyTuple_GET_ITEM(subobj, i);
13371 if (!PyUnicode_Check(substring)) {
13372 PyErr_Format(PyExc_TypeError,
13373 "tuple for startswith must only contain str, "
13374 "not %.100s",
13375 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013376 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013377 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013378 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013379 if (result == -1)
13380 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013381 if (result) {
13382 Py_RETURN_TRUE;
13383 }
13384 }
13385 /* nothing matched */
13386 Py_RETURN_FALSE;
13387 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013388 if (!PyUnicode_Check(subobj)) {
13389 PyErr_Format(PyExc_TypeError,
13390 "startswith first arg must be str or "
13391 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013392 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013393 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013394 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013395 if (result == -1)
13396 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013397 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013398}
13399
13400
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013401PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013402 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013403\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013404Return True if S ends with the specified suffix, False otherwise.\n\
13405With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013406With optional end, stop comparing S at that position.\n\
13407suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013408
13409static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013410unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013411 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013412{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013413 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013414 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013415 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013416 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013417 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013418
Jesus Ceaac451502011-04-20 17:09:23 +020013419 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013420 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013421 if (PyTuple_Check(subobj)) {
13422 Py_ssize_t i;
13423 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013424 substring = PyTuple_GET_ITEM(subobj, i);
13425 if (!PyUnicode_Check(substring)) {
13426 PyErr_Format(PyExc_TypeError,
13427 "tuple for endswith must only contain str, "
13428 "not %.100s",
13429 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013430 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013431 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013432 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013433 if (result == -1)
13434 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013435 if (result) {
13436 Py_RETURN_TRUE;
13437 }
13438 }
13439 Py_RETURN_FALSE;
13440 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013441 if (!PyUnicode_Check(subobj)) {
13442 PyErr_Format(PyExc_TypeError,
13443 "endswith first arg must be str or "
13444 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013445 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013446 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013447 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013448 if (result == -1)
13449 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013450 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013451}
13452
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013453static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013454_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013455{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013456 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13457 writer->data = PyUnicode_DATA(writer->buffer);
13458
13459 if (!writer->readonly) {
13460 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013461 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013462 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013463 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013464 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13465 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13466 writer->kind = PyUnicode_WCHAR_KIND;
13467 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13468
Victor Stinner8f674cc2013-04-17 23:02:17 +020013469 /* Copy-on-write mode: set buffer size to 0 so
13470 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13471 * next write. */
13472 writer->size = 0;
13473 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013474}
13475
Victor Stinnerd3f08822012-05-29 12:57:52 +020013476void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013477_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013478{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013479 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013480
13481 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013482 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013483
13484 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13485 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13486 writer->kind = PyUnicode_WCHAR_KIND;
13487 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013488}
13489
Victor Stinnerd3f08822012-05-29 12:57:52 +020013490int
13491_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13492 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013493{
13494 Py_ssize_t newlen;
13495 PyObject *newbuffer;
13496
Victor Stinner2740e462016-09-06 16:58:36 -070013497 assert(maxchar <= MAX_UNICODE);
13498
Victor Stinnerca9381e2015-09-22 00:58:32 +020013499 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013500 assert((maxchar > writer->maxchar && length >= 0)
13501 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013502
Victor Stinner202fdca2012-05-07 12:47:02 +020013503 if (length > PY_SSIZE_T_MAX - writer->pos) {
13504 PyErr_NoMemory();
13505 return -1;
13506 }
13507 newlen = writer->pos + length;
13508
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013509 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013510
Victor Stinnerd3f08822012-05-29 12:57:52 +020013511 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013512 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013513 if (writer->overallocate
13514 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13515 /* overallocate to limit the number of realloc() */
13516 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013517 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013518 if (newlen < writer->min_length)
13519 newlen = writer->min_length;
13520
Victor Stinnerd3f08822012-05-29 12:57:52 +020013521 writer->buffer = PyUnicode_New(newlen, maxchar);
13522 if (writer->buffer == NULL)
13523 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013524 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013525 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013526 if (writer->overallocate
13527 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13528 /* overallocate to limit the number of realloc() */
13529 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013530 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013531 if (newlen < writer->min_length)
13532 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013533
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013534 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013535 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013536 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013537 newbuffer = PyUnicode_New(newlen, maxchar);
13538 if (newbuffer == NULL)
13539 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013540 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13541 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013542 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013543 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013544 }
13545 else {
13546 newbuffer = resize_compact(writer->buffer, newlen);
13547 if (newbuffer == NULL)
13548 return -1;
13549 }
13550 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013551 }
13552 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013553 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013554 newbuffer = PyUnicode_New(writer->size, maxchar);
13555 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013556 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013557 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13558 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013559 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013560 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013561 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013562 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013563
13564#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013565}
13566
Victor Stinnerca9381e2015-09-22 00:58:32 +020013567int
13568_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13569 enum PyUnicode_Kind kind)
13570{
13571 Py_UCS4 maxchar;
13572
13573 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13574 assert(writer->kind < kind);
13575
13576 switch (kind)
13577 {
13578 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13579 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13580 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13581 default:
13582 assert(0 && "invalid kind");
13583 return -1;
13584 }
13585
13586 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13587}
13588
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013589static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013590_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013591{
Victor Stinner2740e462016-09-06 16:58:36 -070013592 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013593 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13594 return -1;
13595 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13596 writer->pos++;
13597 return 0;
13598}
13599
13600int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013601_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13602{
13603 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13604}
13605
13606int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013607_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13608{
13609 Py_UCS4 maxchar;
13610 Py_ssize_t len;
13611
13612 if (PyUnicode_READY(str) == -1)
13613 return -1;
13614 len = PyUnicode_GET_LENGTH(str);
13615 if (len == 0)
13616 return 0;
13617 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13618 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013619 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013620 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013621 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013622 Py_INCREF(str);
13623 writer->buffer = str;
13624 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013625 writer->pos += len;
13626 return 0;
13627 }
13628 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13629 return -1;
13630 }
13631 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13632 str, 0, len);
13633 writer->pos += len;
13634 return 0;
13635}
13636
Victor Stinnere215d962012-10-06 23:03:36 +020013637int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013638_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13639 Py_ssize_t start, Py_ssize_t end)
13640{
13641 Py_UCS4 maxchar;
13642 Py_ssize_t len;
13643
13644 if (PyUnicode_READY(str) == -1)
13645 return -1;
13646
13647 assert(0 <= start);
13648 assert(end <= PyUnicode_GET_LENGTH(str));
13649 assert(start <= end);
13650
13651 if (end == 0)
13652 return 0;
13653
13654 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13655 return _PyUnicodeWriter_WriteStr(writer, str);
13656
13657 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13658 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13659 else
13660 maxchar = writer->maxchar;
13661 len = end - start;
13662
13663 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13664 return -1;
13665
13666 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13667 str, start, len);
13668 writer->pos += len;
13669 return 0;
13670}
13671
13672int
Victor Stinner4a587072013-11-19 12:54:53 +010013673_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13674 const char *ascii, Py_ssize_t len)
13675{
13676 if (len == -1)
13677 len = strlen(ascii);
13678
13679 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13680
13681 if (writer->buffer == NULL && !writer->overallocate) {
13682 PyObject *str;
13683
13684 str = _PyUnicode_FromASCII(ascii, len);
13685 if (str == NULL)
13686 return -1;
13687
13688 writer->readonly = 1;
13689 writer->buffer = str;
13690 _PyUnicodeWriter_Update(writer);
13691 writer->pos += len;
13692 return 0;
13693 }
13694
13695 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13696 return -1;
13697
13698 switch (writer->kind)
13699 {
13700 case PyUnicode_1BYTE_KIND:
13701 {
13702 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13703 Py_UCS1 *data = writer->data;
13704
Christian Heimesf051e432016-09-13 20:22:02 +020013705 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013706 break;
13707 }
13708 case PyUnicode_2BYTE_KIND:
13709 {
13710 _PyUnicode_CONVERT_BYTES(
13711 Py_UCS1, Py_UCS2,
13712 ascii, ascii + len,
13713 (Py_UCS2 *)writer->data + writer->pos);
13714 break;
13715 }
13716 case PyUnicode_4BYTE_KIND:
13717 {
13718 _PyUnicode_CONVERT_BYTES(
13719 Py_UCS1, Py_UCS4,
13720 ascii, ascii + len,
13721 (Py_UCS4 *)writer->data + writer->pos);
13722 break;
13723 }
13724 default:
13725 assert(0);
13726 }
13727
13728 writer->pos += len;
13729 return 0;
13730}
13731
13732int
13733_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13734 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013735{
13736 Py_UCS4 maxchar;
13737
13738 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13739 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13740 return -1;
13741 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13742 writer->pos += len;
13743 return 0;
13744}
13745
Victor Stinnerd3f08822012-05-29 12:57:52 +020013746PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013747_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013748{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013749 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013750
Victor Stinnerd3f08822012-05-29 12:57:52 +020013751 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013752 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013753 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013754 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013755
13756 str = writer->buffer;
13757 writer->buffer = NULL;
13758
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013759 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013760 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13761 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013762 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013763
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013764 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13765 PyObject *str2;
13766 str2 = resize_compact(str, writer->pos);
13767 if (str2 == NULL) {
13768 Py_DECREF(str);
13769 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013770 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013771 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013772 }
13773
Victor Stinner15a0bd32013-07-08 22:29:55 +020013774 assert(_PyUnicode_CheckConsistency(str, 1));
13775 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013776}
13777
Victor Stinnerd3f08822012-05-29 12:57:52 +020013778void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013779_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013780{
13781 Py_CLEAR(writer->buffer);
13782}
13783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013784#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013785
13786PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013787 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013788\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013789Return a formatted version of S, using substitutions from args and kwargs.\n\
13790The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013791
Eric Smith27bbca62010-11-04 17:06:58 +000013792PyDoc_STRVAR(format_map__doc__,
13793 "S.format_map(mapping) -> str\n\
13794\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013795Return a formatted version of S, using substitutions from mapping.\n\
13796The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013797
Eric Smith4a7d76d2008-05-30 18:10:19 +000013798static PyObject *
13799unicode__format__(PyObject* self, PyObject* args)
13800{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013801 PyObject *format_spec;
13802 _PyUnicodeWriter writer;
13803 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013804
13805 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13806 return NULL;
13807
Victor Stinnerd3f08822012-05-29 12:57:52 +020013808 if (PyUnicode_READY(self) == -1)
13809 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013810 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013811 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13812 self, format_spec, 0,
13813 PyUnicode_GET_LENGTH(format_spec));
13814 if (ret == -1) {
13815 _PyUnicodeWriter_Dealloc(&writer);
13816 return NULL;
13817 }
13818 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013819}
13820
Eric Smith8c663262007-08-25 02:26:07 +000013821PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013822 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013823\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013824Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013825
13826static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013827unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013828{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013829 Py_ssize_t size;
13830
13831 /* If it's a compact object, account for base structure +
13832 character data. */
13833 if (PyUnicode_IS_COMPACT_ASCII(v))
13834 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13835 else if (PyUnicode_IS_COMPACT(v))
13836 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013837 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013838 else {
13839 /* If it is a two-block object, account for base object, and
13840 for character block if present. */
13841 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013842 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013843 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013844 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013845 }
13846 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013847 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013848 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013849 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013850 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013851 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013852
13853 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013854}
13855
13856PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013857 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013858
13859static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013860unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013861{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013862 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013863 if (!copy)
13864 return NULL;
13865 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013866}
13867
Guido van Rossumd57fd912000-03-10 22:53:23 +000013868static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013869 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013870 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013871 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13872 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013873 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13874 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013875 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013876 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13877 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13878 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013879 {"expandtabs", (PyCFunction) unicode_expandtabs,
13880 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013881 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013882 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013883 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13884 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13885 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013886 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013887 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13888 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13889 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013890 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013891 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013892 {"splitlines", (PyCFunction) unicode_splitlines,
13893 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013894 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013895 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13896 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13897 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13898 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13899 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13900 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13901 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13902 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13903 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13904 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13905 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13906 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13907 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13908 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013909 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013910 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013911 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013912 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013913 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013914 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013915 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013916 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013917#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013918 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013919 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013920#endif
13921
Benjamin Peterson14339b62009-01-31 16:36:08 +000013922 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013923 {NULL, NULL}
13924};
13925
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013926static PyObject *
13927unicode_mod(PyObject *v, PyObject *w)
13928{
Brian Curtindfc80e32011-08-10 20:28:54 -050013929 if (!PyUnicode_Check(v))
13930 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013931 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013932}
13933
13934static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013935 0, /*nb_add*/
13936 0, /*nb_subtract*/
13937 0, /*nb_multiply*/
13938 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013939};
13940
Guido van Rossumd57fd912000-03-10 22:53:23 +000013941static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013942 (lenfunc) unicode_length, /* sq_length */
13943 PyUnicode_Concat, /* sq_concat */
13944 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13945 (ssizeargfunc) unicode_getitem, /* sq_item */
13946 0, /* sq_slice */
13947 0, /* sq_ass_item */
13948 0, /* sq_ass_slice */
13949 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013950};
13951
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013952static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013953unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013954{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013955 if (PyUnicode_READY(self) == -1)
13956 return NULL;
13957
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013958 if (PyIndex_Check(item)) {
13959 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013960 if (i == -1 && PyErr_Occurred())
13961 return NULL;
13962 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013963 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013964 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013965 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013966 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013967 PyObject *result;
13968 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013969 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013970 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013971
Serhiy Storchakac26b19d2017-04-08 11:18:14 +030013972 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013973 return NULL;
13974 }
Serhiy Storchakac26b19d2017-04-08 11:18:14 +030013975 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13976 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013977
13978 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013979 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013980 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013981 slicelength == PyUnicode_GET_LENGTH(self)) {
13982 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013983 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013984 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013985 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013986 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013987 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013988 src_kind = PyUnicode_KIND(self);
13989 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013990 if (!PyUnicode_IS_ASCII(self)) {
13991 kind_limit = kind_maxchar_limit(src_kind);
13992 max_char = 0;
13993 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13994 ch = PyUnicode_READ(src_kind, src_data, cur);
13995 if (ch > max_char) {
13996 max_char = ch;
13997 if (max_char >= kind_limit)
13998 break;
13999 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014000 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014001 }
Victor Stinner55c99112011-10-13 01:17:06 +020014002 else
14003 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014004 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014005 if (result == NULL)
14006 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014007 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014008 dest_data = PyUnicode_DATA(result);
14009
14010 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014011 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14012 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014013 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014014 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014015 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014016 } else {
14017 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14018 return NULL;
14019 }
14020}
14021
14022static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014023 (lenfunc)unicode_length, /* mp_length */
14024 (binaryfunc)unicode_subscript, /* mp_subscript */
14025 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014026};
14027
Guido van Rossumd57fd912000-03-10 22:53:23 +000014028
Guido van Rossumd57fd912000-03-10 22:53:23 +000014029/* Helpers for PyUnicode_Format() */
14030
Victor Stinnera47082312012-10-04 02:19:54 +020014031struct unicode_formatter_t {
14032 PyObject *args;
14033 int args_owned;
14034 Py_ssize_t arglen, argidx;
14035 PyObject *dict;
14036
14037 enum PyUnicode_Kind fmtkind;
14038 Py_ssize_t fmtcnt, fmtpos;
14039 void *fmtdata;
14040 PyObject *fmtstr;
14041
14042 _PyUnicodeWriter writer;
14043};
14044
14045struct unicode_format_arg_t {
14046 Py_UCS4 ch;
14047 int flags;
14048 Py_ssize_t width;
14049 int prec;
14050 int sign;
14051};
14052
Guido van Rossumd57fd912000-03-10 22:53:23 +000014053static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014054unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014055{
Victor Stinnera47082312012-10-04 02:19:54 +020014056 Py_ssize_t argidx = ctx->argidx;
14057
14058 if (argidx < ctx->arglen) {
14059 ctx->argidx++;
14060 if (ctx->arglen < 0)
14061 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014062 else
Victor Stinnera47082312012-10-04 02:19:54 +020014063 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014064 }
14065 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014066 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014067 return NULL;
14068}
14069
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014070/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014071
Victor Stinnera47082312012-10-04 02:19:54 +020014072/* Format a float into the writer if the writer is not NULL, or into *p_output
14073 otherwise.
14074
14075 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014076static int
Victor Stinnera47082312012-10-04 02:19:54 +020014077formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14078 PyObject **p_output,
14079 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014080{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014081 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014082 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014083 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014084 int prec;
14085 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014086
Guido van Rossumd57fd912000-03-10 22:53:23 +000014087 x = PyFloat_AsDouble(v);
14088 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014089 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014090
Victor Stinnera47082312012-10-04 02:19:54 +020014091 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014092 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014093 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014094
Victor Stinnera47082312012-10-04 02:19:54 +020014095 if (arg->flags & F_ALT)
14096 dtoa_flags = Py_DTSF_ALT;
14097 else
14098 dtoa_flags = 0;
14099 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014100 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014101 return -1;
14102 len = strlen(p);
14103 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014104 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014105 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014106 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014107 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014108 }
14109 else
14110 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014111 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014112 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014113}
14114
Victor Stinnerd0880d52012-04-27 23:40:13 +020014115/* formatlong() emulates the format codes d, u, o, x and X, and
14116 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14117 * Python's regular ints.
14118 * Return value: a new PyUnicodeObject*, or NULL if error.
14119 * The output string is of the form
14120 * "-"? ("0x" | "0X")? digit+
14121 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14122 * set in flags. The case of hex digits will be correct,
14123 * There will be at least prec digits, zero-filled on the left if
14124 * necessary to get that many.
14125 * val object to be converted
14126 * flags bitmask of format flags; only F_ALT is looked at
14127 * prec minimum number of digits; 0-fill on left if needed
14128 * type a character in [duoxX]; u acts the same as d
14129 *
14130 * CAUTION: o, x and X conversions on regular ints can never
14131 * produce a '-' sign, but can for Python's unbounded ints.
14132 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014133PyObject *
14134_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014135{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014136 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014137 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014138 Py_ssize_t i;
14139 int sign; /* 1 if '-', else 0 */
14140 int len; /* number of characters */
14141 Py_ssize_t llen;
14142 int numdigits; /* len == numnondigits + numdigits */
14143 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014144
Victor Stinnerd0880d52012-04-27 23:40:13 +020014145 /* Avoid exceeding SSIZE_T_MAX */
14146 if (prec > INT_MAX-3) {
14147 PyErr_SetString(PyExc_OverflowError,
14148 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014149 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014150 }
14151
14152 assert(PyLong_Check(val));
14153
14154 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014155 default:
14156 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014157 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014158 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014159 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014160 /* int and int subclasses should print numerically when a numeric */
14161 /* format code is used (see issue18780) */
14162 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014163 break;
14164 case 'o':
14165 numnondigits = 2;
14166 result = PyNumber_ToBase(val, 8);
14167 break;
14168 case 'x':
14169 case 'X':
14170 numnondigits = 2;
14171 result = PyNumber_ToBase(val, 16);
14172 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014173 }
14174 if (!result)
14175 return NULL;
14176
14177 assert(unicode_modifiable(result));
14178 assert(PyUnicode_IS_READY(result));
14179 assert(PyUnicode_IS_ASCII(result));
14180
14181 /* To modify the string in-place, there can only be one reference. */
14182 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014183 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014184 PyErr_BadInternalCall();
14185 return NULL;
14186 }
14187 buf = PyUnicode_DATA(result);
14188 llen = PyUnicode_GET_LENGTH(result);
14189 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014190 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014191 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014192 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014193 return NULL;
14194 }
14195 len = (int)llen;
14196 sign = buf[0] == '-';
14197 numnondigits += sign;
14198 numdigits = len - numnondigits;
14199 assert(numdigits > 0);
14200
14201 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014202 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014203 (type == 'o' || type == 'x' || type == 'X'))) {
14204 assert(buf[sign] == '0');
14205 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14206 buf[sign+1] == 'o');
14207 numnondigits -= 2;
14208 buf += 2;
14209 len -= 2;
14210 if (sign)
14211 buf[0] = '-';
14212 assert(len == numnondigits + numdigits);
14213 assert(numdigits > 0);
14214 }
14215
14216 /* Fill with leading zeroes to meet minimum width. */
14217 if (prec > numdigits) {
14218 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14219 numnondigits + prec);
14220 char *b1;
14221 if (!r1) {
14222 Py_DECREF(result);
14223 return NULL;
14224 }
14225 b1 = PyBytes_AS_STRING(r1);
14226 for (i = 0; i < numnondigits; ++i)
14227 *b1++ = *buf++;
14228 for (i = 0; i < prec - numdigits; i++)
14229 *b1++ = '0';
14230 for (i = 0; i < numdigits; i++)
14231 *b1++ = *buf++;
14232 *b1 = '\0';
14233 Py_DECREF(result);
14234 result = r1;
14235 buf = PyBytes_AS_STRING(result);
14236 len = numnondigits + prec;
14237 }
14238
14239 /* Fix up case for hex conversions. */
14240 if (type == 'X') {
14241 /* Need to convert all lower case letters to upper case.
14242 and need to convert 0x to 0X (and -0x to -0X). */
14243 for (i = 0; i < len; i++)
14244 if (buf[i] >= 'a' && buf[i] <= 'x')
14245 buf[i] -= 'a'-'A';
14246 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014247 if (!PyUnicode_Check(result)
14248 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014249 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014250 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014251 Py_DECREF(result);
14252 result = unicode;
14253 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014254 else if (len != PyUnicode_GET_LENGTH(result)) {
14255 if (PyUnicode_Resize(&result, len) < 0)
14256 Py_CLEAR(result);
14257 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014258 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014259}
14260
Ethan Furmandf3ed242014-01-05 06:50:30 -080014261/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014262 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014263 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014264 * -1 and raise an exception on error */
14265static int
Victor Stinnera47082312012-10-04 02:19:54 +020014266mainformatlong(PyObject *v,
14267 struct unicode_format_arg_t *arg,
14268 PyObject **p_output,
14269 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014270{
14271 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014272 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014273
14274 if (!PyNumber_Check(v))
14275 goto wrongtype;
14276
Ethan Furman9ab74802014-03-21 06:38:46 -070014277 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014278 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014279 if (type == 'o' || type == 'x' || type == 'X') {
14280 iobj = PyNumber_Index(v);
14281 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014282 if (PyErr_ExceptionMatches(PyExc_TypeError))
14283 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014284 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014285 }
14286 }
14287 else {
14288 iobj = PyNumber_Long(v);
14289 if (iobj == NULL ) {
14290 if (PyErr_ExceptionMatches(PyExc_TypeError))
14291 goto wrongtype;
14292 return -1;
14293 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014294 }
14295 assert(PyLong_Check(iobj));
14296 }
14297 else {
14298 iobj = v;
14299 Py_INCREF(iobj);
14300 }
14301
14302 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014303 && arg->width == -1 && arg->prec == -1
14304 && !(arg->flags & (F_SIGN | F_BLANK))
14305 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014306 {
14307 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014308 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014309 int base;
14310
Victor Stinnera47082312012-10-04 02:19:54 +020014311 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014312 {
14313 default:
14314 assert(0 && "'type' not in [diuoxX]");
14315 case 'd':
14316 case 'i':
14317 case 'u':
14318 base = 10;
14319 break;
14320 case 'o':
14321 base = 8;
14322 break;
14323 case 'x':
14324 case 'X':
14325 base = 16;
14326 break;
14327 }
14328
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014329 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14330 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014331 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014332 }
14333 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014334 return 1;
14335 }
14336
Ethan Furmanb95b5612015-01-23 20:05:18 -080014337 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014338 Py_DECREF(iobj);
14339 if (res == NULL)
14340 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014341 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014342 return 0;
14343
14344wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014345 switch(type)
14346 {
14347 case 'o':
14348 case 'x':
14349 case 'X':
14350 PyErr_Format(PyExc_TypeError,
14351 "%%%c format: an integer is required, "
14352 "not %.200s",
14353 type, Py_TYPE(v)->tp_name);
14354 break;
14355 default:
14356 PyErr_Format(PyExc_TypeError,
14357 "%%%c format: a number is required, "
14358 "not %.200s",
14359 type, Py_TYPE(v)->tp_name);
14360 break;
14361 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014362 return -1;
14363}
14364
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014365static Py_UCS4
14366formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014367{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014368 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014369 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014370 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014371 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014372 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014373 goto onError;
14374 }
14375 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014376 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014377 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014378 /* make sure number is a type of integer */
14379 if (!PyLong_Check(v)) {
14380 iobj = PyNumber_Index(v);
14381 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014382 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014383 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014384 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014385 Py_DECREF(iobj);
14386 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014387 else {
14388 x = PyLong_AsLong(v);
14389 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014390 if (x == -1 && PyErr_Occurred())
14391 goto onError;
14392
Victor Stinner8faf8212011-12-08 22:14:11 +010014393 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014394 PyErr_SetString(PyExc_OverflowError,
14395 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014396 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014397 }
14398
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014399 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014400 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014401
Benjamin Peterson29060642009-01-31 22:14:21 +000014402 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014403 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014404 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014405 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014406}
14407
Victor Stinnera47082312012-10-04 02:19:54 +020014408/* Parse options of an argument: flags, width, precision.
14409 Handle also "%(name)" syntax.
14410
14411 Return 0 if the argument has been formatted into arg->str.
14412 Return 1 if the argument has been written into ctx->writer,
14413 Raise an exception and return -1 on error. */
14414static int
14415unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14416 struct unicode_format_arg_t *arg)
14417{
14418#define FORMAT_READ(ctx) \
14419 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14420
14421 PyObject *v;
14422
Victor Stinnera47082312012-10-04 02:19:54 +020014423 if (arg->ch == '(') {
14424 /* Get argument value from a dictionary. Example: "%(name)s". */
14425 Py_ssize_t keystart;
14426 Py_ssize_t keylen;
14427 PyObject *key;
14428 int pcount = 1;
14429
14430 if (ctx->dict == NULL) {
14431 PyErr_SetString(PyExc_TypeError,
14432 "format requires a mapping");
14433 return -1;
14434 }
14435 ++ctx->fmtpos;
14436 --ctx->fmtcnt;
14437 keystart = ctx->fmtpos;
14438 /* Skip over balanced parentheses */
14439 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14440 arg->ch = FORMAT_READ(ctx);
14441 if (arg->ch == ')')
14442 --pcount;
14443 else if (arg->ch == '(')
14444 ++pcount;
14445 ctx->fmtpos++;
14446 }
14447 keylen = ctx->fmtpos - keystart - 1;
14448 if (ctx->fmtcnt < 0 || pcount > 0) {
14449 PyErr_SetString(PyExc_ValueError,
14450 "incomplete format key");
14451 return -1;
14452 }
14453 key = PyUnicode_Substring(ctx->fmtstr,
14454 keystart, keystart + keylen);
14455 if (key == NULL)
14456 return -1;
14457 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014458 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014459 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014460 }
14461 ctx->args = PyObject_GetItem(ctx->dict, key);
14462 Py_DECREF(key);
14463 if (ctx->args == NULL)
14464 return -1;
14465 ctx->args_owned = 1;
14466 ctx->arglen = -1;
14467 ctx->argidx = -2;
14468 }
14469
14470 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014471 while (--ctx->fmtcnt >= 0) {
14472 arg->ch = FORMAT_READ(ctx);
14473 ctx->fmtpos++;
14474 switch (arg->ch) {
14475 case '-': arg->flags |= F_LJUST; continue;
14476 case '+': arg->flags |= F_SIGN; continue;
14477 case ' ': arg->flags |= F_BLANK; continue;
14478 case '#': arg->flags |= F_ALT; continue;
14479 case '0': arg->flags |= F_ZERO; continue;
14480 }
14481 break;
14482 }
14483
14484 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014485 if (arg->ch == '*') {
14486 v = unicode_format_getnextarg(ctx);
14487 if (v == NULL)
14488 return -1;
14489 if (!PyLong_Check(v)) {
14490 PyErr_SetString(PyExc_TypeError,
14491 "* wants int");
14492 return -1;
14493 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014494 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014495 if (arg->width == -1 && PyErr_Occurred())
14496 return -1;
14497 if (arg->width < 0) {
14498 arg->flags |= F_LJUST;
14499 arg->width = -arg->width;
14500 }
14501 if (--ctx->fmtcnt >= 0) {
14502 arg->ch = FORMAT_READ(ctx);
14503 ctx->fmtpos++;
14504 }
14505 }
14506 else if (arg->ch >= '0' && arg->ch <= '9') {
14507 arg->width = arg->ch - '0';
14508 while (--ctx->fmtcnt >= 0) {
14509 arg->ch = FORMAT_READ(ctx);
14510 ctx->fmtpos++;
14511 if (arg->ch < '0' || arg->ch > '9')
14512 break;
14513 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14514 mixing signed and unsigned comparison. Since arg->ch is between
14515 '0' and '9', casting to int is safe. */
14516 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14517 PyErr_SetString(PyExc_ValueError,
14518 "width too big");
14519 return -1;
14520 }
14521 arg->width = arg->width*10 + (arg->ch - '0');
14522 }
14523 }
14524
14525 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014526 if (arg->ch == '.') {
14527 arg->prec = 0;
14528 if (--ctx->fmtcnt >= 0) {
14529 arg->ch = FORMAT_READ(ctx);
14530 ctx->fmtpos++;
14531 }
14532 if (arg->ch == '*') {
14533 v = unicode_format_getnextarg(ctx);
14534 if (v == NULL)
14535 return -1;
14536 if (!PyLong_Check(v)) {
14537 PyErr_SetString(PyExc_TypeError,
14538 "* wants int");
14539 return -1;
14540 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014541 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014542 if (arg->prec == -1 && PyErr_Occurred())
14543 return -1;
14544 if (arg->prec < 0)
14545 arg->prec = 0;
14546 if (--ctx->fmtcnt >= 0) {
14547 arg->ch = FORMAT_READ(ctx);
14548 ctx->fmtpos++;
14549 }
14550 }
14551 else if (arg->ch >= '0' && arg->ch <= '9') {
14552 arg->prec = arg->ch - '0';
14553 while (--ctx->fmtcnt >= 0) {
14554 arg->ch = FORMAT_READ(ctx);
14555 ctx->fmtpos++;
14556 if (arg->ch < '0' || arg->ch > '9')
14557 break;
14558 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14559 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014560 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014561 return -1;
14562 }
14563 arg->prec = arg->prec*10 + (arg->ch - '0');
14564 }
14565 }
14566 }
14567
14568 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14569 if (ctx->fmtcnt >= 0) {
14570 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14571 if (--ctx->fmtcnt >= 0) {
14572 arg->ch = FORMAT_READ(ctx);
14573 ctx->fmtpos++;
14574 }
14575 }
14576 }
14577 if (ctx->fmtcnt < 0) {
14578 PyErr_SetString(PyExc_ValueError,
14579 "incomplete format");
14580 return -1;
14581 }
14582 return 0;
14583
14584#undef FORMAT_READ
14585}
14586
14587/* Format one argument. Supported conversion specifiers:
14588
14589 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014590 - "i", "d", "u": int or float
14591 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014592 - "e", "E", "f", "F", "g", "G": float
14593 - "c": int or str (1 character)
14594
Victor Stinner8dbd4212012-12-04 09:30:24 +010014595 When possible, the output is written directly into the Unicode writer
14596 (ctx->writer). A string is created when padding is required.
14597
Victor Stinnera47082312012-10-04 02:19:54 +020014598 Return 0 if the argument has been formatted into *p_str,
14599 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014600 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014601static int
14602unicode_format_arg_format(struct unicode_formatter_t *ctx,
14603 struct unicode_format_arg_t *arg,
14604 PyObject **p_str)
14605{
14606 PyObject *v;
14607 _PyUnicodeWriter *writer = &ctx->writer;
14608
14609 if (ctx->fmtcnt == 0)
14610 ctx->writer.overallocate = 0;
14611
14612 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014613 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014614 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014615 return 1;
14616 }
14617
14618 v = unicode_format_getnextarg(ctx);
14619 if (v == NULL)
14620 return -1;
14621
Victor Stinnera47082312012-10-04 02:19:54 +020014622
14623 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014624 case 's':
14625 case 'r':
14626 case 'a':
14627 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14628 /* Fast path */
14629 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14630 return -1;
14631 return 1;
14632 }
14633
14634 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14635 *p_str = v;
14636 Py_INCREF(*p_str);
14637 }
14638 else {
14639 if (arg->ch == 's')
14640 *p_str = PyObject_Str(v);
14641 else if (arg->ch == 'r')
14642 *p_str = PyObject_Repr(v);
14643 else
14644 *p_str = PyObject_ASCII(v);
14645 }
14646 break;
14647
14648 case 'i':
14649 case 'd':
14650 case 'u':
14651 case 'o':
14652 case 'x':
14653 case 'X':
14654 {
14655 int ret = mainformatlong(v, arg, p_str, writer);
14656 if (ret != 0)
14657 return ret;
14658 arg->sign = 1;
14659 break;
14660 }
14661
14662 case 'e':
14663 case 'E':
14664 case 'f':
14665 case 'F':
14666 case 'g':
14667 case 'G':
14668 if (arg->width == -1 && arg->prec == -1
14669 && !(arg->flags & (F_SIGN | F_BLANK)))
14670 {
14671 /* Fast path */
14672 if (formatfloat(v, arg, NULL, writer) == -1)
14673 return -1;
14674 return 1;
14675 }
14676
14677 arg->sign = 1;
14678 if (formatfloat(v, arg, p_str, NULL) == -1)
14679 return -1;
14680 break;
14681
14682 case 'c':
14683 {
14684 Py_UCS4 ch = formatchar(v);
14685 if (ch == (Py_UCS4) -1)
14686 return -1;
14687 if (arg->width == -1 && arg->prec == -1) {
14688 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014689 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014690 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014691 return 1;
14692 }
14693 *p_str = PyUnicode_FromOrdinal(ch);
14694 break;
14695 }
14696
14697 default:
14698 PyErr_Format(PyExc_ValueError,
14699 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014700 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014701 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14702 (int)arg->ch,
14703 ctx->fmtpos - 1);
14704 return -1;
14705 }
14706 if (*p_str == NULL)
14707 return -1;
14708 assert (PyUnicode_Check(*p_str));
14709 return 0;
14710}
14711
14712static int
14713unicode_format_arg_output(struct unicode_formatter_t *ctx,
14714 struct unicode_format_arg_t *arg,
14715 PyObject *str)
14716{
14717 Py_ssize_t len;
14718 enum PyUnicode_Kind kind;
14719 void *pbuf;
14720 Py_ssize_t pindex;
14721 Py_UCS4 signchar;
14722 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014723 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014724 Py_ssize_t sublen;
14725 _PyUnicodeWriter *writer = &ctx->writer;
14726 Py_UCS4 fill;
14727
14728 fill = ' ';
14729 if (arg->sign && arg->flags & F_ZERO)
14730 fill = '0';
14731
14732 if (PyUnicode_READY(str) == -1)
14733 return -1;
14734
14735 len = PyUnicode_GET_LENGTH(str);
14736 if ((arg->width == -1 || arg->width <= len)
14737 && (arg->prec == -1 || arg->prec >= len)
14738 && !(arg->flags & (F_SIGN | F_BLANK)))
14739 {
14740 /* Fast path */
14741 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14742 return -1;
14743 return 0;
14744 }
14745
14746 /* Truncate the string for "s", "r" and "a" formats
14747 if the precision is set */
14748 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14749 if (arg->prec >= 0 && len > arg->prec)
14750 len = arg->prec;
14751 }
14752
14753 /* Adjust sign and width */
14754 kind = PyUnicode_KIND(str);
14755 pbuf = PyUnicode_DATA(str);
14756 pindex = 0;
14757 signchar = '\0';
14758 if (arg->sign) {
14759 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14760 if (ch == '-' || ch == '+') {
14761 signchar = ch;
14762 len--;
14763 pindex++;
14764 }
14765 else if (arg->flags & F_SIGN)
14766 signchar = '+';
14767 else if (arg->flags & F_BLANK)
14768 signchar = ' ';
14769 else
14770 arg->sign = 0;
14771 }
14772 if (arg->width < len)
14773 arg->width = len;
14774
14775 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014776 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014777 if (!(arg->flags & F_LJUST)) {
14778 if (arg->sign) {
14779 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014780 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014781 }
14782 else {
14783 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014784 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014785 }
14786 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014787 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14788 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014789 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014790 }
14791
Victor Stinnera47082312012-10-04 02:19:54 +020014792 buflen = arg->width;
14793 if (arg->sign && len == arg->width)
14794 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014795 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014796 return -1;
14797
14798 /* Write the sign if needed */
14799 if (arg->sign) {
14800 if (fill != ' ') {
14801 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14802 writer->pos += 1;
14803 }
14804 if (arg->width > len)
14805 arg->width--;
14806 }
14807
14808 /* Write the numeric prefix for "x", "X" and "o" formats
14809 if the alternate form is used.
14810 For example, write "0x" for the "%#x" format. */
14811 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14812 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14813 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14814 if (fill != ' ') {
14815 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14816 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14817 writer->pos += 2;
14818 pindex += 2;
14819 }
14820 arg->width -= 2;
14821 if (arg->width < 0)
14822 arg->width = 0;
14823 len -= 2;
14824 }
14825
14826 /* Pad left with the fill character if needed */
14827 if (arg->width > len && !(arg->flags & F_LJUST)) {
14828 sublen = arg->width - len;
14829 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14830 writer->pos += sublen;
14831 arg->width = len;
14832 }
14833
14834 /* If padding with spaces: write sign if needed and/or numeric prefix if
14835 the alternate form is used */
14836 if (fill == ' ') {
14837 if (arg->sign) {
14838 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14839 writer->pos += 1;
14840 }
14841 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14842 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14843 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14844 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14845 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14846 writer->pos += 2;
14847 pindex += 2;
14848 }
14849 }
14850
14851 /* Write characters */
14852 if (len) {
14853 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14854 str, pindex, len);
14855 writer->pos += len;
14856 }
14857
14858 /* Pad right with the fill character if needed */
14859 if (arg->width > len) {
14860 sublen = arg->width - len;
14861 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14862 writer->pos += sublen;
14863 }
14864 return 0;
14865}
14866
14867/* Helper of PyUnicode_Format(): format one arg.
14868 Return 0 on success, raise an exception and return -1 on error. */
14869static int
14870unicode_format_arg(struct unicode_formatter_t *ctx)
14871{
14872 struct unicode_format_arg_t arg;
14873 PyObject *str;
14874 int ret;
14875
Victor Stinner8dbd4212012-12-04 09:30:24 +010014876 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14877 arg.flags = 0;
14878 arg.width = -1;
14879 arg.prec = -1;
14880 arg.sign = 0;
14881 str = NULL;
14882
Victor Stinnera47082312012-10-04 02:19:54 +020014883 ret = unicode_format_arg_parse(ctx, &arg);
14884 if (ret == -1)
14885 return -1;
14886
14887 ret = unicode_format_arg_format(ctx, &arg, &str);
14888 if (ret == -1)
14889 return -1;
14890
14891 if (ret != 1) {
14892 ret = unicode_format_arg_output(ctx, &arg, str);
14893 Py_DECREF(str);
14894 if (ret == -1)
14895 return -1;
14896 }
14897
14898 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14899 PyErr_SetString(PyExc_TypeError,
14900 "not all arguments converted during string formatting");
14901 return -1;
14902 }
14903 return 0;
14904}
14905
Alexander Belopolsky40018472011-02-26 01:02:56 +000014906PyObject *
14907PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014908{
Victor Stinnera47082312012-10-04 02:19:54 +020014909 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014910
Guido van Rossumd57fd912000-03-10 22:53:23 +000014911 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014912 PyErr_BadInternalCall();
14913 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014914 }
Victor Stinnera47082312012-10-04 02:19:54 +020014915
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014916 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014917 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014918
14919 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014920 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14921 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14922 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14923 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014924
Victor Stinner8f674cc2013-04-17 23:02:17 +020014925 _PyUnicodeWriter_Init(&ctx.writer);
14926 ctx.writer.min_length = ctx.fmtcnt + 100;
14927 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014928
Guido van Rossumd57fd912000-03-10 22:53:23 +000014929 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014930 ctx.arglen = PyTuple_Size(args);
14931 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014932 }
14933 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014934 ctx.arglen = -1;
14935 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014936 }
Victor Stinnera47082312012-10-04 02:19:54 +020014937 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014938 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014939 ctx.dict = args;
14940 else
14941 ctx.dict = NULL;
14942 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014943
Victor Stinnera47082312012-10-04 02:19:54 +020014944 while (--ctx.fmtcnt >= 0) {
14945 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014946 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014947
14948 nonfmtpos = ctx.fmtpos++;
14949 while (ctx.fmtcnt >= 0 &&
14950 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14951 ctx.fmtpos++;
14952 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014953 }
Victor Stinnera47082312012-10-04 02:19:54 +020014954 if (ctx.fmtcnt < 0) {
14955 ctx.fmtpos--;
14956 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014957 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014958
Victor Stinnercfc4c132013-04-03 01:48:39 +020014959 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14960 nonfmtpos, ctx.fmtpos) < 0)
14961 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014962 }
14963 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014964 ctx.fmtpos++;
14965 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014966 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014967 }
14968 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014969
Victor Stinnera47082312012-10-04 02:19:54 +020014970 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014971 PyErr_SetString(PyExc_TypeError,
14972 "not all arguments converted during string formatting");
14973 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014974 }
14975
Victor Stinnera47082312012-10-04 02:19:54 +020014976 if (ctx.args_owned) {
14977 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014978 }
Victor Stinnera47082312012-10-04 02:19:54 +020014979 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014980
Benjamin Peterson29060642009-01-31 22:14:21 +000014981 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014982 _PyUnicodeWriter_Dealloc(&ctx.writer);
14983 if (ctx.args_owned) {
14984 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014985 }
14986 return NULL;
14987}
14988
Jeremy Hylton938ace62002-07-17 16:30:39 +000014989static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014990unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14991
Tim Peters6d6c1a32001-08-02 04:15:00 +000014992static PyObject *
14993unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14994{
Benjamin Peterson29060642009-01-31 22:14:21 +000014995 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014996 static char *kwlist[] = {"object", "encoding", "errors", 0};
14997 char *encoding = NULL;
14998 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014999
Benjamin Peterson14339b62009-01-31 16:36:08 +000015000 if (type != &PyUnicode_Type)
15001 return unicode_subtype_new(type, args, kwds);
15002 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015003 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015004 return NULL;
15005 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015006 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015007 if (encoding == NULL && errors == NULL)
15008 return PyObject_Str(x);
15009 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015010 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015011}
15012
Guido van Rossume023fe02001-08-30 03:12:59 +000015013static PyObject *
15014unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15015{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015016 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015017 Py_ssize_t length, char_size;
15018 int share_wstr, share_utf8;
15019 unsigned int kind;
15020 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015021
Benjamin Peterson14339b62009-01-31 16:36:08 +000015022 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015023
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015024 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015025 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015026 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015027 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015028 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015029 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015030 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015031 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015032
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015033 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015034 if (self == NULL) {
15035 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015036 return NULL;
15037 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015038 kind = PyUnicode_KIND(unicode);
15039 length = PyUnicode_GET_LENGTH(unicode);
15040
15041 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015042#ifdef Py_DEBUG
15043 _PyUnicode_HASH(self) = -1;
15044#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015045 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015046#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015047 _PyUnicode_STATE(self).interned = 0;
15048 _PyUnicode_STATE(self).kind = kind;
15049 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015050 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015051 _PyUnicode_STATE(self).ready = 1;
15052 _PyUnicode_WSTR(self) = NULL;
15053 _PyUnicode_UTF8_LENGTH(self) = 0;
15054 _PyUnicode_UTF8(self) = NULL;
15055 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015056 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015057
15058 share_utf8 = 0;
15059 share_wstr = 0;
15060 if (kind == PyUnicode_1BYTE_KIND) {
15061 char_size = 1;
15062 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15063 share_utf8 = 1;
15064 }
15065 else if (kind == PyUnicode_2BYTE_KIND) {
15066 char_size = 2;
15067 if (sizeof(wchar_t) == 2)
15068 share_wstr = 1;
15069 }
15070 else {
15071 assert(kind == PyUnicode_4BYTE_KIND);
15072 char_size = 4;
15073 if (sizeof(wchar_t) == 4)
15074 share_wstr = 1;
15075 }
15076
15077 /* Ensure we won't overflow the length. */
15078 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15079 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015080 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015081 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015082 data = PyObject_MALLOC((length + 1) * char_size);
15083 if (data == NULL) {
15084 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015085 goto onError;
15086 }
15087
Victor Stinnerc3c74152011-10-02 20:39:55 +020015088 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015089 if (share_utf8) {
15090 _PyUnicode_UTF8_LENGTH(self) = length;
15091 _PyUnicode_UTF8(self) = data;
15092 }
15093 if (share_wstr) {
15094 _PyUnicode_WSTR_LENGTH(self) = length;
15095 _PyUnicode_WSTR(self) = (wchar_t *)data;
15096 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015097
Christian Heimesf051e432016-09-13 20:22:02 +020015098 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015099 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015100 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015101#ifdef Py_DEBUG
15102 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15103#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015104 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015105 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015106
15107onError:
15108 Py_DECREF(unicode);
15109 Py_DECREF(self);
15110 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015111}
15112
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015113PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015114"str(object='') -> str\n\
15115str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015116\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015117Create a new string object from the given object. If encoding or\n\
15118errors is specified, then the object must expose a data buffer\n\
15119that will be decoded using the given encoding and error handler.\n\
15120Otherwise, returns the result of object.__str__() (if defined)\n\
15121or repr(object).\n\
15122encoding defaults to sys.getdefaultencoding().\n\
15123errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015124
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015125static PyObject *unicode_iter(PyObject *seq);
15126
Guido van Rossumd57fd912000-03-10 22:53:23 +000015127PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015128 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015129 "str", /* tp_name */
15130 sizeof(PyUnicodeObject), /* tp_size */
15131 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015132 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015133 (destructor)unicode_dealloc, /* tp_dealloc */
15134 0, /* tp_print */
15135 0, /* tp_getattr */
15136 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015137 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015138 unicode_repr, /* tp_repr */
15139 &unicode_as_number, /* tp_as_number */
15140 &unicode_as_sequence, /* tp_as_sequence */
15141 &unicode_as_mapping, /* tp_as_mapping */
15142 (hashfunc) unicode_hash, /* tp_hash*/
15143 0, /* tp_call*/
15144 (reprfunc) unicode_str, /* tp_str */
15145 PyObject_GenericGetAttr, /* tp_getattro */
15146 0, /* tp_setattro */
15147 0, /* tp_as_buffer */
15148 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015149 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015150 unicode_doc, /* tp_doc */
15151 0, /* tp_traverse */
15152 0, /* tp_clear */
15153 PyUnicode_RichCompare, /* tp_richcompare */
15154 0, /* tp_weaklistoffset */
15155 unicode_iter, /* tp_iter */
15156 0, /* tp_iternext */
15157 unicode_methods, /* tp_methods */
15158 0, /* tp_members */
15159 0, /* tp_getset */
15160 &PyBaseObject_Type, /* tp_base */
15161 0, /* tp_dict */
15162 0, /* tp_descr_get */
15163 0, /* tp_descr_set */
15164 0, /* tp_dictoffset */
15165 0, /* tp_init */
15166 0, /* tp_alloc */
15167 unicode_new, /* tp_new */
15168 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015169};
15170
15171/* Initialize the Unicode implementation */
15172
Victor Stinner3a50e702011-10-18 21:21:00 +020015173int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015174{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015175 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015176 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015177 0x000A, /* LINE FEED */
15178 0x000D, /* CARRIAGE RETURN */
15179 0x001C, /* FILE SEPARATOR */
15180 0x001D, /* GROUP SEPARATOR */
15181 0x001E, /* RECORD SEPARATOR */
15182 0x0085, /* NEXT LINE */
15183 0x2028, /* LINE SEPARATOR */
15184 0x2029, /* PARAGRAPH SEPARATOR */
15185 };
15186
Fred Drakee4315f52000-05-09 19:53:39 +000015187 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015188 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015189 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015190 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015191 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015192
Guido van Rossumcacfc072002-05-24 19:01:59 +000015193 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015194 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015195
15196 /* initialize the linebreak bloom filter */
15197 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015198 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015199 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015200
Christian Heimes26532f72013-07-20 14:57:16 +020015201 if (PyType_Ready(&EncodingMapType) < 0)
15202 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015203
Benjamin Petersonc4311282012-10-30 23:21:10 -040015204 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15205 Py_FatalError("Can't initialize field name iterator type");
15206
15207 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15208 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015209
Victor Stinner3a50e702011-10-18 21:21:00 +020015210 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015211}
15212
15213/* Finalize the Unicode implementation */
15214
Christian Heimesa156e092008-02-16 07:38:31 +000015215int
15216PyUnicode_ClearFreeList(void)
15217{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015218 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015219}
15220
Guido van Rossumd57fd912000-03-10 22:53:23 +000015221void
Thomas Wouters78890102000-07-22 19:25:51 +000015222_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015223{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015224 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015225
Serhiy Storchaka05997252013-01-26 12:14:02 +020015226 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015227
Serhiy Storchaka05997252013-01-26 12:14:02 +020015228 for (i = 0; i < 256; i++)
15229 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015230 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015231 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015232}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015233
Walter Dörwald16807132007-05-25 13:52:07 +000015234void
15235PyUnicode_InternInPlace(PyObject **p)
15236{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015237 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015238 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015239#ifdef Py_DEBUG
15240 assert(s != NULL);
15241 assert(_PyUnicode_CHECK(s));
15242#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015243 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015244 return;
15245#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015246 /* If it's a subclass, we don't really know what putting
15247 it in the interned dict might do. */
15248 if (!PyUnicode_CheckExact(s))
15249 return;
15250 if (PyUnicode_CHECK_INTERNED(s))
15251 return;
15252 if (interned == NULL) {
15253 interned = PyDict_New();
15254 if (interned == NULL) {
15255 PyErr_Clear(); /* Don't leave an exception */
15256 return;
15257 }
15258 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015259 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015260 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015261 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015262 if (t == NULL) {
15263 PyErr_Clear();
15264 return;
15265 }
15266 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015267 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015268 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015269 return;
15270 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015271 /* The two references in interned are not counted by refcnt.
15272 The deallocator will take care of this */
15273 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015274 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015275}
15276
15277void
15278PyUnicode_InternImmortal(PyObject **p)
15279{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015280 PyUnicode_InternInPlace(p);
15281 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015282 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015283 Py_INCREF(*p);
15284 }
Walter Dörwald16807132007-05-25 13:52:07 +000015285}
15286
15287PyObject *
15288PyUnicode_InternFromString(const char *cp)
15289{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015290 PyObject *s = PyUnicode_FromString(cp);
15291 if (s == NULL)
15292 return NULL;
15293 PyUnicode_InternInPlace(&s);
15294 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015295}
15296
Alexander Belopolsky40018472011-02-26 01:02:56 +000015297void
15298_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015299{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015300 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015301 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015302 Py_ssize_t i, n;
15303 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015304
Benjamin Peterson14339b62009-01-31 16:36:08 +000015305 if (interned == NULL || !PyDict_Check(interned))
15306 return;
15307 keys = PyDict_Keys(interned);
15308 if (keys == NULL || !PyList_Check(keys)) {
15309 PyErr_Clear();
15310 return;
15311 }
Walter Dörwald16807132007-05-25 13:52:07 +000015312
Benjamin Peterson14339b62009-01-31 16:36:08 +000015313 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15314 detector, interned unicode strings are not forcibly deallocated;
15315 rather, we give them their stolen references back, and then clear
15316 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015317
Benjamin Peterson14339b62009-01-31 16:36:08 +000015318 n = PyList_GET_SIZE(keys);
15319 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015320 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015321 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015322 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015323 if (PyUnicode_READY(s) == -1) {
15324 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015325 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015326 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015327 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015328 case SSTATE_NOT_INTERNED:
15329 /* XXX Shouldn't happen */
15330 break;
15331 case SSTATE_INTERNED_IMMORTAL:
15332 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015333 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015334 break;
15335 case SSTATE_INTERNED_MORTAL:
15336 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015337 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015338 break;
15339 default:
15340 Py_FatalError("Inconsistent interned string state.");
15341 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015342 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015343 }
15344 fprintf(stderr, "total size of all interned strings: "
15345 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15346 "mortal/immortal\n", mortal_size, immortal_size);
15347 Py_DECREF(keys);
15348 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015349 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015350}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015351
15352
15353/********************* Unicode Iterator **************************/
15354
15355typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015356 PyObject_HEAD
15357 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015358 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015359} unicodeiterobject;
15360
15361static void
15362unicodeiter_dealloc(unicodeiterobject *it)
15363{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015364 _PyObject_GC_UNTRACK(it);
15365 Py_XDECREF(it->it_seq);
15366 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015367}
15368
15369static int
15370unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15371{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015372 Py_VISIT(it->it_seq);
15373 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015374}
15375
15376static PyObject *
15377unicodeiter_next(unicodeiterobject *it)
15378{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015379 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015380
Benjamin Peterson14339b62009-01-31 16:36:08 +000015381 assert(it != NULL);
15382 seq = it->it_seq;
15383 if (seq == NULL)
15384 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015385 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015386
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015387 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15388 int kind = PyUnicode_KIND(seq);
15389 void *data = PyUnicode_DATA(seq);
15390 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15391 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015392 if (item != NULL)
15393 ++it->it_index;
15394 return item;
15395 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015396
Benjamin Peterson14339b62009-01-31 16:36:08 +000015397 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015398 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015399 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015400}
15401
15402static PyObject *
15403unicodeiter_len(unicodeiterobject *it)
15404{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015405 Py_ssize_t len = 0;
15406 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015407 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015408 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015409}
15410
15411PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15412
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015413static PyObject *
15414unicodeiter_reduce(unicodeiterobject *it)
15415{
15416 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015417 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015418 it->it_seq, it->it_index);
15419 } else {
15420 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15421 if (u == NULL)
15422 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015423 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015424 }
15425}
15426
15427PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15428
15429static PyObject *
15430unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15431{
15432 Py_ssize_t index = PyLong_AsSsize_t(state);
15433 if (index == -1 && PyErr_Occurred())
15434 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015435 if (it->it_seq != NULL) {
15436 if (index < 0)
15437 index = 0;
15438 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15439 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15440 it->it_index = index;
15441 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015442 Py_RETURN_NONE;
15443}
15444
15445PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15446
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015447static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015448 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015449 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015450 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15451 reduce_doc},
15452 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15453 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015454 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015455};
15456
15457PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015458 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15459 "str_iterator", /* tp_name */
15460 sizeof(unicodeiterobject), /* tp_basicsize */
15461 0, /* tp_itemsize */
15462 /* methods */
15463 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15464 0, /* tp_print */
15465 0, /* tp_getattr */
15466 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015467 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015468 0, /* tp_repr */
15469 0, /* tp_as_number */
15470 0, /* tp_as_sequence */
15471 0, /* tp_as_mapping */
15472 0, /* tp_hash */
15473 0, /* tp_call */
15474 0, /* tp_str */
15475 PyObject_GenericGetAttr, /* tp_getattro */
15476 0, /* tp_setattro */
15477 0, /* tp_as_buffer */
15478 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15479 0, /* tp_doc */
15480 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15481 0, /* tp_clear */
15482 0, /* tp_richcompare */
15483 0, /* tp_weaklistoffset */
15484 PyObject_SelfIter, /* tp_iter */
15485 (iternextfunc)unicodeiter_next, /* tp_iternext */
15486 unicodeiter_methods, /* tp_methods */
15487 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015488};
15489
15490static PyObject *
15491unicode_iter(PyObject *seq)
15492{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015493 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015494
Benjamin Peterson14339b62009-01-31 16:36:08 +000015495 if (!PyUnicode_Check(seq)) {
15496 PyErr_BadInternalCall();
15497 return NULL;
15498 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015499 if (PyUnicode_READY(seq) == -1)
15500 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015501 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15502 if (it == NULL)
15503 return NULL;
15504 it->it_index = 0;
15505 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015506 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015507 _PyObject_GC_TRACK(it);
15508 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015509}
15510
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015511
15512size_t
15513Py_UNICODE_strlen(const Py_UNICODE *u)
15514{
15515 int res = 0;
15516 while(*u++)
15517 res++;
15518 return res;
15519}
15520
15521Py_UNICODE*
15522Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15523{
15524 Py_UNICODE *u = s1;
15525 while ((*u++ = *s2++));
15526 return s1;
15527}
15528
15529Py_UNICODE*
15530Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15531{
15532 Py_UNICODE *u = s1;
15533 while ((*u++ = *s2++))
15534 if (n-- == 0)
15535 break;
15536 return s1;
15537}
15538
15539Py_UNICODE*
15540Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15541{
15542 Py_UNICODE *u1 = s1;
15543 u1 += Py_UNICODE_strlen(u1);
15544 Py_UNICODE_strcpy(u1, s2);
15545 return s1;
15546}
15547
15548int
15549Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15550{
15551 while (*s1 && *s2 && *s1 == *s2)
15552 s1++, s2++;
15553 if (*s1 && *s2)
15554 return (*s1 < *s2) ? -1 : +1;
15555 if (*s1)
15556 return 1;
15557 if (*s2)
15558 return -1;
15559 return 0;
15560}
15561
15562int
15563Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15564{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015565 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015566 for (; n != 0; n--) {
15567 u1 = *s1;
15568 u2 = *s2;
15569 if (u1 != u2)
15570 return (u1 < u2) ? -1 : +1;
15571 if (u1 == '\0')
15572 return 0;
15573 s1++;
15574 s2++;
15575 }
15576 return 0;
15577}
15578
15579Py_UNICODE*
15580Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15581{
15582 const Py_UNICODE *p;
15583 for (p = s; *p; p++)
15584 if (*p == c)
15585 return (Py_UNICODE*)p;
15586 return NULL;
15587}
15588
15589Py_UNICODE*
15590Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15591{
15592 const Py_UNICODE *p;
15593 p = s + Py_UNICODE_strlen(s);
15594 while (p != s) {
15595 p--;
15596 if (*p == c)
15597 return (Py_UNICODE*)p;
15598 }
15599 return NULL;
15600}
Victor Stinner331ea922010-08-10 16:37:20 +000015601
Victor Stinner71133ff2010-09-01 23:43:53 +000015602Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015603PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015604{
Victor Stinner577db2c2011-10-11 22:12:48 +020015605 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015606 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015607
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015608 if (!PyUnicode_Check(unicode)) {
15609 PyErr_BadArgument();
15610 return NULL;
15611 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015612 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015613 if (u == NULL)
15614 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015615 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015616 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015617 PyErr_NoMemory();
15618 return NULL;
15619 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015620 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015621 size *= sizeof(Py_UNICODE);
15622 copy = PyMem_Malloc(size);
15623 if (copy == NULL) {
15624 PyErr_NoMemory();
15625 return NULL;
15626 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015627 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015628 return copy;
15629}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015630
Georg Brandl66c221e2010-10-14 07:04:07 +000015631/* A _string module, to export formatter_parser and formatter_field_name_split
15632 to the string.Formatter class implemented in Python. */
15633
15634static PyMethodDef _string_methods[] = {
15635 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15636 METH_O, PyDoc_STR("split the argument as a field name")},
15637 {"formatter_parser", (PyCFunction) formatter_parser,
15638 METH_O, PyDoc_STR("parse the argument as a format string")},
15639 {NULL, NULL}
15640};
15641
15642static struct PyModuleDef _string_module = {
15643 PyModuleDef_HEAD_INIT,
15644 "_string",
15645 PyDoc_STR("string helper module"),
15646 0,
15647 _string_methods,
15648 NULL,
15649 NULL,
15650 NULL,
15651 NULL
15652};
15653
15654PyMODINIT_FUNC
15655PyInit__string(void)
15656{
15657 return PyModule_Create(&_string_module);
15658}
15659
15660
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015661#ifdef __cplusplus
15662}
15663#endif