blob: f0a908386fe8c8a35175e2f5a933286c1d4d3f3c [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
Victor Stinnerd3f08822012-05-29 12:57:52 +02001552 if (from_start < 0) {
1553 PyErr_SetString(PyExc_IndexError, "string index out of range");
1554 return -1;
1555 }
1556 if (to_start < 0) {
1557 PyErr_SetString(PyExc_IndexError, "string index out of range");
1558 return -1;
1559 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001560 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1561 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1562 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001563 "Cannot write %zi characters at %zi "
1564 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001565 how_many, to_start, PyUnicode_GET_LENGTH(to));
1566 return -1;
1567 }
1568
1569 if (how_many == 0)
1570 return 0;
1571
Victor Stinner488fa492011-12-12 00:01:39 +01001572 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001573 return -1;
1574
1575 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1576 if (err) {
1577 PyErr_Format(PyExc_SystemError,
1578 "Cannot copy %s characters "
1579 "into a string of %s characters",
1580 unicode_kind_name(from),
1581 unicode_kind_name(to));
1582 return -1;
1583 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001584 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001585}
1586
Victor Stinner17222162011-09-28 22:15:37 +02001587/* Find the maximum code point and count the number of surrogate pairs so a
1588 correct string length can be computed before converting a string to UCS4.
1589 This function counts single surrogates as a character and not as a pair.
1590
1591 Return 0 on success, or -1 on error. */
1592static int
1593find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1594 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001595{
1596 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001597 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598
Victor Stinnerc53be962011-10-02 21:33:54 +02001599 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600 *num_surrogates = 0;
1601 *maxchar = 0;
1602
1603 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001604#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001605 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1606 && (iter+1) < end
1607 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1608 {
1609 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1610 ++(*num_surrogates);
1611 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001612 }
1613 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001614#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001615 {
1616 ch = *iter;
1617 iter++;
1618 }
1619 if (ch > *maxchar) {
1620 *maxchar = ch;
1621 if (*maxchar > MAX_UNICODE) {
1622 PyErr_Format(PyExc_ValueError,
1623 "character U+%x is not in range [U+0000; U+10ffff]",
1624 ch);
1625 return -1;
1626 }
1627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001628 }
1629 return 0;
1630}
1631
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001632int
1633_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001634{
1635 wchar_t *end;
1636 Py_UCS4 maxchar = 0;
1637 Py_ssize_t num_surrogates;
1638#if SIZEOF_WCHAR_T == 2
1639 Py_ssize_t length_wo_surrogates;
1640#endif
1641
Georg Brandl7597add2011-10-05 16:36:47 +02001642 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001643 strings were created using _PyObject_New() and where no canonical
1644 representation (the str field) has been set yet aka strings
1645 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001646 assert(_PyUnicode_CHECK(unicode));
1647 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001648 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001649 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001650 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001651 /* Actually, it should neither be interned nor be anything else: */
1652 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001654 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001655 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001656 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001658
1659 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001660 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1661 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001662 PyErr_NoMemory();
1663 return -1;
1664 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001665 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001666 _PyUnicode_WSTR(unicode), end,
1667 PyUnicode_1BYTE_DATA(unicode));
1668 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1669 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1670 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1671 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001672 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001673 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001674 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001675 }
1676 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001677 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001678 _PyUnicode_UTF8(unicode) = NULL;
1679 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001680 }
1681 PyObject_FREE(_PyUnicode_WSTR(unicode));
1682 _PyUnicode_WSTR(unicode) = NULL;
1683 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1684 }
1685 /* In this case we might have to convert down from 4-byte native
1686 wchar_t to 2-byte unicode. */
1687 else if (maxchar < 65536) {
1688 assert(num_surrogates == 0 &&
1689 "FindMaxCharAndNumSurrogatePairs() messed up");
1690
Victor Stinner506f5922011-09-28 22:34:18 +02001691#if SIZEOF_WCHAR_T == 2
1692 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001693 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001694 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1695 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1696 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001697 _PyUnicode_UTF8(unicode) = NULL;
1698 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001699#else
1700 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001701 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001702 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001703 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001704 PyErr_NoMemory();
1705 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706 }
Victor Stinner506f5922011-09-28 22:34:18 +02001707 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1708 _PyUnicode_WSTR(unicode), end,
1709 PyUnicode_2BYTE_DATA(unicode));
1710 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1711 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1712 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001713 _PyUnicode_UTF8(unicode) = NULL;
1714 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001715 PyObject_FREE(_PyUnicode_WSTR(unicode));
1716 _PyUnicode_WSTR(unicode) = NULL;
1717 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1718#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001719 }
1720 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1721 else {
1722#if SIZEOF_WCHAR_T == 2
1723 /* in case the native representation is 2-bytes, we need to allocate a
1724 new normalized 4-byte version. */
1725 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001726 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1727 PyErr_NoMemory();
1728 return -1;
1729 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001730 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1731 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001732 PyErr_NoMemory();
1733 return -1;
1734 }
1735 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1736 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001737 _PyUnicode_UTF8(unicode) = NULL;
1738 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001739 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1740 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001741 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001742 PyObject_FREE(_PyUnicode_WSTR(unicode));
1743 _PyUnicode_WSTR(unicode) = NULL;
1744 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1745#else
1746 assert(num_surrogates == 0);
1747
Victor Stinnerc3c74152011-10-02 20:39:55 +02001748 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001749 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001750 _PyUnicode_UTF8(unicode) = NULL;
1751 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1753#endif
1754 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1755 }
1756 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001757 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 return 0;
1759}
1760
Alexander Belopolsky40018472011-02-26 01:02:56 +00001761static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001762unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001763{
Walter Dörwald16807132007-05-25 13:52:07 +00001764 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001765 case SSTATE_NOT_INTERNED:
1766 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001767
Benjamin Peterson29060642009-01-31 22:14:21 +00001768 case SSTATE_INTERNED_MORTAL:
1769 /* revive dead object temporarily for DelItem */
1770 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001771 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001772 Py_FatalError(
1773 "deletion of interned string failed");
1774 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001775
Benjamin Peterson29060642009-01-31 22:14:21 +00001776 case SSTATE_INTERNED_IMMORTAL:
1777 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001778
Benjamin Peterson29060642009-01-31 22:14:21 +00001779 default:
1780 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001781 }
1782
Victor Stinner03490912011-10-03 23:45:12 +02001783 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001784 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001785 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001786 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001787 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1788 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001789
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001790 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001791}
1792
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001793#ifdef Py_DEBUG
1794static int
1795unicode_is_singleton(PyObject *unicode)
1796{
1797 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1798 if (unicode == unicode_empty)
1799 return 1;
1800 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1801 {
1802 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1803 if (ch < 256 && unicode_latin1[ch] == unicode)
1804 return 1;
1805 }
1806 return 0;
1807}
1808#endif
1809
Alexander Belopolsky40018472011-02-26 01:02:56 +00001810static int
Victor Stinner488fa492011-12-12 00:01:39 +01001811unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001812{
Victor Stinner488fa492011-12-12 00:01:39 +01001813 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001814 if (Py_REFCNT(unicode) != 1)
1815 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001816 if (_PyUnicode_HASH(unicode) != -1)
1817 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001818 if (PyUnicode_CHECK_INTERNED(unicode))
1819 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001820 if (!PyUnicode_CheckExact(unicode))
1821 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001822#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001823 /* singleton refcount is greater than 1 */
1824 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001825#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001826 return 1;
1827}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001828
Victor Stinnerfe226c02011-10-03 03:52:20 +02001829static int
1830unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1831{
1832 PyObject *unicode;
1833 Py_ssize_t old_length;
1834
1835 assert(p_unicode != NULL);
1836 unicode = *p_unicode;
1837
1838 assert(unicode != NULL);
1839 assert(PyUnicode_Check(unicode));
1840 assert(0 <= length);
1841
Victor Stinner910337b2011-10-03 03:20:16 +02001842 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001843 old_length = PyUnicode_WSTR_LENGTH(unicode);
1844 else
1845 old_length = PyUnicode_GET_LENGTH(unicode);
1846 if (old_length == length)
1847 return 0;
1848
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001849 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001850 _Py_INCREF_UNICODE_EMPTY();
1851 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001852 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001853 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001854 return 0;
1855 }
1856
Victor Stinner488fa492011-12-12 00:01:39 +01001857 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001858 PyObject *copy = resize_copy(unicode, length);
1859 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001860 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001861 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001862 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001863 }
1864
Victor Stinnerfe226c02011-10-03 03:52:20 +02001865 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001866 PyObject *new_unicode = resize_compact(unicode, length);
1867 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001868 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001869 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001870 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001871 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001872 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001873}
1874
Alexander Belopolsky40018472011-02-26 01:02:56 +00001875int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001876PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001877{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001878 PyObject *unicode;
1879 if (p_unicode == NULL) {
1880 PyErr_BadInternalCall();
1881 return -1;
1882 }
1883 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001884 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001885 {
1886 PyErr_BadInternalCall();
1887 return -1;
1888 }
1889 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001890}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001891
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001892/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001893
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001894 WARNING: The function doesn't copy the terminating null character and
1895 doesn't check the maximum character (may write a latin1 character in an
1896 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001897static void
1898unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1899 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001900{
1901 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1902 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001903 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001904
1905 switch (kind) {
1906 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001907 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001908#ifdef Py_DEBUG
1909 if (PyUnicode_IS_ASCII(unicode)) {
1910 Py_UCS4 maxchar = ucs1lib_find_max_char(
1911 (const Py_UCS1*)str,
1912 (const Py_UCS1*)str + len);
1913 assert(maxchar < 128);
1914 }
1915#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001916 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001917 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001918 }
1919 case PyUnicode_2BYTE_KIND: {
1920 Py_UCS2 *start = (Py_UCS2 *)data + index;
1921 Py_UCS2 *ucs2 = start;
1922 assert(index <= PyUnicode_GET_LENGTH(unicode));
1923
Victor Stinner184252a2012-06-16 02:57:41 +02001924 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001925 *ucs2 = (Py_UCS2)*str;
1926
1927 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001928 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001929 }
1930 default: {
1931 Py_UCS4 *start = (Py_UCS4 *)data + index;
1932 Py_UCS4 *ucs4 = start;
1933 assert(kind == PyUnicode_4BYTE_KIND);
1934 assert(index <= PyUnicode_GET_LENGTH(unicode));
1935
Victor Stinner184252a2012-06-16 02:57:41 +02001936 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001937 *ucs4 = (Py_UCS4)*str;
1938
1939 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001940 }
1941 }
1942}
1943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001944static PyObject*
1945get_latin1_char(unsigned char ch)
1946{
Victor Stinnera464fc12011-10-02 20:39:30 +02001947 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001949 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950 if (!unicode)
1951 return NULL;
1952 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001953 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 unicode_latin1[ch] = unicode;
1955 }
1956 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001957 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001958}
1959
Victor Stinner985a82a2014-01-03 12:53:47 +01001960static PyObject*
1961unicode_char(Py_UCS4 ch)
1962{
1963 PyObject *unicode;
1964
1965 assert(ch <= MAX_UNICODE);
1966
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001967 if (ch < 256)
1968 return get_latin1_char(ch);
1969
Victor Stinner985a82a2014-01-03 12:53:47 +01001970 unicode = PyUnicode_New(1, ch);
1971 if (unicode == NULL)
1972 return NULL;
1973 switch (PyUnicode_KIND(unicode)) {
1974 case PyUnicode_1BYTE_KIND:
1975 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1976 break;
1977 case PyUnicode_2BYTE_KIND:
1978 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1979 break;
1980 default:
1981 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1982 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1983 }
1984 assert(_PyUnicode_CheckConsistency(unicode, 1));
1985 return unicode;
1986}
1987
Alexander Belopolsky40018472011-02-26 01:02:56 +00001988PyObject *
1989PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001990{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001991 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992 Py_UCS4 maxchar = 0;
1993 Py_ssize_t num_surrogates;
1994
1995 if (u == NULL)
1996 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001997
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001998 /* If the Unicode data is known at construction time, we can apply
1999 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002001 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002002 if (size == 0)
2003 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002005 /* Single character Unicode objects in the Latin-1 range are
2006 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002007 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 return get_latin1_char((unsigned char)*u);
2009
2010 /* If not empty and not single character, copy the Unicode data
2011 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002012 if (find_maxchar_surrogates(u, u + size,
2013 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014 return NULL;
2015
Victor Stinner8faf8212011-12-08 22:14:11 +01002016 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002017 if (!unicode)
2018 return NULL;
2019
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002020 switch (PyUnicode_KIND(unicode)) {
2021 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002022 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002023 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2024 break;
2025 case PyUnicode_2BYTE_KIND:
2026#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002027 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002028#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002029 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002030 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2031#endif
2032 break;
2033 case PyUnicode_4BYTE_KIND:
2034#if SIZEOF_WCHAR_T == 2
2035 /* This is the only case which has to process surrogates, thus
2036 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002037 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002038#else
2039 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002040 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041#endif
2042 break;
2043 default:
2044 assert(0 && "Impossible state");
2045 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002046
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002047 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002048}
2049
Alexander Belopolsky40018472011-02-26 01:02:56 +00002050PyObject *
2051PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002052{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002053 if (size < 0) {
2054 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002055 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002056 return NULL;
2057 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002058 if (u != NULL)
2059 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2060 else
2061 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002062}
2063
Alexander Belopolsky40018472011-02-26 01:02:56 +00002064PyObject *
2065PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002066{
2067 size_t size = strlen(u);
2068 if (size > PY_SSIZE_T_MAX) {
2069 PyErr_SetString(PyExc_OverflowError, "input too long");
2070 return NULL;
2071 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002072 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002073}
2074
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002075PyObject *
2076_PyUnicode_FromId(_Py_Identifier *id)
2077{
2078 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002079 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2080 strlen(id->string),
2081 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002082 if (!id->object)
2083 return NULL;
2084 PyUnicode_InternInPlace(&id->object);
2085 assert(!id->next);
2086 id->next = static_strings;
2087 static_strings = id;
2088 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002089 return id->object;
2090}
2091
2092void
2093_PyUnicode_ClearStaticStrings()
2094{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002095 _Py_Identifier *tmp, *s = static_strings;
2096 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002097 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002098 tmp = s->next;
2099 s->next = NULL;
2100 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002101 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002102 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002103}
2104
Benjamin Peterson0df54292012-03-26 14:50:32 -04002105/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002106
Victor Stinnerd3f08822012-05-29 12:57:52 +02002107PyObject*
2108_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002109{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002110 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002111 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002112 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002113#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002114 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002115#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002116 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002117 }
Victor Stinner785938e2011-12-11 20:09:03 +01002118 unicode = PyUnicode_New(size, 127);
2119 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002120 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002121 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2122 assert(_PyUnicode_CheckConsistency(unicode, 1));
2123 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002124}
2125
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002126static Py_UCS4
2127kind_maxchar_limit(unsigned int kind)
2128{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002129 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002130 case PyUnicode_1BYTE_KIND:
2131 return 0x80;
2132 case PyUnicode_2BYTE_KIND:
2133 return 0x100;
2134 case PyUnicode_4BYTE_KIND:
2135 return 0x10000;
2136 default:
2137 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01002138 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002139 }
2140}
2141
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -07002142static inline Py_UCS4
Victor Stinnere6abb482012-05-02 01:15:40 +02002143align_maxchar(Py_UCS4 maxchar)
2144{
2145 if (maxchar <= 127)
2146 return 127;
2147 else if (maxchar <= 255)
2148 return 255;
2149 else if (maxchar <= 65535)
2150 return 65535;
2151 else
2152 return MAX_UNICODE;
2153}
2154
Victor Stinner702c7342011-10-05 13:50:52 +02002155static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002156_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002157{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002158 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002159 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002160
Serhiy Storchaka678db842013-01-26 12:16:36 +02002161 if (size == 0)
2162 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002163 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002164 if (size == 1)
2165 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002166
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002167 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002168 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002169 if (!res)
2170 return NULL;
2171 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002172 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002174}
2175
Victor Stinnere57b1c02011-09-28 22:20:48 +02002176static PyObject*
2177_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002178{
2179 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002180 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002181
Serhiy Storchaka678db842013-01-26 12:16:36 +02002182 if (size == 0)
2183 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002184 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002185 if (size == 1)
2186 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002187
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002188 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002189 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002190 if (!res)
2191 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002192 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002193 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002194 else {
2195 _PyUnicode_CONVERT_BYTES(
2196 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2197 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002198 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002199 return res;
2200}
2201
Victor Stinnere57b1c02011-09-28 22:20:48 +02002202static PyObject*
2203_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002204{
2205 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002206 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002207
Serhiy Storchaka678db842013-01-26 12:16:36 +02002208 if (size == 0)
2209 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002210 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002211 if (size == 1)
2212 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002213
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002214 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002215 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 if (!res)
2217 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002218 if (max_char < 256)
2219 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2220 PyUnicode_1BYTE_DATA(res));
2221 else if (max_char < 0x10000)
2222 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2223 PyUnicode_2BYTE_DATA(res));
2224 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002225 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002226 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002227 return res;
2228}
2229
2230PyObject*
2231PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2232{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002233 if (size < 0) {
2234 PyErr_SetString(PyExc_ValueError, "size must be positive");
2235 return NULL;
2236 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002237 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002238 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002239 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002241 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002242 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002243 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002244 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002245 PyErr_SetString(PyExc_SystemError, "invalid kind");
2246 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002248}
2249
Victor Stinnerece58de2012-04-23 23:36:38 +02002250Py_UCS4
2251_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2252{
2253 enum PyUnicode_Kind kind;
2254 void *startptr, *endptr;
2255
2256 assert(PyUnicode_IS_READY(unicode));
2257 assert(0 <= start);
2258 assert(end <= PyUnicode_GET_LENGTH(unicode));
2259 assert(start <= end);
2260
2261 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2262 return PyUnicode_MAX_CHAR_VALUE(unicode);
2263
2264 if (start == end)
2265 return 127;
2266
Victor Stinner94d558b2012-04-27 22:26:58 +02002267 if (PyUnicode_IS_ASCII(unicode))
2268 return 127;
2269
Victor Stinnerece58de2012-04-23 23:36:38 +02002270 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002271 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002272 endptr = (char *)startptr + end * kind;
2273 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002274 switch(kind) {
2275 case PyUnicode_1BYTE_KIND:
2276 return ucs1lib_find_max_char(startptr, endptr);
2277 case PyUnicode_2BYTE_KIND:
2278 return ucs2lib_find_max_char(startptr, endptr);
2279 case PyUnicode_4BYTE_KIND:
2280 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002281 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002282 assert(0);
2283 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002284 }
2285}
2286
Victor Stinner25a4b292011-10-06 12:31:55 +02002287/* Ensure that a string uses the most efficient storage, if it is not the
2288 case: create a new string with of the right kind. Write NULL into *p_unicode
2289 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002290static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002291unicode_adjust_maxchar(PyObject **p_unicode)
2292{
2293 PyObject *unicode, *copy;
2294 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002295 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002296 unsigned int kind;
2297
2298 assert(p_unicode != NULL);
2299 unicode = *p_unicode;
2300 assert(PyUnicode_IS_READY(unicode));
2301 if (PyUnicode_IS_ASCII(unicode))
2302 return;
2303
2304 len = PyUnicode_GET_LENGTH(unicode);
2305 kind = PyUnicode_KIND(unicode);
2306 if (kind == PyUnicode_1BYTE_KIND) {
2307 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002308 max_char = ucs1lib_find_max_char(u, u + len);
2309 if (max_char >= 128)
2310 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002311 }
2312 else if (kind == PyUnicode_2BYTE_KIND) {
2313 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002314 max_char = ucs2lib_find_max_char(u, u + len);
2315 if (max_char >= 256)
2316 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002317 }
2318 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002319 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002320 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002321 max_char = ucs4lib_find_max_char(u, u + len);
2322 if (max_char >= 0x10000)
2323 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002324 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002325 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002326 if (copy != NULL)
2327 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002328 Py_DECREF(unicode);
2329 *p_unicode = copy;
2330}
2331
Victor Stinner034f6cf2011-09-30 02:26:44 +02002332PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002333_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002334{
Victor Stinner87af4f22011-11-21 23:03:47 +01002335 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002336 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002337
Victor Stinner034f6cf2011-09-30 02:26:44 +02002338 if (!PyUnicode_Check(unicode)) {
2339 PyErr_BadInternalCall();
2340 return NULL;
2341 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002342 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002343 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002344
Victor Stinner87af4f22011-11-21 23:03:47 +01002345 length = PyUnicode_GET_LENGTH(unicode);
2346 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002347 if (!copy)
2348 return NULL;
2349 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2350
Christian Heimesf051e432016-09-13 20:22:02 +02002351 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002352 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002353 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002354 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002355}
2356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002357
Victor Stinnerbc603d12011-10-02 01:00:40 +02002358/* Widen Unicode objects to larger buffers. Don't write terminating null
2359 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002360
2361void*
2362_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2363{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002364 Py_ssize_t len;
2365 void *result;
2366 unsigned int skind;
2367
Benjamin Petersonbac79492012-01-14 13:34:47 -05002368 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002369 return NULL;
2370
2371 len = PyUnicode_GET_LENGTH(s);
2372 skind = PyUnicode_KIND(s);
2373 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002374 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375 return NULL;
2376 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002377 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002378 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002379 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002380 if (!result)
2381 return PyErr_NoMemory();
2382 assert(skind == PyUnicode_1BYTE_KIND);
2383 _PyUnicode_CONVERT_BYTES(
2384 Py_UCS1, Py_UCS2,
2385 PyUnicode_1BYTE_DATA(s),
2386 PyUnicode_1BYTE_DATA(s) + len,
2387 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002388 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002389 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002390 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002391 if (!result)
2392 return PyErr_NoMemory();
2393 if (skind == PyUnicode_2BYTE_KIND) {
2394 _PyUnicode_CONVERT_BYTES(
2395 Py_UCS2, Py_UCS4,
2396 PyUnicode_2BYTE_DATA(s),
2397 PyUnicode_2BYTE_DATA(s) + len,
2398 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002400 else {
2401 assert(skind == PyUnicode_1BYTE_KIND);
2402 _PyUnicode_CONVERT_BYTES(
2403 Py_UCS1, Py_UCS4,
2404 PyUnicode_1BYTE_DATA(s),
2405 PyUnicode_1BYTE_DATA(s) + len,
2406 result);
2407 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002408 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002409 default:
2410 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002411 }
Victor Stinner01698042011-10-04 00:04:26 +02002412 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 return NULL;
2414}
2415
2416static Py_UCS4*
2417as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2418 int copy_null)
2419{
2420 int kind;
2421 void *data;
2422 Py_ssize_t len, targetlen;
2423 if (PyUnicode_READY(string) == -1)
2424 return NULL;
2425 kind = PyUnicode_KIND(string);
2426 data = PyUnicode_DATA(string);
2427 len = PyUnicode_GET_LENGTH(string);
2428 targetlen = len;
2429 if (copy_null)
2430 targetlen++;
2431 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002432 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 if (!target) {
2434 PyErr_NoMemory();
2435 return NULL;
2436 }
2437 }
2438 else {
2439 if (targetsize < targetlen) {
2440 PyErr_Format(PyExc_SystemError,
2441 "string is longer than the buffer");
2442 if (copy_null && 0 < targetsize)
2443 target[0] = 0;
2444 return NULL;
2445 }
2446 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002447 if (kind == PyUnicode_1BYTE_KIND) {
2448 Py_UCS1 *start = (Py_UCS1 *) data;
2449 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002450 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002451 else if (kind == PyUnicode_2BYTE_KIND) {
2452 Py_UCS2 *start = (Py_UCS2 *) data;
2453 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2454 }
2455 else {
2456 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002457 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002458 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 if (copy_null)
2460 target[len] = 0;
2461 return target;
2462}
2463
2464Py_UCS4*
2465PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2466 int copy_null)
2467{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002468 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002469 PyErr_BadInternalCall();
2470 return NULL;
2471 }
2472 return as_ucs4(string, target, targetsize, copy_null);
2473}
2474
2475Py_UCS4*
2476PyUnicode_AsUCS4Copy(PyObject *string)
2477{
2478 return as_ucs4(string, NULL, 0, 1);
2479}
2480
2481#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002482
Alexander Belopolsky40018472011-02-26 01:02:56 +00002483PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002484PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002485{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002486 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002487 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002488 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002489 PyErr_BadInternalCall();
2490 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002491 }
2492
Martin v. Löwis790465f2008-04-05 20:41:37 +00002493 if (size == -1) {
2494 size = wcslen(w);
2495 }
2496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002497 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002498}
2499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002501
Victor Stinner15a11362012-10-06 23:48:20 +02002502/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002503 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2504 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2505#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002506
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002507static int
2508unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2509 Py_ssize_t width, Py_ssize_t precision)
2510{
2511 Py_ssize_t length, fill, arglen;
2512 Py_UCS4 maxchar;
2513
2514 if (PyUnicode_READY(str) == -1)
2515 return -1;
2516
2517 length = PyUnicode_GET_LENGTH(str);
2518 if ((precision == -1 || precision >= length)
2519 && width <= length)
2520 return _PyUnicodeWriter_WriteStr(writer, str);
2521
2522 if (precision != -1)
2523 length = Py_MIN(precision, length);
2524
2525 arglen = Py_MAX(length, width);
2526 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2527 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2528 else
2529 maxchar = writer->maxchar;
2530
2531 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2532 return -1;
2533
2534 if (width > length) {
2535 fill = width - length;
2536 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2537 return -1;
2538 writer->pos += fill;
2539 }
2540
2541 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2542 str, 0, length);
2543 writer->pos += length;
2544 return 0;
2545}
2546
2547static int
2548unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2549 Py_ssize_t width, Py_ssize_t precision)
2550{
2551 /* UTF-8 */
2552 Py_ssize_t length;
2553 PyObject *unicode;
2554 int res;
2555
2556 length = strlen(str);
2557 if (precision != -1)
2558 length = Py_MIN(length, precision);
2559 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2560 if (unicode == NULL)
2561 return -1;
2562
2563 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2564 Py_DECREF(unicode);
2565 return res;
2566}
2567
Victor Stinner96865452011-03-01 23:44:09 +00002568static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002569unicode_fromformat_arg(_PyUnicodeWriter *writer,
2570 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002571{
Victor Stinnere215d962012-10-06 23:03:36 +02002572 const char *p;
2573 Py_ssize_t len;
2574 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002575 Py_ssize_t width;
2576 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002577 int longflag;
2578 int longlongflag;
2579 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002580 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002581
2582 p = f;
2583 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002584 zeropad = 0;
2585 if (*f == '0') {
2586 zeropad = 1;
2587 f++;
2588 }
Victor Stinner96865452011-03-01 23:44:09 +00002589
2590 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002591 width = -1;
2592 if (Py_ISDIGIT((unsigned)*f)) {
2593 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002594 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002595 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002596 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002597 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002598 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002599 return NULL;
2600 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002601 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002602 f++;
2603 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002604 }
2605 precision = -1;
2606 if (*f == '.') {
2607 f++;
2608 if (Py_ISDIGIT((unsigned)*f)) {
2609 precision = (*f - '0');
2610 f++;
2611 while (Py_ISDIGIT((unsigned)*f)) {
2612 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2613 PyErr_SetString(PyExc_ValueError,
2614 "precision too big");
2615 return NULL;
2616 }
2617 precision = (precision * 10) + (*f - '0');
2618 f++;
2619 }
2620 }
Victor Stinner96865452011-03-01 23:44:09 +00002621 if (*f == '%') {
2622 /* "%.3%s" => f points to "3" */
2623 f--;
2624 }
2625 }
2626 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002627 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002628 f--;
2629 }
Victor Stinner96865452011-03-01 23:44:09 +00002630
2631 /* Handle %ld, %lu, %lld and %llu. */
2632 longflag = 0;
2633 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002634 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002635 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002636 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002637 longflag = 1;
2638 ++f;
2639 }
Victor Stinner96865452011-03-01 23:44:09 +00002640 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002641 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002642 longlongflag = 1;
2643 f += 2;
2644 }
Victor Stinner96865452011-03-01 23:44:09 +00002645 }
2646 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002647 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002648 size_tflag = 1;
2649 ++f;
2650 }
Victor Stinnere215d962012-10-06 23:03:36 +02002651
2652 if (f[1] == '\0')
2653 writer->overallocate = 0;
2654
2655 switch (*f) {
2656 case 'c':
2657 {
2658 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002659 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002660 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002661 "character argument not in range(0x110000)");
2662 return NULL;
2663 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002664 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002665 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002666 break;
2667 }
2668
2669 case 'i':
2670 case 'd':
2671 case 'u':
2672 case 'x':
2673 {
2674 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002675 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002676 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002677
2678 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002679 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002680 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002681 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002682 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002683 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002684 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002685 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002686 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002687 va_arg(*vargs, size_t));
2688 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002689 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002690 va_arg(*vargs, unsigned int));
2691 }
2692 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002693 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002694 }
2695 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002696 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002697 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002698 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002699 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002700 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002701 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002702 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002703 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002704 va_arg(*vargs, Py_ssize_t));
2705 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002706 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002707 va_arg(*vargs, int));
2708 }
2709 assert(len >= 0);
2710
Victor Stinnere215d962012-10-06 23:03:36 +02002711 if (precision < len)
2712 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002713
2714 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002715 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2716 return NULL;
2717
Victor Stinnere215d962012-10-06 23:03:36 +02002718 if (width > precision) {
2719 Py_UCS4 fillchar;
2720 fill = width - precision;
2721 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002722 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2723 return NULL;
2724 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002725 }
Victor Stinner15a11362012-10-06 23:48:20 +02002726 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002727 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002728 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2729 return NULL;
2730 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002731 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002732
Victor Stinner4a587072013-11-19 12:54:53 +01002733 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2734 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002735 break;
2736 }
2737
2738 case 'p':
2739 {
2740 char number[MAX_LONG_LONG_CHARS];
2741
2742 len = sprintf(number, "%p", va_arg(*vargs, void*));
2743 assert(len >= 0);
2744
2745 /* %p is ill-defined: ensure leading 0x. */
2746 if (number[1] == 'X')
2747 number[1] = 'x';
2748 else if (number[1] != 'x') {
2749 memmove(number + 2, number,
2750 strlen(number) + 1);
2751 number[0] = '0';
2752 number[1] = 'x';
2753 len += 2;
2754 }
2755
Victor Stinner4a587072013-11-19 12:54:53 +01002756 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002757 return NULL;
2758 break;
2759 }
2760
2761 case 's':
2762 {
2763 /* UTF-8 */
2764 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002765 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002766 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002767 break;
2768 }
2769
2770 case 'U':
2771 {
2772 PyObject *obj = va_arg(*vargs, PyObject *);
2773 assert(obj && _PyUnicode_CHECK(obj));
2774
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002775 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002776 return NULL;
2777 break;
2778 }
2779
2780 case 'V':
2781 {
2782 PyObject *obj = va_arg(*vargs, PyObject *);
2783 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002784 if (obj) {
2785 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002786 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002787 return NULL;
2788 }
2789 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002790 assert(str != NULL);
2791 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002792 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002793 }
2794 break;
2795 }
2796
2797 case 'S':
2798 {
2799 PyObject *obj = va_arg(*vargs, PyObject *);
2800 PyObject *str;
2801 assert(obj);
2802 str = PyObject_Str(obj);
2803 if (!str)
2804 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002805 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002806 Py_DECREF(str);
2807 return NULL;
2808 }
2809 Py_DECREF(str);
2810 break;
2811 }
2812
2813 case 'R':
2814 {
2815 PyObject *obj = va_arg(*vargs, PyObject *);
2816 PyObject *repr;
2817 assert(obj);
2818 repr = PyObject_Repr(obj);
2819 if (!repr)
2820 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002821 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002822 Py_DECREF(repr);
2823 return NULL;
2824 }
2825 Py_DECREF(repr);
2826 break;
2827 }
2828
2829 case 'A':
2830 {
2831 PyObject *obj = va_arg(*vargs, PyObject *);
2832 PyObject *ascii;
2833 assert(obj);
2834 ascii = PyObject_ASCII(obj);
2835 if (!ascii)
2836 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002837 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002838 Py_DECREF(ascii);
2839 return NULL;
2840 }
2841 Py_DECREF(ascii);
2842 break;
2843 }
2844
2845 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002846 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002847 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002848 break;
2849
2850 default:
2851 /* if we stumble upon an unknown formatting code, copy the rest
2852 of the format string to the output string. (we cannot just
2853 skip the code, since there's no way to know what's in the
2854 argument list) */
2855 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002856 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002857 return NULL;
2858 f = p+len;
2859 return f;
2860 }
2861
2862 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002863 return f;
2864}
2865
Walter Dörwaldd2034312007-05-18 16:29:38 +00002866PyObject *
2867PyUnicode_FromFormatV(const char *format, va_list vargs)
2868{
Victor Stinnere215d962012-10-06 23:03:36 +02002869 va_list vargs2;
2870 const char *f;
2871 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002872
Victor Stinner8f674cc2013-04-17 23:02:17 +02002873 _PyUnicodeWriter_Init(&writer);
2874 writer.min_length = strlen(format) + 100;
2875 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002876
Benjamin Peterson0c212142016-09-20 20:39:33 -07002877 // Copy varags to be able to pass a reference to a subfunction.
2878 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002879
2880 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002881 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002882 f = unicode_fromformat_arg(&writer, f, &vargs2);
2883 if (f == NULL)
2884 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002886 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002887 const char *p;
2888 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002889
Victor Stinnere215d962012-10-06 23:03:36 +02002890 p = f;
2891 do
2892 {
2893 if ((unsigned char)*p > 127) {
2894 PyErr_Format(PyExc_ValueError,
2895 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2896 "string, got a non-ASCII byte: 0x%02x",
2897 (unsigned char)*p);
2898 return NULL;
2899 }
2900 p++;
2901 }
2902 while (*p != '\0' && *p != '%');
2903 len = p - f;
2904
2905 if (*p == '\0')
2906 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002907
2908 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002909 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002910
2911 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002912 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002913 }
Victor Stinnere215d962012-10-06 23:03:36 +02002914 return _PyUnicodeWriter_Finish(&writer);
2915
2916 fail:
2917 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002918 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002919}
2920
Walter Dörwaldd2034312007-05-18 16:29:38 +00002921PyObject *
2922PyUnicode_FromFormat(const char *format, ...)
2923{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002924 PyObject* ret;
2925 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002926
2927#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002928 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002929#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002930 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002931#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002932 ret = PyUnicode_FromFormatV(format, vargs);
2933 va_end(vargs);
2934 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002935}
2936
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002937#ifdef HAVE_WCHAR_H
2938
Victor Stinner5593d8a2010-10-02 11:11:27 +00002939/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2940 convert a Unicode object to a wide character string.
2941
Victor Stinnerd88d9832011-09-06 02:00:05 +02002942 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002943 character) required to convert the unicode object. Ignore size argument.
2944
Victor Stinnerd88d9832011-09-06 02:00:05 +02002945 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002946 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002947 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002948static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002949unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002950 wchar_t *w,
2951 Py_ssize_t size)
2952{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002953 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002954 const wchar_t *wstr;
2955
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002956 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002957 if (wstr == NULL)
2958 return -1;
2959
Victor Stinner5593d8a2010-10-02 11:11:27 +00002960 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002961 if (size > res)
2962 size = res + 1;
2963 else
2964 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002965 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002966 return res;
2967 }
2968 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002969 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002970}
2971
2972Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002973PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002974 wchar_t *w,
2975 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002976{
2977 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002978 PyErr_BadInternalCall();
2979 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002980 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002981 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002982}
2983
Victor Stinner137c34c2010-09-29 10:25:54 +00002984wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002985PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002986 Py_ssize_t *size)
2987{
2988 wchar_t* buffer;
2989 Py_ssize_t buflen;
2990
2991 if (unicode == NULL) {
2992 PyErr_BadInternalCall();
2993 return NULL;
2994 }
2995
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002996 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002997 if (buflen == -1)
2998 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002999 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00003000 if (buffer == NULL) {
3001 PyErr_NoMemory();
3002 return NULL;
3003 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003004 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02003005 if (buflen == -1) {
3006 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003007 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02003008 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00003009 if (size != NULL)
3010 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003011 return buffer;
3012}
3013
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003014#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003015
Alexander Belopolsky40018472011-02-26 01:02:56 +00003016PyObject *
3017PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003018{
Victor Stinner8faf8212011-12-08 22:14:11 +01003019 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003020 PyErr_SetString(PyExc_ValueError,
3021 "chr() arg not in range(0x110000)");
3022 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003023 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003024
Victor Stinner985a82a2014-01-03 12:53:47 +01003025 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003026}
3027
Alexander Belopolsky40018472011-02-26 01:02:56 +00003028PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003029PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003030{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003031 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003032 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003033 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003034 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003035 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003036 Py_INCREF(obj);
3037 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003038 }
3039 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003040 /* For a Unicode subtype that's not a Unicode object,
3041 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003042 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003043 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003044 PyErr_Format(PyExc_TypeError,
3045 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003046 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003047 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003048}
3049
Alexander Belopolsky40018472011-02-26 01:02:56 +00003050PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003051PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003052 const char *encoding,
3053 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003054{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003055 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003056 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003057
Guido van Rossumd57fd912000-03-10 22:53:23 +00003058 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003059 PyErr_BadInternalCall();
3060 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003061 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003062
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003063 /* Decoding bytes objects is the most common case and should be fast */
3064 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003065 if (PyBytes_GET_SIZE(obj) == 0)
3066 _Py_RETURN_UNICODE_EMPTY();
3067 v = PyUnicode_Decode(
3068 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3069 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003070 return v;
3071 }
3072
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003073 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003074 PyErr_SetString(PyExc_TypeError,
3075 "decoding str is not supported");
3076 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003077 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003078
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003079 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3080 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3081 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003082 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003083 Py_TYPE(obj)->tp_name);
3084 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003085 }
Tim Petersced69f82003-09-16 20:30:58 +00003086
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003087 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003088 PyBuffer_Release(&buffer);
3089 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003090 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003091
Serhiy Storchaka05997252013-01-26 12:14:02 +02003092 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003093 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003094 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003095}
3096
Victor Stinner942889a2016-09-05 15:40:10 -07003097/* Normalize an encoding name: C implementation of
3098 encodings.normalize_encoding(). Return 1 on success, or 0 on error (encoding
3099 is longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003100int
3101_Py_normalize_encoding(const char *encoding,
3102 char *lower,
3103 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003104{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003105 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003106 char *l;
3107 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003108 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003109
Victor Stinner942889a2016-09-05 15:40:10 -07003110 assert(encoding != NULL);
3111
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003112 e = encoding;
3113 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003114 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003115 punct = 0;
3116 while (1) {
3117 char c = *e;
3118 if (c == 0) {
3119 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003120 }
Victor Stinner942889a2016-09-05 15:40:10 -07003121
3122 if (Py_ISALNUM(c) || c == '.') {
3123 if (punct && l != lower) {
3124 if (l == l_end) {
3125 return 0;
3126 }
3127 *l++ = '_';
3128 }
3129 punct = 0;
3130
3131 if (l == l_end) {
3132 return 0;
3133 }
3134 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003135 }
3136 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003137 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003138 }
Victor Stinner942889a2016-09-05 15:40:10 -07003139
3140 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003141 }
3142 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003143 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003144}
3145
Alexander Belopolsky40018472011-02-26 01:02:56 +00003146PyObject *
3147PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003148 Py_ssize_t size,
3149 const char *encoding,
3150 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003151{
3152 PyObject *buffer = NULL, *unicode;
3153 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003154 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3155
3156 if (encoding == NULL) {
3157 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3158 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003159
Fred Drakee4315f52000-05-09 19:53:39 +00003160 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003161 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3162 char *lower = buflower;
3163
3164 /* Fast paths */
3165 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3166 lower += 3;
3167 if (*lower == '_') {
3168 /* Match "utf8" and "utf_8" */
3169 lower++;
3170 }
3171
3172 if (lower[0] == '8' && lower[1] == 0) {
3173 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3174 }
3175 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3176 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3177 }
3178 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3179 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3180 }
3181 }
3182 else {
3183 if (strcmp(lower, "ascii") == 0
3184 || strcmp(lower, "us_ascii") == 0) {
3185 return PyUnicode_DecodeASCII(s, size, errors);
3186 }
Steve Dowercc16be82016-09-08 10:35:16 -07003187 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003188 else if (strcmp(lower, "mbcs") == 0) {
3189 return PyUnicode_DecodeMBCS(s, size, errors);
3190 }
3191 #endif
3192 else if (strcmp(lower, "latin1") == 0
3193 || strcmp(lower, "latin_1") == 0
3194 || strcmp(lower, "iso_8859_1") == 0
3195 || strcmp(lower, "iso8859_1") == 0) {
3196 return PyUnicode_DecodeLatin1(s, size, errors);
3197 }
3198 }
Victor Stinner37296e82010-06-10 13:36:23 +00003199 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003200
3201 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003202 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003203 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003204 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003205 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003206 if (buffer == NULL)
3207 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003208 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003209 if (unicode == NULL)
3210 goto onError;
3211 if (!PyUnicode_Check(unicode)) {
3212 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003213 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3214 "use codecs.decode() to decode to arbitrary types",
3215 encoding,
3216 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003217 Py_DECREF(unicode);
3218 goto onError;
3219 }
3220 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003221 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003222
Benjamin Peterson29060642009-01-31 22:14:21 +00003223 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003224 Py_XDECREF(buffer);
3225 return NULL;
3226}
3227
Alexander Belopolsky40018472011-02-26 01:02:56 +00003228PyObject *
3229PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003230 const char *encoding,
3231 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003232{
3233 PyObject *v;
3234
3235 if (!PyUnicode_Check(unicode)) {
3236 PyErr_BadArgument();
3237 goto onError;
3238 }
3239
3240 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003241 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003242
3243 /* Decode via the codec registry */
3244 v = PyCodec_Decode(unicode, encoding, errors);
3245 if (v == NULL)
3246 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003247 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003248
Benjamin Peterson29060642009-01-31 22:14:21 +00003249 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003250 return NULL;
3251}
3252
Alexander Belopolsky40018472011-02-26 01:02:56 +00003253PyObject *
3254PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003255 const char *encoding,
3256 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003257{
3258 PyObject *v;
3259
3260 if (!PyUnicode_Check(unicode)) {
3261 PyErr_BadArgument();
3262 goto onError;
3263 }
3264
3265 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003266 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003267
3268 /* Decode via the codec registry */
3269 v = PyCodec_Decode(unicode, encoding, errors);
3270 if (v == NULL)
3271 goto onError;
3272 if (!PyUnicode_Check(v)) {
3273 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003274 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3275 "use codecs.decode() to decode to arbitrary types",
3276 encoding,
3277 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003278 Py_DECREF(v);
3279 goto onError;
3280 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003281 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003282
Benjamin Peterson29060642009-01-31 22:14:21 +00003283 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003284 return NULL;
3285}
3286
Alexander Belopolsky40018472011-02-26 01:02:56 +00003287PyObject *
3288PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003289 Py_ssize_t size,
3290 const char *encoding,
3291 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292{
3293 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003294
Guido van Rossumd57fd912000-03-10 22:53:23 +00003295 unicode = PyUnicode_FromUnicode(s, size);
3296 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003297 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003298 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3299 Py_DECREF(unicode);
3300 return v;
3301}
3302
Alexander Belopolsky40018472011-02-26 01:02:56 +00003303PyObject *
3304PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003305 const char *encoding,
3306 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003307{
3308 PyObject *v;
3309
3310 if (!PyUnicode_Check(unicode)) {
3311 PyErr_BadArgument();
3312 goto onError;
3313 }
3314
3315 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003316 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003317
3318 /* Encode via the codec registry */
3319 v = PyCodec_Encode(unicode, encoding, errors);
3320 if (v == NULL)
3321 goto onError;
3322 return v;
3323
Benjamin Peterson29060642009-01-31 22:14:21 +00003324 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003325 return NULL;
3326}
3327
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003328static size_t
3329wcstombs_errorpos(const wchar_t *wstr)
3330{
3331 size_t len;
3332#if SIZEOF_WCHAR_T == 2
3333 wchar_t buf[3];
3334#else
3335 wchar_t buf[2];
3336#endif
3337 char outbuf[MB_LEN_MAX];
3338 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003339
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003340#if SIZEOF_WCHAR_T == 2
3341 buf[2] = 0;
3342#else
3343 buf[1] = 0;
3344#endif
3345 start = wstr;
3346 while (*wstr != L'\0')
3347 {
3348 previous = wstr;
3349#if SIZEOF_WCHAR_T == 2
3350 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3351 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3352 {
3353 buf[0] = wstr[0];
3354 buf[1] = wstr[1];
3355 wstr += 2;
3356 }
3357 else {
3358 buf[0] = *wstr;
3359 buf[1] = 0;
3360 wstr++;
3361 }
3362#else
3363 buf[0] = *wstr;
3364 wstr++;
3365#endif
3366 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003367 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003368 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003369 }
3370
3371 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003372 return 0;
3373}
3374
Victor Stinner1b579672011-12-17 05:47:23 +01003375static int
3376locale_error_handler(const char *errors, int *surrogateescape)
3377{
Victor Stinner50149202015-09-22 00:26:54 +02003378 _Py_error_handler error_handler = get_error_handler(errors);
3379 switch (error_handler)
3380 {
3381 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003382 *surrogateescape = 0;
3383 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003384 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003385 *surrogateescape = 1;
3386 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003387 default:
3388 PyErr_Format(PyExc_ValueError,
3389 "only 'strict' and 'surrogateescape' error handlers "
3390 "are supported, not '%s'",
3391 errors);
3392 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003393 }
Victor Stinner1b579672011-12-17 05:47:23 +01003394}
3395
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003396PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003397PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003398{
3399 Py_ssize_t wlen, wlen2;
3400 wchar_t *wstr;
3401 PyObject *bytes = NULL;
3402 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003403 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003404 PyObject *exc;
3405 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003406 int surrogateescape;
3407
3408 if (locale_error_handler(errors, &surrogateescape) < 0)
3409 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003410
3411 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3412 if (wstr == NULL)
3413 return NULL;
3414
3415 wlen2 = wcslen(wstr);
3416 if (wlen2 != wlen) {
3417 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003418 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003419 return NULL;
3420 }
3421
3422 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003423 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003424 char *str;
3425
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003426 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003427 if (str == NULL) {
3428 if (error_pos == (size_t)-1) {
3429 PyErr_NoMemory();
3430 PyMem_Free(wstr);
3431 return NULL;
3432 }
3433 else {
3434 goto encode_error;
3435 }
3436 }
3437 PyMem_Free(wstr);
3438
3439 bytes = PyBytes_FromString(str);
3440 PyMem_Free(str);
3441 }
3442 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003443 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003444 size_t len, len2;
3445
3446 len = wcstombs(NULL, wstr, 0);
3447 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003448 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003449 goto encode_error;
3450 }
3451
3452 bytes = PyBytes_FromStringAndSize(NULL, len);
3453 if (bytes == NULL) {
3454 PyMem_Free(wstr);
3455 return NULL;
3456 }
3457
3458 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3459 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003460 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003461 goto encode_error;
3462 }
3463 PyMem_Free(wstr);
3464 }
3465 return bytes;
3466
3467encode_error:
3468 errmsg = strerror(errno);
3469 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003470
3471 if (error_pos == (size_t)-1)
3472 error_pos = wcstombs_errorpos(wstr);
3473
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003474 PyMem_Free(wstr);
3475 Py_XDECREF(bytes);
3476
Victor Stinner2f197072011-12-17 07:08:30 +01003477 if (errmsg != NULL) {
3478 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003479 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003480 if (wstr != NULL) {
3481 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003482 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003483 } else
3484 errmsg = NULL;
3485 }
3486 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003487 reason = PyUnicode_FromString(
3488 "wcstombs() encountered an unencodable "
3489 "wide character");
3490 if (reason == NULL)
3491 return NULL;
3492
3493 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3494 "locale", unicode,
3495 (Py_ssize_t)error_pos,
3496 (Py_ssize_t)(error_pos+1),
3497 reason);
3498 Py_DECREF(reason);
3499 if (exc != NULL) {
3500 PyCodec_StrictErrors(exc);
3501 Py_XDECREF(exc);
3502 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003503 return NULL;
3504}
3505
Victor Stinnerad158722010-10-27 00:25:46 +00003506PyObject *
3507PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003508{
Steve Dowercc16be82016-09-08 10:35:16 -07003509#if defined(__APPLE__)
3510 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003511#else
Victor Stinner793b5312011-04-27 00:24:21 +02003512 PyInterpreterState *interp = PyThreadState_GET()->interp;
3513 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3514 cannot use it to encode and decode filenames before it is loaded. Load
3515 the Python codec requires to encode at least its own filename. Use the C
3516 version of the locale codec until the codec registry is initialized and
3517 the Python codec is loaded.
3518
3519 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3520 cannot only rely on it: check also interp->fscodec_initialized for
3521 subinterpreters. */
3522 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003523 return PyUnicode_AsEncodedString(unicode,
3524 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003525 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003526 }
3527 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003528 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003529 }
Victor Stinnerad158722010-10-27 00:25:46 +00003530#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003531}
3532
Alexander Belopolsky40018472011-02-26 01:02:56 +00003533PyObject *
3534PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003535 const char *encoding,
3536 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003537{
3538 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003539 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003540
Guido van Rossumd57fd912000-03-10 22:53:23 +00003541 if (!PyUnicode_Check(unicode)) {
3542 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003543 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003544 }
Fred Drakee4315f52000-05-09 19:53:39 +00003545
Victor Stinner942889a2016-09-05 15:40:10 -07003546 if (encoding == NULL) {
3547 return _PyUnicode_AsUTF8String(unicode, errors);
3548 }
3549
Fred Drakee4315f52000-05-09 19:53:39 +00003550 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003551 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3552 char *lower = buflower;
3553
3554 /* Fast paths */
3555 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3556 lower += 3;
3557 if (*lower == '_') {
3558 /* Match "utf8" and "utf_8" */
3559 lower++;
3560 }
3561
3562 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003563 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003564 }
3565 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3566 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3567 }
3568 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3569 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3570 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003571 }
Victor Stinner942889a2016-09-05 15:40:10 -07003572 else {
3573 if (strcmp(lower, "ascii") == 0
3574 || strcmp(lower, "us_ascii") == 0) {
3575 return _PyUnicode_AsASCIIString(unicode, errors);
3576 }
Steve Dowercc16be82016-09-08 10:35:16 -07003577#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003578 else if (strcmp(lower, "mbcs") == 0) {
3579 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3580 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003581#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003582 else if (strcmp(lower, "latin1") == 0 ||
3583 strcmp(lower, "latin_1") == 0 ||
3584 strcmp(lower, "iso_8859_1") == 0 ||
3585 strcmp(lower, "iso8859_1") == 0) {
3586 return _PyUnicode_AsLatin1String(unicode, errors);
3587 }
3588 }
Victor Stinner37296e82010-06-10 13:36:23 +00003589 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003590
3591 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003592 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003593 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003594 return NULL;
3595
3596 /* The normal path */
3597 if (PyBytes_Check(v))
3598 return v;
3599
3600 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003601 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003602 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003603 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003604
3605 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003606 "encoder %s returned bytearray instead of bytes; "
3607 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003608 encoding);
3609 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003610 Py_DECREF(v);
3611 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003612 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003613
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003614 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3615 Py_DECREF(v);
3616 return b;
3617 }
3618
3619 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003620 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3621 "use codecs.encode() to encode to arbitrary types",
3622 encoding,
3623 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003624 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003625 return NULL;
3626}
3627
Alexander Belopolsky40018472011-02-26 01:02:56 +00003628PyObject *
3629PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003630 const char *encoding,
3631 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003632{
3633 PyObject *v;
3634
3635 if (!PyUnicode_Check(unicode)) {
3636 PyErr_BadArgument();
3637 goto onError;
3638 }
3639
3640 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003641 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003642
3643 /* Encode via the codec registry */
3644 v = PyCodec_Encode(unicode, encoding, errors);
3645 if (v == NULL)
3646 goto onError;
3647 if (!PyUnicode_Check(v)) {
3648 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003649 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3650 "use codecs.encode() to encode to arbitrary types",
3651 encoding,
3652 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003653 Py_DECREF(v);
3654 goto onError;
3655 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003656 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003657
Benjamin Peterson29060642009-01-31 22:14:21 +00003658 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003659 return NULL;
3660}
3661
Victor Stinner2f197072011-12-17 07:08:30 +01003662static size_t
3663mbstowcs_errorpos(const char *str, size_t len)
3664{
3665#ifdef HAVE_MBRTOWC
3666 const char *start = str;
3667 mbstate_t mbs;
3668 size_t converted;
3669 wchar_t ch;
3670
3671 memset(&mbs, 0, sizeof mbs);
3672 while (len)
3673 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003674 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003675 if (converted == 0)
3676 /* Reached end of string */
3677 break;
3678 if (converted == (size_t)-1 || converted == (size_t)-2) {
3679 /* Conversion error or incomplete character */
3680 return str - start;
3681 }
3682 else {
3683 str += converted;
3684 len -= converted;
3685 }
3686 }
3687 /* failed to find the undecodable byte sequence */
3688 return 0;
3689#endif
3690 return 0;
3691}
3692
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003693PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003694PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003695 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003696{
3697 wchar_t smallbuf[256];
3698 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3699 wchar_t *wstr;
3700 size_t wlen, wlen2;
3701 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003702 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003703 size_t error_pos;
3704 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003705 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3706 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003707
3708 if (locale_error_handler(errors, &surrogateescape) < 0)
3709 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003710
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003711 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3712 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003713 return NULL;
3714 }
3715
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003716 if (surrogateescape) {
3717 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003718 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003719 if (wstr == NULL) {
3720 if (wlen == (size_t)-1)
3721 PyErr_NoMemory();
3722 else
3723 PyErr_SetFromErrno(PyExc_OSError);
3724 return NULL;
3725 }
3726
3727 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003728 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003729 }
3730 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003731 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003732#ifndef HAVE_BROKEN_MBSTOWCS
3733 wlen = mbstowcs(NULL, str, 0);
3734#else
3735 wlen = len;
3736#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003737 if (wlen == (size_t)-1)
3738 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003739 if (wlen+1 <= smallbuf_len) {
3740 wstr = smallbuf;
3741 }
3742 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003743 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003744 if (!wstr)
3745 return PyErr_NoMemory();
3746 }
3747
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003748 wlen2 = mbstowcs(wstr, str, wlen+1);
3749 if (wlen2 == (size_t)-1) {
3750 if (wstr != smallbuf)
3751 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003752 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003753 }
3754#ifdef HAVE_BROKEN_MBSTOWCS
3755 assert(wlen2 == wlen);
3756#endif
3757 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3758 if (wstr != smallbuf)
3759 PyMem_Free(wstr);
3760 }
3761 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003762
3763decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003764 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003765 errmsg = strerror(errno);
3766 assert(errmsg != NULL);
3767
3768 error_pos = mbstowcs_errorpos(str, len);
3769 if (errmsg != NULL) {
3770 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003771 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003772 if (wstr != NULL) {
3773 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003774 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003775 }
Victor Stinner2f197072011-12-17 07:08:30 +01003776 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003777 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003778 reason = PyUnicode_FromString(
3779 "mbstowcs() encountered an invalid multibyte sequence");
3780 if (reason == NULL)
3781 return NULL;
3782
3783 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3784 "locale", str, len,
3785 (Py_ssize_t)error_pos,
3786 (Py_ssize_t)(error_pos+1),
3787 reason);
3788 Py_DECREF(reason);
3789 if (exc != NULL) {
3790 PyCodec_StrictErrors(exc);
3791 Py_XDECREF(exc);
3792 }
3793 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003794}
3795
3796PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003797PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003798{
3799 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003800 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003801}
3802
3803
3804PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003805PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003806 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003807 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3808}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003809
Christian Heimes5894ba72007-11-04 11:43:14 +00003810PyObject*
3811PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3812{
Steve Dowercc16be82016-09-08 10:35:16 -07003813#if defined(__APPLE__)
3814 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003815#else
Victor Stinner793b5312011-04-27 00:24:21 +02003816 PyInterpreterState *interp = PyThreadState_GET()->interp;
3817 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3818 cannot use it to encode and decode filenames before it is loaded. Load
3819 the Python codec requires to encode at least its own filename. Use the C
3820 version of the locale codec until the codec registry is initialized and
3821 the Python codec is loaded.
3822
3823 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3824 cannot only rely on it: check also interp->fscodec_initialized for
3825 subinterpreters. */
3826 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dowercc16be82016-09-08 10:35:16 -07003827 PyObject *res = PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003828 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003829 Py_FileSystemDefaultEncodeErrors);
3830#ifdef MS_WINDOWS
3831 if (!res && PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
3832 PyObject *exc, *val, *tb;
3833 PyErr_Fetch(&exc, &val, &tb);
3834 PyErr_Format(PyExc_RuntimeError,
3835 "filesystem path bytes were not correctly encoded with '%s'. " \
3836 "Please report this at http://bugs.python.org/issue27781",
3837 Py_FileSystemDefaultEncoding);
3838 _PyErr_ChainExceptions(exc, val, tb);
3839 }
3840#endif
3841 return res;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003842 }
3843 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003844 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003845 }
Victor Stinnerad158722010-10-27 00:25:46 +00003846#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003847}
3848
Martin v. Löwis011e8422009-05-05 04:43:17 +00003849
3850int
3851PyUnicode_FSConverter(PyObject* arg, void* addr)
3852{
Brett Cannonec6ce872016-09-06 15:50:29 -07003853 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003854 PyObject *output = NULL;
3855 Py_ssize_t size;
3856 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003857 if (arg == NULL) {
3858 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003859 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003860 return 1;
3861 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003862 path = PyOS_FSPath(arg);
3863 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003864 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003865 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003866 if (PyBytes_Check(path)) {
3867 output = path;
3868 }
3869 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3870 output = PyUnicode_EncodeFSDefault(path);
3871 Py_DECREF(path);
3872 if (!output) {
3873 return 0;
3874 }
3875 assert(PyBytes_Check(output));
3876 }
3877
Victor Stinner0ea2a462010-04-30 00:22:08 +00003878 size = PyBytes_GET_SIZE(output);
3879 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003880 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003881 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003882 Py_DECREF(output);
3883 return 0;
3884 }
3885 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003886 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003887}
3888
3889
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003890int
3891PyUnicode_FSDecoder(PyObject* arg, void* addr)
3892{
Brett Cannona5711202016-09-06 19:36:01 -07003893 int is_buffer = 0;
3894 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003895 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003896 if (arg == NULL) {
3897 Py_DECREF(*(PyObject**)addr);
3898 return 1;
3899 }
Brett Cannona5711202016-09-06 19:36:01 -07003900
3901 is_buffer = PyObject_CheckBuffer(arg);
3902 if (!is_buffer) {
3903 path = PyOS_FSPath(arg);
3904 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003905 return 0;
3906 }
Brett Cannona5711202016-09-06 19:36:01 -07003907 }
3908 else {
3909 path = arg;
3910 Py_INCREF(arg);
3911 }
3912
3913 if (PyUnicode_Check(path)) {
3914 if (PyUnicode_READY(path) == -1) {
3915 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003916 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003917 }
3918 output = path;
3919 }
3920 else if (PyBytes_Check(path) || is_buffer) {
3921 PyObject *path_bytes = NULL;
3922
3923 if (!PyBytes_Check(path) &&
3924 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3925 "path should be string, bytes, or os.PathLike, not %.200s",
3926 Py_TYPE(arg)->tp_name)) {
3927 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003928 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003929 }
3930 path_bytes = PyBytes_FromObject(path);
3931 Py_DECREF(path);
3932 if (!path_bytes) {
3933 return 0;
3934 }
3935 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3936 PyBytes_GET_SIZE(path_bytes));
3937 Py_DECREF(path_bytes);
3938 if (!output) {
3939 return 0;
3940 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003941 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003942 else {
3943 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003944 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003945 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003946 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003947 return 0;
3948 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003949 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003950 Py_DECREF(output);
3951 return 0;
3952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003953 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003954 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003955 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003956 Py_DECREF(output);
3957 return 0;
3958 }
3959 *(PyObject**)addr = output;
3960 return Py_CLEANUP_SUPPORTED;
3961}
3962
3963
Martin v. Löwis5b222132007-06-10 09:51:05 +00003964char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003965PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003966{
Christian Heimesf3863112007-11-22 07:46:41 +00003967 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003968
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003969 if (!PyUnicode_Check(unicode)) {
3970 PyErr_BadArgument();
3971 return NULL;
3972 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003973 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003974 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003975
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003976 if (PyUnicode_UTF8(unicode) == NULL) {
3977 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003978 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003979 if (bytes == NULL)
3980 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003981 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3982 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003983 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003984 Py_DECREF(bytes);
3985 return NULL;
3986 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003987 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003988 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003989 PyBytes_AS_STRING(bytes),
3990 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003991 Py_DECREF(bytes);
3992 }
3993
3994 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003995 *psize = PyUnicode_UTF8_LENGTH(unicode);
3996 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003997}
3998
3999char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004000PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004001{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004002 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4003}
4004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004005Py_UNICODE *
4006PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4007{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004008 const unsigned char *one_byte;
4009#if SIZEOF_WCHAR_T == 4
4010 const Py_UCS2 *two_bytes;
4011#else
4012 const Py_UCS4 *four_bytes;
4013 const Py_UCS4 *ucs4_end;
4014 Py_ssize_t num_surrogates;
4015#endif
4016 wchar_t *w;
4017 wchar_t *wchar_end;
4018
4019 if (!PyUnicode_Check(unicode)) {
4020 PyErr_BadArgument();
4021 return NULL;
4022 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004023 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004025 assert(_PyUnicode_KIND(unicode) != 0);
4026 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004027
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004028 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004029#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004030 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4031 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004032 num_surrogates = 0;
4033
4034 for (; four_bytes < ucs4_end; ++four_bytes) {
4035 if (*four_bytes > 0xFFFF)
4036 ++num_surrogates;
4037 }
4038
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004039 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4040 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4041 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004042 PyErr_NoMemory();
4043 return NULL;
4044 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004045 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004046
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004047 w = _PyUnicode_WSTR(unicode);
4048 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4049 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004050 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4051 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004052 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004053 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004054 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4055 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004056 }
4057 else
4058 *w = *four_bytes;
4059
4060 if (w > wchar_end) {
4061 assert(0 && "Miscalculated string end");
4062 }
4063 }
4064 *w = 0;
4065#else
4066 /* sizeof(wchar_t) == 4 */
4067 Py_FatalError("Impossible unicode object state, wstr and str "
4068 "should share memory already.");
4069 return NULL;
4070#endif
4071 }
4072 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004073 if ((size_t)_PyUnicode_LENGTH(unicode) >
4074 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4075 PyErr_NoMemory();
4076 return NULL;
4077 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004078 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4079 (_PyUnicode_LENGTH(unicode) + 1));
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 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4085 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4086 w = _PyUnicode_WSTR(unicode);
4087 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004088
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004089 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4090 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004091 for (; w < wchar_end; ++one_byte, ++w)
4092 *w = *one_byte;
4093 /* null-terminate the wstr */
4094 *w = 0;
4095 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004096 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004097#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004098 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004099 for (; w < wchar_end; ++two_bytes, ++w)
4100 *w = *two_bytes;
4101 /* null-terminate the wstr */
4102 *w = 0;
4103#else
4104 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004105 PyObject_FREE(_PyUnicode_WSTR(unicode));
4106 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004107 Py_FatalError("Impossible unicode object state, wstr "
4108 "and str should share memory already.");
4109 return NULL;
4110#endif
4111 }
4112 else {
4113 assert(0 && "This should never happen.");
4114 }
4115 }
4116 }
4117 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004118 *size = PyUnicode_WSTR_LENGTH(unicode);
4119 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004120}
4121
Alexander Belopolsky40018472011-02-26 01:02:56 +00004122Py_UNICODE *
4123PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004124{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004125 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004126}
4127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004128
Alexander Belopolsky40018472011-02-26 01:02:56 +00004129Py_ssize_t
4130PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004131{
4132 if (!PyUnicode_Check(unicode)) {
4133 PyErr_BadArgument();
4134 goto onError;
4135 }
4136 return PyUnicode_GET_SIZE(unicode);
4137
Benjamin Peterson29060642009-01-31 22:14:21 +00004138 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004139 return -1;
4140}
4141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004142Py_ssize_t
4143PyUnicode_GetLength(PyObject *unicode)
4144{
Victor Stinner07621332012-06-16 04:53:46 +02004145 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004146 PyErr_BadArgument();
4147 return -1;
4148 }
Victor Stinner07621332012-06-16 04:53:46 +02004149 if (PyUnicode_READY(unicode) == -1)
4150 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004151 return PyUnicode_GET_LENGTH(unicode);
4152}
4153
4154Py_UCS4
4155PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4156{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004157 void *data;
4158 int kind;
4159
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004160 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4161 PyErr_BadArgument();
4162 return (Py_UCS4)-1;
4163 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004164 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004165 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004166 return (Py_UCS4)-1;
4167 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004168 data = PyUnicode_DATA(unicode);
4169 kind = PyUnicode_KIND(unicode);
4170 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004171}
4172
4173int
4174PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4175{
4176 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004177 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004178 return -1;
4179 }
Victor Stinner488fa492011-12-12 00:01:39 +01004180 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004181 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004182 PyErr_SetString(PyExc_IndexError, "string index out of range");
4183 return -1;
4184 }
Victor Stinner488fa492011-12-12 00:01:39 +01004185 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004186 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004187 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4188 PyErr_SetString(PyExc_ValueError, "character out of range");
4189 return -1;
4190 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004191 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4192 index, ch);
4193 return 0;
4194}
4195
Alexander Belopolsky40018472011-02-26 01:02:56 +00004196const char *
4197PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004198{
Victor Stinner42cb4622010-09-01 19:39:01 +00004199 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004200}
4201
Victor Stinner554f3f02010-06-16 23:33:54 +00004202/* create or adjust a UnicodeDecodeError */
4203static void
4204make_decode_exception(PyObject **exceptionObject,
4205 const char *encoding,
4206 const char *input, Py_ssize_t length,
4207 Py_ssize_t startpos, Py_ssize_t endpos,
4208 const char *reason)
4209{
4210 if (*exceptionObject == NULL) {
4211 *exceptionObject = PyUnicodeDecodeError_Create(
4212 encoding, input, length, startpos, endpos, reason);
4213 }
4214 else {
4215 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4216 goto onError;
4217 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4218 goto onError;
4219 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4220 goto onError;
4221 }
4222 return;
4223
4224onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004225 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004226}
4227
Steve Dowercc16be82016-09-08 10:35:16 -07004228#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004229/* error handling callback helper:
4230 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004231 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004232 and adjust various state variables.
4233 return 0 on success, -1 on error
4234*/
4235
Alexander Belopolsky40018472011-02-26 01:02:56 +00004236static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004237unicode_decode_call_errorhandler_wchar(
4238 const char *errors, PyObject **errorHandler,
4239 const char *encoding, const char *reason,
4240 const char **input, const char **inend, Py_ssize_t *startinpos,
4241 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4242 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004243{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004244 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004245
4246 PyObject *restuple = NULL;
4247 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004248 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004249 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004250 Py_ssize_t requiredsize;
4251 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004252 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004253 wchar_t *repwstr;
4254 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004255
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004256 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4257 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004258
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004259 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004260 *errorHandler = PyCodec_LookupError(errors);
4261 if (*errorHandler == NULL)
4262 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004263 }
4264
Victor Stinner554f3f02010-06-16 23:33:54 +00004265 make_decode_exception(exceptionObject,
4266 encoding,
4267 *input, *inend - *input,
4268 *startinpos, *endinpos,
4269 reason);
4270 if (*exceptionObject == NULL)
4271 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004272
4273 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4274 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004275 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004276 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004277 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004278 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004279 }
4280 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004281 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004282
4283 /* Copy back the bytes variables, which might have been modified by the
4284 callback */
4285 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4286 if (!inputobj)
4287 goto onError;
4288 if (!PyBytes_Check(inputobj)) {
4289 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4290 }
4291 *input = PyBytes_AS_STRING(inputobj);
4292 insize = PyBytes_GET_SIZE(inputobj);
4293 *inend = *input + insize;
4294 /* we can DECREF safely, as the exception has another reference,
4295 so the object won't go away. */
4296 Py_DECREF(inputobj);
4297
4298 if (newpos<0)
4299 newpos = insize+newpos;
4300 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004301 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004302 goto onError;
4303 }
4304
4305 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4306 if (repwstr == NULL)
4307 goto onError;
4308 /* need more space? (at least enough for what we
4309 have+the replacement+the rest of the string (starting
4310 at the new input position), so we won't have to check space
4311 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004312 requiredsize = *outpos;
4313 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4314 goto overflow;
4315 requiredsize += repwlen;
4316 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4317 goto overflow;
4318 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004319 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004320 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004321 requiredsize = 2*outsize;
4322 if (unicode_resize(output, requiredsize) < 0)
4323 goto onError;
4324 }
4325 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4326 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004327 *endinpos = newpos;
4328 *inptr = *input + newpos;
4329
4330 /* we made it! */
4331 Py_XDECREF(restuple);
4332 return 0;
4333
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004334 overflow:
4335 PyErr_SetString(PyExc_OverflowError,
4336 "decoded result is too long for a Python string");
4337
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004338 onError:
4339 Py_XDECREF(restuple);
4340 return -1;
4341}
Steve Dowercc16be82016-09-08 10:35:16 -07004342#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004343
4344static int
4345unicode_decode_call_errorhandler_writer(
4346 const char *errors, PyObject **errorHandler,
4347 const char *encoding, const char *reason,
4348 const char **input, const char **inend, Py_ssize_t *startinpos,
4349 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4350 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4351{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004352 static const char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004353
4354 PyObject *restuple = NULL;
4355 PyObject *repunicode = NULL;
4356 Py_ssize_t insize;
4357 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004358 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004359 PyObject *inputobj = NULL;
4360
4361 if (*errorHandler == NULL) {
4362 *errorHandler = PyCodec_LookupError(errors);
4363 if (*errorHandler == NULL)
4364 goto onError;
4365 }
4366
4367 make_decode_exception(exceptionObject,
4368 encoding,
4369 *input, *inend - *input,
4370 *startinpos, *endinpos,
4371 reason);
4372 if (*exceptionObject == NULL)
4373 goto onError;
4374
4375 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4376 if (restuple == NULL)
4377 goto onError;
4378 if (!PyTuple_Check(restuple)) {
4379 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4380 goto onError;
4381 }
4382 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004383 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004384
4385 /* Copy back the bytes variables, which might have been modified by the
4386 callback */
4387 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4388 if (!inputobj)
4389 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004390 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004391 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004392 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004393 *input = PyBytes_AS_STRING(inputobj);
4394 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004395 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004396 /* we can DECREF safely, as the exception has another reference,
4397 so the object won't go away. */
4398 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004399
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004400 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004401 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004402 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004403 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004404 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004405 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004406
Victor Stinner8f674cc2013-04-17 23:02:17 +02004407 if (PyUnicode_READY(repunicode) < 0)
4408 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004409 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004410 if (replen > 1) {
4411 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004412 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004413 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4414 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4415 goto onError;
4416 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004417 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004418 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004419
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004420 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004421 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004422
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004423 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004424 Py_XDECREF(restuple);
4425 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004426
Benjamin Peterson29060642009-01-31 22:14:21 +00004427 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004428 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004429 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004430}
4431
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004432/* --- UTF-7 Codec -------------------------------------------------------- */
4433
Antoine Pitrou244651a2009-05-04 18:56:13 +00004434/* See RFC2152 for details. We encode conservatively and decode liberally. */
4435
4436/* Three simple macros defining base-64. */
4437
4438/* Is c a base-64 character? */
4439
4440#define IS_BASE64(c) \
4441 (((c) >= 'A' && (c) <= 'Z') || \
4442 ((c) >= 'a' && (c) <= 'z') || \
4443 ((c) >= '0' && (c) <= '9') || \
4444 (c) == '+' || (c) == '/')
4445
4446/* given that c is a base-64 character, what is its base-64 value? */
4447
4448#define FROM_BASE64(c) \
4449 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4450 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4451 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4452 (c) == '+' ? 62 : 63)
4453
4454/* What is the base-64 character of the bottom 6 bits of n? */
4455
4456#define TO_BASE64(n) \
4457 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4458
4459/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4460 * decoded as itself. We are permissive on decoding; the only ASCII
4461 * byte not decoding to itself is the + which begins a base64
4462 * string. */
4463
4464#define DECODE_DIRECT(c) \
4465 ((c) <= 127 && (c) != '+')
4466
4467/* The UTF-7 encoder treats ASCII characters differently according to
4468 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4469 * the above). See RFC2152. This array identifies these different
4470 * sets:
4471 * 0 : "Set D"
4472 * alphanumeric and '(),-./:?
4473 * 1 : "Set O"
4474 * !"#$%&*;<=>@[]^_`{|}
4475 * 2 : "whitespace"
4476 * ht nl cr sp
4477 * 3 : special (must be base64 encoded)
4478 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4479 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004480
Tim Petersced69f82003-09-16 20:30:58 +00004481static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004482char utf7_category[128] = {
4483/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4484 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4485/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4486 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4487/* sp ! " # $ % & ' ( ) * + , - . / */
4488 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4489/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4490 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4491/* @ A B C D E F G H I J K L M N O */
4492 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4493/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4494 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4495/* ` a b c d e f g h i j k l m n o */
4496 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4497/* p q r s t u v w x y z { | } ~ del */
4498 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499};
4500
Antoine Pitrou244651a2009-05-04 18:56:13 +00004501/* ENCODE_DIRECT: this character should be encoded as itself. The
4502 * answer depends on whether we are encoding set O as itself, and also
4503 * on whether we are encoding whitespace as itself. RFC2152 makes it
4504 * clear that the answers to these questions vary between
4505 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004506
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507#define ENCODE_DIRECT(c, directO, directWS) \
4508 ((c) < 128 && (c) > 0 && \
4509 ((utf7_category[(c)] == 0) || \
4510 (directWS && (utf7_category[(c)] == 2)) || \
4511 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004512
Alexander Belopolsky40018472011-02-26 01:02:56 +00004513PyObject *
4514PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004515 Py_ssize_t size,
4516 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004517{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004518 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4519}
4520
Antoine Pitrou244651a2009-05-04 18:56:13 +00004521/* The decoder. The only state we preserve is our read position,
4522 * i.e. how many characters we have consumed. So if we end in the
4523 * middle of a shift sequence we have to back off the read position
4524 * and the output to the beginning of the sequence, otherwise we lose
4525 * all the shift state (seen bits, number of bits seen, high
4526 * surrogate). */
4527
Alexander Belopolsky40018472011-02-26 01:02:56 +00004528PyObject *
4529PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004530 Py_ssize_t size,
4531 const char *errors,
4532 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004533{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004534 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004535 Py_ssize_t startinpos;
4536 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004537 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004538 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004539 const char *errmsg = "";
4540 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004541 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004542 unsigned int base64bits = 0;
4543 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004544 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004545 PyObject *errorHandler = NULL;
4546 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004547
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004548 if (size == 0) {
4549 if (consumed)
4550 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004551 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004552 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004553
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004554 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004555 _PyUnicodeWriter_Init(&writer);
4556 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004557
4558 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004559 e = s + size;
4560
4561 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004562 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004563 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004564 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004565
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566 if (inShift) { /* in a base-64 section */
4567 if (IS_BASE64(ch)) { /* consume a base-64 character */
4568 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4569 base64bits += 6;
4570 s++;
4571 if (base64bits >= 16) {
4572 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004573 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 base64bits -= 16;
4575 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004576 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 if (surrogate) {
4578 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004579 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4580 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004581 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004582 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004583 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004584 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004585 }
4586 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004587 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004588 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004589 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004590 }
4591 }
Victor Stinner551ac952011-11-29 22:58:13 +01004592 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593 /* first surrogate */
4594 surrogate = outCh;
4595 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004597 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004598 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004599 }
4600 }
4601 }
4602 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004603 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004604 if (base64bits > 0) { /* left-over bits */
4605 if (base64bits >= 6) {
4606 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004607 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004608 errmsg = "partial character in shift sequence";
4609 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004610 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004611 else {
4612 /* Some bits remain; they should be zero */
4613 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004614 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004615 errmsg = "non-zero padding bits in shift sequence";
4616 goto utf7Error;
4617 }
4618 }
4619 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004620 if (surrogate && DECODE_DIRECT(ch)) {
4621 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4622 goto onError;
4623 }
4624 surrogate = 0;
4625 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004626 /* '-' is absorbed; other terminating
4627 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004628 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004629 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004630 }
4631 }
4632 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004633 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004634 s++; /* consume '+' */
4635 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004636 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004637 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004638 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004639 }
4640 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004641 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004642 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004643 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004644 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004645 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004646 }
4647 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004648 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004649 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004650 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004651 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004652 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004653 else {
4654 startinpos = s-starts;
4655 s++;
4656 errmsg = "unexpected special character";
4657 goto utf7Error;
4658 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004659 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004660utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004661 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004662 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004663 errors, &errorHandler,
4664 "utf7", errmsg,
4665 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004666 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004667 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004668 }
4669
Antoine Pitrou244651a2009-05-04 18:56:13 +00004670 /* end of string */
4671
4672 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4673 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004674 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004675 if (surrogate ||
4676 (base64bits >= 6) ||
4677 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004678 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004679 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004680 errors, &errorHandler,
4681 "utf7", "unterminated shift sequence",
4682 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004683 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004684 goto onError;
4685 if (s < e)
4686 goto restart;
4687 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004688 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004689
4690 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004691 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004692 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004693 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004694 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004695 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004696 writer.kind, writer.data, shiftOutStart);
4697 Py_XDECREF(errorHandler);
4698 Py_XDECREF(exc);
4699 _PyUnicodeWriter_Dealloc(&writer);
4700 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004701 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004702 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004703 }
4704 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004705 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004706 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004707 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004708
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004709 Py_XDECREF(errorHandler);
4710 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004711 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004712
Benjamin Peterson29060642009-01-31 22:14:21 +00004713 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004714 Py_XDECREF(errorHandler);
4715 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004716 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004717 return NULL;
4718}
4719
4720
Alexander Belopolsky40018472011-02-26 01:02:56 +00004721PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004722_PyUnicode_EncodeUTF7(PyObject *str,
4723 int base64SetO,
4724 int base64WhiteSpace,
4725 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004726{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004727 int kind;
4728 void *data;
4729 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004730 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004731 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004732 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004733 unsigned int base64bits = 0;
4734 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004735 char * out;
4736 char * start;
4737
Benjamin Petersonbac79492012-01-14 13:34:47 -05004738 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004739 return NULL;
4740 kind = PyUnicode_KIND(str);
4741 data = PyUnicode_DATA(str);
4742 len = PyUnicode_GET_LENGTH(str);
4743
4744 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004745 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004746
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004747 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004748 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004749 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004750 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004751 if (v == NULL)
4752 return NULL;
4753
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004754 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004755 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004756 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004757
Antoine Pitrou244651a2009-05-04 18:56:13 +00004758 if (inShift) {
4759 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4760 /* shifting out */
4761 if (base64bits) { /* output remaining bits */
4762 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4763 base64buffer = 0;
4764 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004765 }
4766 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004767 /* Characters not in the BASE64 set implicitly unshift the sequence
4768 so no '-' is required, except if the character is itself a '-' */
4769 if (IS_BASE64(ch) || ch == '-') {
4770 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004771 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004772 *out++ = (char) ch;
4773 }
4774 else {
4775 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004776 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004777 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004778 else { /* not in a shift sequence */
4779 if (ch == '+') {
4780 *out++ = '+';
4781 *out++ = '-';
4782 }
4783 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4784 *out++ = (char) ch;
4785 }
4786 else {
4787 *out++ = '+';
4788 inShift = 1;
4789 goto encode_char;
4790 }
4791 }
4792 continue;
4793encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004794 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004795 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004796
Antoine Pitrou244651a2009-05-04 18:56:13 +00004797 /* code first surrogate */
4798 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004799 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004800 while (base64bits >= 6) {
4801 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4802 base64bits -= 6;
4803 }
4804 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004805 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004806 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004807 base64bits += 16;
4808 base64buffer = (base64buffer << 16) | ch;
4809 while (base64bits >= 6) {
4810 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4811 base64bits -= 6;
4812 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004813 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004814 if (base64bits)
4815 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4816 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004817 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004818 if (_PyBytes_Resize(&v, out - start) < 0)
4819 return NULL;
4820 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004821}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004822PyObject *
4823PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4824 Py_ssize_t size,
4825 int base64SetO,
4826 int base64WhiteSpace,
4827 const char *errors)
4828{
4829 PyObject *result;
4830 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4831 if (tmp == NULL)
4832 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004833 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004834 base64WhiteSpace, errors);
4835 Py_DECREF(tmp);
4836 return result;
4837}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004838
Antoine Pitrou244651a2009-05-04 18:56:13 +00004839#undef IS_BASE64
4840#undef FROM_BASE64
4841#undef TO_BASE64
4842#undef DECODE_DIRECT
4843#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004844
Guido van Rossumd57fd912000-03-10 22:53:23 +00004845/* --- UTF-8 Codec -------------------------------------------------------- */
4846
Alexander Belopolsky40018472011-02-26 01:02:56 +00004847PyObject *
4848PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004849 Py_ssize_t size,
4850 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004851{
Walter Dörwald69652032004-09-07 20:24:22 +00004852 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4853}
4854
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004855#include "stringlib/asciilib.h"
4856#include "stringlib/codecs.h"
4857#include "stringlib/undef.h"
4858
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004859#include "stringlib/ucs1lib.h"
4860#include "stringlib/codecs.h"
4861#include "stringlib/undef.h"
4862
4863#include "stringlib/ucs2lib.h"
4864#include "stringlib/codecs.h"
4865#include "stringlib/undef.h"
4866
4867#include "stringlib/ucs4lib.h"
4868#include "stringlib/codecs.h"
4869#include "stringlib/undef.h"
4870
Antoine Pitrouab868312009-01-10 15:40:25 +00004871/* Mask to quickly check whether a C 'long' contains a
4872 non-ASCII, UTF8-encoded char. */
4873#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004874# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004875#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004876# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004877#else
4878# error C 'long' size should be either 4 or 8!
4879#endif
4880
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004881static Py_ssize_t
4882ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004883{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004884 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004885 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004886
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004887 /*
4888 * Issue #17237: m68k is a bit different from most architectures in
4889 * that objects do not use "natural alignment" - for example, int and
4890 * long are only aligned at 2-byte boundaries. Therefore the assert()
4891 * won't work; also, tests have shown that skipping the "optimised
4892 * version" will even speed up m68k.
4893 */
4894#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004895#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004896 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4897 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004898 /* Fast path, see in STRINGLIB(utf8_decode) for
4899 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004900 /* Help allocation */
4901 const char *_p = p;
4902 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004903 while (_p < aligned_end) {
4904 unsigned long value = *(const unsigned long *) _p;
4905 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004906 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004907 *((unsigned long *)q) = value;
4908 _p += SIZEOF_LONG;
4909 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004910 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004911 p = _p;
4912 while (p < end) {
4913 if ((unsigned char)*p & 0x80)
4914 break;
4915 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004916 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004917 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004918 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004919#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004920#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004921 while (p < end) {
4922 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4923 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004924 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004925 /* Help allocation */
4926 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004927 while (_p < aligned_end) {
4928 unsigned long value = *(unsigned long *) _p;
4929 if (value & ASCII_CHAR_MASK)
4930 break;
4931 _p += SIZEOF_LONG;
4932 }
4933 p = _p;
4934 if (_p == end)
4935 break;
4936 }
4937 if ((unsigned char)*p & 0x80)
4938 break;
4939 ++p;
4940 }
4941 memcpy(dest, start, p - start);
4942 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004943}
Antoine Pitrouab868312009-01-10 15:40:25 +00004944
Victor Stinner785938e2011-12-11 20:09:03 +01004945PyObject *
4946PyUnicode_DecodeUTF8Stateful(const char *s,
4947 Py_ssize_t size,
4948 const char *errors,
4949 Py_ssize_t *consumed)
4950{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004951 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004952 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004953 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004954
4955 Py_ssize_t startinpos;
4956 Py_ssize_t endinpos;
4957 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004958 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004959 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004960 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004961
4962 if (size == 0) {
4963 if (consumed)
4964 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004965 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004966 }
4967
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004968 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4969 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004970 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004971 *consumed = 1;
4972 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004973 }
4974
Victor Stinner8f674cc2013-04-17 23:02:17 +02004975 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004976 writer.min_length = size;
4977 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004978 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004979
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004980 writer.pos = ascii_decode(s, end, writer.data);
4981 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004982 while (s < end) {
4983 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004984 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004985
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004986 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004987 if (PyUnicode_IS_ASCII(writer.buffer))
4988 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004989 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004990 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004991 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004992 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004993 } else {
4994 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004995 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004996 }
4997
4998 switch (ch) {
4999 case 0:
5000 if (s == end || consumed)
5001 goto End;
5002 errmsg = "unexpected end of data";
5003 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005004 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005005 break;
5006 case 1:
5007 errmsg = "invalid start byte";
5008 startinpos = s - starts;
5009 endinpos = startinpos + 1;
5010 break;
5011 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005012 case 3:
5013 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005014 errmsg = "invalid continuation byte";
5015 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005016 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005017 break;
5018 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005019 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005020 goto onError;
5021 continue;
5022 }
5023
Victor Stinner1d65d912015-10-05 13:43:50 +02005024 if (error_handler == _Py_ERROR_UNKNOWN)
5025 error_handler = get_error_handler(errors);
5026
5027 switch (error_handler) {
5028 case _Py_ERROR_IGNORE:
5029 s += (endinpos - startinpos);
5030 break;
5031
5032 case _Py_ERROR_REPLACE:
5033 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5034 goto onError;
5035 s += (endinpos - startinpos);
5036 break;
5037
5038 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005039 {
5040 Py_ssize_t i;
5041
Victor Stinner1d65d912015-10-05 13:43:50 +02005042 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5043 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005044 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005045 ch = (Py_UCS4)(unsigned char)(starts[i]);
5046 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5047 ch + 0xdc00);
5048 writer.pos++;
5049 }
5050 s += (endinpos - startinpos);
5051 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005052 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005053
5054 default:
5055 if (unicode_decode_call_errorhandler_writer(
5056 errors, &error_handler_obj,
5057 "utf-8", errmsg,
5058 &starts, &end, &startinpos, &endinpos, &exc, &s,
5059 &writer))
5060 goto onError;
5061 }
Victor Stinner785938e2011-12-11 20:09:03 +01005062 }
5063
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005064End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005065 if (consumed)
5066 *consumed = s - starts;
5067
Victor Stinner1d65d912015-10-05 13:43:50 +02005068 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005069 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005070 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005071
5072onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005073 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005074 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005075 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005076 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005077}
5078
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005079#ifdef __APPLE__
5080
5081/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005082 used to decode the command line arguments on Mac OS X.
5083
5084 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005085 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005086
5087wchar_t*
5088_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5089{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005090 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005091 wchar_t *unicode;
5092 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005093
5094 /* Note: size will always be longer than the resulting Unicode
5095 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005096 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005097 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005098 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005099 if (!unicode)
5100 return NULL;
5101
5102 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005103 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005104 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005105 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005106 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005107#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005108 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005109#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005110 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005111#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005112 if (ch > 0xFF) {
5113#if SIZEOF_WCHAR_T == 4
5114 assert(0);
5115#else
5116 assert(Py_UNICODE_IS_SURROGATE(ch));
5117 /* compute and append the two surrogates: */
5118 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5119 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5120#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005121 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005122 else {
5123 if (!ch && s == e)
5124 break;
5125 /* surrogateescape */
5126 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5127 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005128 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005129 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005130 return unicode;
5131}
5132
5133#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005135/* Primary internal function which creates utf8 encoded bytes objects.
5136
5137 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005138 and allocate exactly as much space needed at the end. Else allocate the
5139 maximum possible needed (4 result bytes per Unicode character), and return
5140 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005141*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005142PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005143_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005144{
Victor Stinner6099a032011-12-18 14:22:26 +01005145 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005146 void *data;
5147 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005149 if (!PyUnicode_Check(unicode)) {
5150 PyErr_BadArgument();
5151 return NULL;
5152 }
5153
5154 if (PyUnicode_READY(unicode) == -1)
5155 return NULL;
5156
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005157 if (PyUnicode_UTF8(unicode))
5158 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5159 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005160
5161 kind = PyUnicode_KIND(unicode);
5162 data = PyUnicode_DATA(unicode);
5163 size = PyUnicode_GET_LENGTH(unicode);
5164
Benjamin Petersonead6b532011-12-20 17:23:42 -06005165 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005166 default:
5167 assert(0);
5168 case PyUnicode_1BYTE_KIND:
5169 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5170 assert(!PyUnicode_IS_ASCII(unicode));
5171 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5172 case PyUnicode_2BYTE_KIND:
5173 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5174 case PyUnicode_4BYTE_KIND:
5175 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005176 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005177}
5178
Alexander Belopolsky40018472011-02-26 01:02:56 +00005179PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005180PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5181 Py_ssize_t size,
5182 const char *errors)
5183{
5184 PyObject *v, *unicode;
5185
5186 unicode = PyUnicode_FromUnicode(s, size);
5187 if (unicode == NULL)
5188 return NULL;
5189 v = _PyUnicode_AsUTF8String(unicode, errors);
5190 Py_DECREF(unicode);
5191 return v;
5192}
5193
5194PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005195PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005196{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005197 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005198}
5199
Walter Dörwald41980ca2007-08-16 21:55:45 +00005200/* --- UTF-32 Codec ------------------------------------------------------- */
5201
5202PyObject *
5203PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005204 Py_ssize_t size,
5205 const char *errors,
5206 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005207{
5208 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5209}
5210
5211PyObject *
5212PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005213 Py_ssize_t size,
5214 const char *errors,
5215 int *byteorder,
5216 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005217{
5218 const char *starts = s;
5219 Py_ssize_t startinpos;
5220 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005221 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005222 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005223 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005224 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005225 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005226 PyObject *errorHandler = NULL;
5227 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005228
Walter Dörwald41980ca2007-08-16 21:55:45 +00005229 q = (unsigned char *)s;
5230 e = q + size;
5231
5232 if (byteorder)
5233 bo = *byteorder;
5234
5235 /* Check for BOM marks (U+FEFF) in the input and adjust current
5236 byte order setting accordingly. In native mode, the leading BOM
5237 mark is skipped, in all other modes, it is copied to the output
5238 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005239 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005240 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005241 if (bom == 0x0000FEFF) {
5242 bo = -1;
5243 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005244 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005245 else if (bom == 0xFFFE0000) {
5246 bo = 1;
5247 q += 4;
5248 }
5249 if (byteorder)
5250 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005251 }
5252
Victor Stinnere64322e2012-10-30 23:12:47 +01005253 if (q == e) {
5254 if (consumed)
5255 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005256 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005257 }
5258
Victor Stinnere64322e2012-10-30 23:12:47 +01005259#ifdef WORDS_BIGENDIAN
5260 le = bo < 0;
5261#else
5262 le = bo <= 0;
5263#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005264 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005265
Victor Stinner8f674cc2013-04-17 23:02:17 +02005266 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005267 writer.min_length = (e - q + 3) / 4;
5268 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005269 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005270
Victor Stinnere64322e2012-10-30 23:12:47 +01005271 while (1) {
5272 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005273 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005274
Victor Stinnere64322e2012-10-30 23:12:47 +01005275 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005276 enum PyUnicode_Kind kind = writer.kind;
5277 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005278 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005279 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005280 if (le) {
5281 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005282 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005283 if (ch > maxch)
5284 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005285 if (kind != PyUnicode_1BYTE_KIND &&
5286 Py_UNICODE_IS_SURROGATE(ch))
5287 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005288 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005289 q += 4;
5290 } while (q <= last);
5291 }
5292 else {
5293 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005294 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005295 if (ch > maxch)
5296 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005297 if (kind != PyUnicode_1BYTE_KIND &&
5298 Py_UNICODE_IS_SURROGATE(ch))
5299 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005300 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005301 q += 4;
5302 } while (q <= last);
5303 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005304 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005305 }
5306
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005307 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005308 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005309 startinpos = ((const char *)q) - starts;
5310 endinpos = startinpos + 4;
5311 }
5312 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005313 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005314 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005315 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005316 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005317 startinpos = ((const char *)q) - starts;
5318 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005319 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005320 else {
5321 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005322 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005323 goto onError;
5324 q += 4;
5325 continue;
5326 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005327 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005328 startinpos = ((const char *)q) - starts;
5329 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005330 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005331
5332 /* The remaining input chars are ignored if the callback
5333 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005334 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005335 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005336 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005338 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005339 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005340 }
5341
Walter Dörwald41980ca2007-08-16 21:55:45 +00005342 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005343 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005344
Walter Dörwald41980ca2007-08-16 21:55:45 +00005345 Py_XDECREF(errorHandler);
5346 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005347 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005348
Benjamin Peterson29060642009-01-31 22:14:21 +00005349 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005350 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005351 Py_XDECREF(errorHandler);
5352 Py_XDECREF(exc);
5353 return NULL;
5354}
5355
5356PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005357_PyUnicode_EncodeUTF32(PyObject *str,
5358 const char *errors,
5359 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005360{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005361 enum PyUnicode_Kind kind;
5362 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005363 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005364 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005365 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005366#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005367 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005368#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005369 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005370#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005371 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005372 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005373 PyObject *errorHandler = NULL;
5374 PyObject *exc = NULL;
5375 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005376
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005377 if (!PyUnicode_Check(str)) {
5378 PyErr_BadArgument();
5379 return NULL;
5380 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005381 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005382 return NULL;
5383 kind = PyUnicode_KIND(str);
5384 data = PyUnicode_DATA(str);
5385 len = PyUnicode_GET_LENGTH(str);
5386
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005387 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005388 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005389 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005390 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005391 if (v == NULL)
5392 return NULL;
5393
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005394 /* output buffer is 4-bytes aligned */
5395 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005396 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005397 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005398 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005399 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005400 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005401
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005402 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005403 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005404 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005405 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005406 else
5407 encoding = "utf-32";
5408
5409 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005410 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5411 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005412 }
5413
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005414 pos = 0;
5415 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005416 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005417
5418 if (kind == PyUnicode_2BYTE_KIND) {
5419 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5420 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005421 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005422 else {
5423 assert(kind == PyUnicode_4BYTE_KIND);
5424 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5425 &out, native_ordering);
5426 }
5427 if (pos == len)
5428 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005429
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005430 rep = unicode_encode_call_errorhandler(
5431 errors, &errorHandler,
5432 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005433 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005434 if (!rep)
5435 goto error;
5436
5437 if (PyBytes_Check(rep)) {
5438 repsize = PyBytes_GET_SIZE(rep);
5439 if (repsize & 3) {
5440 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005441 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005442 "surrogates not allowed");
5443 goto error;
5444 }
5445 moreunits = repsize / 4;
5446 }
5447 else {
5448 assert(PyUnicode_Check(rep));
5449 if (PyUnicode_READY(rep) < 0)
5450 goto error;
5451 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5452 if (!PyUnicode_IS_ASCII(rep)) {
5453 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005454 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005455 "surrogates not allowed");
5456 goto error;
5457 }
5458 }
5459
5460 /* four bytes are reserved for each surrogate */
5461 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005462 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005463 Py_ssize_t morebytes = 4 * (moreunits - 1);
5464 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5465 /* integer overflow */
5466 PyErr_NoMemory();
5467 goto error;
5468 }
5469 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5470 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005471 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005472 }
5473
5474 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005475 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005476 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005477 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005478 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005479 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5480 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005481 }
5482
5483 Py_CLEAR(rep);
5484 }
5485
5486 /* Cut back to size actually needed. This is necessary for, for example,
5487 encoding of a string containing isolated surrogates and the 'ignore'
5488 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005489 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005490 if (nsize != PyBytes_GET_SIZE(v))
5491 _PyBytes_Resize(&v, nsize);
5492 Py_XDECREF(errorHandler);
5493 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005494 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005495 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005496 error:
5497 Py_XDECREF(rep);
5498 Py_XDECREF(errorHandler);
5499 Py_XDECREF(exc);
5500 Py_XDECREF(v);
5501 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005502}
5503
Alexander Belopolsky40018472011-02-26 01:02:56 +00005504PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005505PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5506 Py_ssize_t size,
5507 const char *errors,
5508 int byteorder)
5509{
5510 PyObject *result;
5511 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5512 if (tmp == NULL)
5513 return NULL;
5514 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5515 Py_DECREF(tmp);
5516 return result;
5517}
5518
5519PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005520PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005521{
Victor Stinnerb960b342011-11-20 19:12:52 +01005522 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005523}
5524
Guido van Rossumd57fd912000-03-10 22:53:23 +00005525/* --- UTF-16 Codec ------------------------------------------------------- */
5526
Tim Peters772747b2001-08-09 22:21:55 +00005527PyObject *
5528PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005529 Py_ssize_t size,
5530 const char *errors,
5531 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005532{
Walter Dörwald69652032004-09-07 20:24:22 +00005533 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5534}
5535
5536PyObject *
5537PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005538 Py_ssize_t size,
5539 const char *errors,
5540 int *byteorder,
5541 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005542{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005543 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005544 Py_ssize_t startinpos;
5545 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005546 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005547 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005548 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005549 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005550 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005551 PyObject *errorHandler = NULL;
5552 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005553 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005554
Tim Peters772747b2001-08-09 22:21:55 +00005555 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005556 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005557
5558 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005559 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005560
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005561 /* Check for BOM marks (U+FEFF) in the input and adjust current
5562 byte order setting accordingly. In native mode, the leading BOM
5563 mark is skipped, in all other modes, it is copied to the output
5564 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005565 if (bo == 0 && size >= 2) {
5566 const Py_UCS4 bom = (q[1] << 8) | q[0];
5567 if (bom == 0xFEFF) {
5568 q += 2;
5569 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005570 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005571 else if (bom == 0xFFFE) {
5572 q += 2;
5573 bo = 1;
5574 }
5575 if (byteorder)
5576 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005577 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005578
Antoine Pitrou63065d72012-05-15 23:48:04 +02005579 if (q == e) {
5580 if (consumed)
5581 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005582 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005583 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005584
Christian Heimes743e0cd2012-10-17 23:52:17 +02005585#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005586 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005587 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005588#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005589 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005590 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005591#endif
Tim Peters772747b2001-08-09 22:21:55 +00005592
Antoine Pitrou63065d72012-05-15 23:48:04 +02005593 /* Note: size will always be longer than the resulting Unicode
5594 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005595 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005596 writer.min_length = (e - q + 1) / 2;
5597 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005598 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005599
Antoine Pitrou63065d72012-05-15 23:48:04 +02005600 while (1) {
5601 Py_UCS4 ch = 0;
5602 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005603 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005604 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005605 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005606 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005607 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005608 native_ordering);
5609 else
5610 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005611 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005612 native_ordering);
5613 } else if (kind == PyUnicode_2BYTE_KIND) {
5614 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005615 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005616 native_ordering);
5617 } else {
5618 assert(kind == PyUnicode_4BYTE_KIND);
5619 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005620 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005621 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005622 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005623 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005624
Antoine Pitrou63065d72012-05-15 23:48:04 +02005625 switch (ch)
5626 {
5627 case 0:
5628 /* remaining byte at the end? (size should be even) */
5629 if (q == e || consumed)
5630 goto End;
5631 errmsg = "truncated data";
5632 startinpos = ((const char *)q) - starts;
5633 endinpos = ((const char *)e) - starts;
5634 break;
5635 /* The remaining input chars are ignored if the callback
5636 chooses to skip the input */
5637 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005638 q -= 2;
5639 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005640 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005641 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005642 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005643 endinpos = ((const char *)e) - starts;
5644 break;
5645 case 2:
5646 errmsg = "illegal encoding";
5647 startinpos = ((const char *)q) - 2 - starts;
5648 endinpos = startinpos + 2;
5649 break;
5650 case 3:
5651 errmsg = "illegal UTF-16 surrogate";
5652 startinpos = ((const char *)q) - 4 - starts;
5653 endinpos = startinpos + 2;
5654 break;
5655 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005656 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005657 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005658 continue;
5659 }
5660
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005661 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005662 errors,
5663 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005664 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005665 &starts,
5666 (const char **)&e,
5667 &startinpos,
5668 &endinpos,
5669 &exc,
5670 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005671 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005672 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673 }
5674
Antoine Pitrou63065d72012-05-15 23:48:04 +02005675End:
Walter Dörwald69652032004-09-07 20:24:22 +00005676 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005677 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005678
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005679 Py_XDECREF(errorHandler);
5680 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005681 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005682
Benjamin Peterson29060642009-01-31 22:14:21 +00005683 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005684 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005685 Py_XDECREF(errorHandler);
5686 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687 return NULL;
5688}
5689
Tim Peters772747b2001-08-09 22:21:55 +00005690PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005691_PyUnicode_EncodeUTF16(PyObject *str,
5692 const char *errors,
5693 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005695 enum PyUnicode_Kind kind;
5696 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005697 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005698 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005699 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005700 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005701#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005702 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005703#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005704 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005705#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005706 const char *encoding;
5707 Py_ssize_t nsize, pos;
5708 PyObject *errorHandler = NULL;
5709 PyObject *exc = NULL;
5710 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005711
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005712 if (!PyUnicode_Check(str)) {
5713 PyErr_BadArgument();
5714 return NULL;
5715 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005716 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005717 return NULL;
5718 kind = PyUnicode_KIND(str);
5719 data = PyUnicode_DATA(str);
5720 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005721
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005722 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005723 if (kind == PyUnicode_4BYTE_KIND) {
5724 const Py_UCS4 *in = (const Py_UCS4 *)data;
5725 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005726 while (in < end) {
5727 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005728 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005729 }
5730 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005731 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005732 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005733 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005734 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005735 nsize = len + pairs + (byteorder == 0);
5736 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005737 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005739 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005741 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005742 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005743 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005744 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005745 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005746 }
5747 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005748 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005749 }
Tim Peters772747b2001-08-09 22:21:55 +00005750
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005751 if (kind == PyUnicode_1BYTE_KIND) {
5752 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5753 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005754 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005755
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005756 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005757 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005758 }
5759 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005760 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005761 }
5762 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005763 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005764 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005765
5766 pos = 0;
5767 while (pos < len) {
5768 Py_ssize_t repsize, moreunits;
5769
5770 if (kind == PyUnicode_2BYTE_KIND) {
5771 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5772 &out, native_ordering);
5773 }
5774 else {
5775 assert(kind == PyUnicode_4BYTE_KIND);
5776 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5777 &out, native_ordering);
5778 }
5779 if (pos == len)
5780 break;
5781
5782 rep = unicode_encode_call_errorhandler(
5783 errors, &errorHandler,
5784 encoding, "surrogates not allowed",
5785 str, &exc, pos, pos + 1, &pos);
5786 if (!rep)
5787 goto error;
5788
5789 if (PyBytes_Check(rep)) {
5790 repsize = PyBytes_GET_SIZE(rep);
5791 if (repsize & 1) {
5792 raise_encode_exception(&exc, encoding,
5793 str, pos - 1, pos,
5794 "surrogates not allowed");
5795 goto error;
5796 }
5797 moreunits = repsize / 2;
5798 }
5799 else {
5800 assert(PyUnicode_Check(rep));
5801 if (PyUnicode_READY(rep) < 0)
5802 goto error;
5803 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5804 if (!PyUnicode_IS_ASCII(rep)) {
5805 raise_encode_exception(&exc, encoding,
5806 str, pos - 1, pos,
5807 "surrogates not allowed");
5808 goto error;
5809 }
5810 }
5811
5812 /* two bytes are reserved for each surrogate */
5813 if (moreunits > 1) {
5814 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5815 Py_ssize_t morebytes = 2 * (moreunits - 1);
5816 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5817 /* integer overflow */
5818 PyErr_NoMemory();
5819 goto error;
5820 }
5821 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5822 goto error;
5823 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5824 }
5825
5826 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005827 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005828 out += moreunits;
5829 } else /* rep is unicode */ {
5830 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5831 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5832 &out, native_ordering);
5833 }
5834
5835 Py_CLEAR(rep);
5836 }
5837
5838 /* Cut back to size actually needed. This is necessary for, for example,
5839 encoding of a string containing isolated surrogates and the 'ignore' handler
5840 is used. */
5841 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5842 if (nsize != PyBytes_GET_SIZE(v))
5843 _PyBytes_Resize(&v, nsize);
5844 Py_XDECREF(errorHandler);
5845 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005846 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005847 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005848 error:
5849 Py_XDECREF(rep);
5850 Py_XDECREF(errorHandler);
5851 Py_XDECREF(exc);
5852 Py_XDECREF(v);
5853 return NULL;
5854#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005855}
5856
Alexander Belopolsky40018472011-02-26 01:02:56 +00005857PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005858PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5859 Py_ssize_t size,
5860 const char *errors,
5861 int byteorder)
5862{
5863 PyObject *result;
5864 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5865 if (tmp == NULL)
5866 return NULL;
5867 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5868 Py_DECREF(tmp);
5869 return result;
5870}
5871
5872PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005873PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005875 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876}
5877
5878/* --- Unicode Escape Codec ----------------------------------------------- */
5879
Fredrik Lundh06d12682001-01-24 07:59:11 +00005880static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005881
Alexander Belopolsky40018472011-02-26 01:02:56 +00005882PyObject *
5883PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005884 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005885 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005886{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005887 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005888 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005890 PyObject *errorHandler = NULL;
5891 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005892
Victor Stinner62ec3312016-09-06 17:04:34 -07005893 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005894 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005895 }
5896 /* Escaped strings will always be longer than the resulting
5897 Unicode string, so we start with size here and then reduce the
5898 length after conversion to the true value.
5899 (but if the error callback returns a long replacement string
5900 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005901 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005902 writer.min_length = size;
5903 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5904 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005905 }
5906
Guido van Rossumd57fd912000-03-10 22:53:23 +00005907 end = s + size;
5908 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005909 unsigned char c = (unsigned char) *s++;
5910 Py_UCS4 ch;
5911 int count;
5912 Py_ssize_t startinpos;
5913 Py_ssize_t endinpos;
5914 const char *message;
5915
5916#define WRITE_ASCII_CHAR(ch) \
5917 do { \
5918 assert(ch <= 127); \
5919 assert(writer.pos < writer.size); \
5920 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5921 } while(0)
5922
5923#define WRITE_CHAR(ch) \
5924 do { \
5925 if (ch <= writer.maxchar) { \
5926 assert(writer.pos < writer.size); \
5927 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5928 } \
5929 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5930 goto onError; \
5931 } \
5932 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933
5934 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005935 if (c != '\\') {
5936 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937 continue;
5938 }
5939
Victor Stinner62ec3312016-09-06 17:04:34 -07005940 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005942 if (s >= end) {
5943 message = "\\ at end of string";
5944 goto error;
5945 }
5946 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005947
Victor Stinner62ec3312016-09-06 17:04:34 -07005948 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005949 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005950
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005952 case '\n': continue;
5953 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5954 case '\'': WRITE_ASCII_CHAR('\''); continue;
5955 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5956 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005957 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005958 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5959 case 't': WRITE_ASCII_CHAR('\t'); continue;
5960 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5961 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005962 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005963 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005964 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005965 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966
Benjamin Peterson29060642009-01-31 22:14:21 +00005967 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 case '0': case '1': case '2': case '3':
5969 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005970 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005971 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005972 ch = (ch<<3) + *s++ - '0';
5973 if (s < end && '0' <= *s && *s <= '7') {
5974 ch = (ch<<3) + *s++ - '0';
5975 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005977 WRITE_CHAR(ch);
5978 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979
Benjamin Peterson29060642009-01-31 22:14:21 +00005980 /* hex escapes */
5981 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005982 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005983 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005984 message = "truncated \\xXX escape";
5985 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005986
Benjamin Peterson29060642009-01-31 22:14:21 +00005987 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005988 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005989 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005990 message = "truncated \\uXXXX escape";
5991 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992
Benjamin Peterson29060642009-01-31 22:14:21 +00005993 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005994 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005995 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005996 message = "truncated \\UXXXXXXXX escape";
5997 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07005998 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02005999 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006000 ch <<= 4;
6001 if (c >= '0' && c <= '9') {
6002 ch += c - '0';
6003 }
6004 else if (c >= 'a' && c <= 'f') {
6005 ch += c - ('a' - 10);
6006 }
6007 else if (c >= 'A' && c <= 'F') {
6008 ch += c - ('A' - 10);
6009 }
6010 else {
6011 break;
6012 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006013 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006014 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006015 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006016 }
6017
6018 /* when we get here, ch is a 32-bit unicode character */
6019 if (ch > MAX_UNICODE) {
6020 message = "illegal Unicode character";
6021 goto error;
6022 }
6023
6024 WRITE_CHAR(ch);
6025 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006026
Benjamin Peterson29060642009-01-31 22:14:21 +00006027 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006028 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006029 if (ucnhash_CAPI == NULL) {
6030 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006031 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6032 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006033 if (ucnhash_CAPI == NULL) {
6034 PyErr_SetString(
6035 PyExc_UnicodeError,
6036 "\\N escapes not supported (can't load unicodedata module)"
6037 );
6038 goto onError;
6039 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006040 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006041
6042 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006043 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006044 const char *start = ++s;
6045 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006046 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006047 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006048 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006049 namelen = s - start;
6050 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006051 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006052 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006053 ch = 0xffffffff; /* in case 'getcode' messes up */
6054 if (namelen <= INT_MAX &&
6055 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6056 &ch, 0)) {
6057 assert(ch <= MAX_UNICODE);
6058 WRITE_CHAR(ch);
6059 continue;
6060 }
6061 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006062 }
6063 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006064 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006065
6066 default:
R David Murray110b6fe2016-09-08 15:34:08 -04006067 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6068 "invalid escape sequence '\\%c'", c) < 0)
6069 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006070 WRITE_ASCII_CHAR('\\');
6071 WRITE_CHAR(c);
6072 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006073 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006074
6075 error:
6076 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006077 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006078 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006079 errors, &errorHandler,
6080 "unicodeescape", message,
6081 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006082 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006083 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006084 }
6085 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6086 goto onError;
6087 }
6088
6089#undef WRITE_ASCII_CHAR
6090#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006091 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006092
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006093 Py_XDECREF(errorHandler);
6094 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006095 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006096
Benjamin Peterson29060642009-01-31 22:14:21 +00006097 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006098 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006099 Py_XDECREF(errorHandler);
6100 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006101 return NULL;
6102}
6103
6104/* Return a Unicode-Escape string version of the Unicode object.
6105
6106 If quotes is true, the string is enclosed in u"" or u'' quotes as
6107 appropriate.
6108
6109*/
6110
Alexander Belopolsky40018472011-02-26 01:02:56 +00006111PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006112PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006113{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006114 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006115 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006116 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006117 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006118 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006119 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006120
Ezio Melottie7f90372012-10-05 03:33:31 +03006121 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006122 escape.
6123
Ezio Melottie7f90372012-10-05 03:33:31 +03006124 For UCS1 strings it's '\xxx', 4 bytes per source character.
6125 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6126 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006127 */
6128
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006129 if (!PyUnicode_Check(unicode)) {
6130 PyErr_BadArgument();
6131 return NULL;
6132 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006133 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006134 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006135 }
Victor Stinner358af132015-10-12 22:36:57 +02006136
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006137 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006138 if (len == 0) {
6139 return PyBytes_FromStringAndSize(NULL, 0);
6140 }
6141
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006142 kind = PyUnicode_KIND(unicode);
6143 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006144 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6145 bytes, and 1 byte characters 4. */
6146 expandsize = kind * 2 + 2;
6147 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize) {
6148 return PyErr_NoMemory();
6149 }
6150 repr = PyBytes_FromStringAndSize(NULL, 2 + expandsize * len + 1);
6151 if (repr == NULL) {
6152 return NULL;
6153 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006154
Victor Stinner62ec3312016-09-06 17:04:34 -07006155 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006156 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006157 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006158
Victor Stinner62ec3312016-09-06 17:04:34 -07006159 /* U+0000-U+00ff range */
6160 if (ch < 0x100) {
6161 if (ch >= ' ' && ch < 127) {
6162 if (ch != '\\') {
6163 /* Copy printable US ASCII as-is */
6164 *p++ = (char) ch;
6165 }
6166 /* Escape backslashes */
6167 else {
6168 *p++ = '\\';
6169 *p++ = '\\';
6170 }
6171 }
Victor Stinner358af132015-10-12 22:36:57 +02006172
Victor Stinner62ec3312016-09-06 17:04:34 -07006173 /* Map special whitespace to '\t', \n', '\r' */
6174 else if (ch == '\t') {
6175 *p++ = '\\';
6176 *p++ = 't';
6177 }
6178 else if (ch == '\n') {
6179 *p++ = '\\';
6180 *p++ = 'n';
6181 }
6182 else if (ch == '\r') {
6183 *p++ = '\\';
6184 *p++ = 'r';
6185 }
6186
6187 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6188 else {
6189 *p++ = '\\';
6190 *p++ = 'x';
6191 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6192 *p++ = Py_hexdigits[ch & 0x000F];
6193 }
Tim Petersced69f82003-09-16 20:30:58 +00006194 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006195 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6196 else if (ch < 0x10000) {
6197 /* U+0100-U+ffff */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198 *p++ = '\\';
6199 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006200 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6201 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6202 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6203 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006204 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006205 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6206 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006207
Victor Stinner62ec3312016-09-06 17:04:34 -07006208 /* Make sure that the first two digits are zero */
6209 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006210 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006211 *p++ = 'U';
6212 *p++ = '0';
6213 *p++ = '0';
6214 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6215 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6216 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6217 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6218 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6219 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006220 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006222
Victor Stinner62ec3312016-09-06 17:04:34 -07006223 assert(p - PyBytes_AS_STRING(repr) > 0);
6224 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6225 return NULL;
6226 }
6227 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228}
6229
Alexander Belopolsky40018472011-02-26 01:02:56 +00006230PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006231PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6232 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006234 PyObject *result;
6235 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006236 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006238 }
6239
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006240 result = PyUnicode_AsUnicodeEscapeString(tmp);
6241 Py_DECREF(tmp);
6242 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243}
6244
6245/* --- Raw Unicode Escape Codec ------------------------------------------- */
6246
Alexander Belopolsky40018472011-02-26 01:02:56 +00006247PyObject *
6248PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006249 Py_ssize_t size,
6250 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006251{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006252 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006253 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006255 PyObject *errorHandler = NULL;
6256 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006257
Victor Stinner62ec3312016-09-06 17:04:34 -07006258 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006259 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006260 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006261
Guido van Rossumd57fd912000-03-10 22:53:23 +00006262 /* Escaped strings will always be longer than the resulting
6263 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006264 length after conversion to the true value. (But decoding error
6265 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006266 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006267 writer.min_length = size;
6268 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6269 goto onError;
6270 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006271
Guido van Rossumd57fd912000-03-10 22:53:23 +00006272 end = s + size;
6273 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006274 unsigned char c = (unsigned char) *s++;
6275 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006276 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006277 Py_ssize_t startinpos;
6278 Py_ssize_t endinpos;
6279 const char *message;
6280
6281#define WRITE_CHAR(ch) \
6282 do { \
6283 if (ch <= writer.maxchar) { \
6284 assert(writer.pos < writer.size); \
6285 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6286 } \
6287 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6288 goto onError; \
6289 } \
6290 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006291
Benjamin Peterson29060642009-01-31 22:14:21 +00006292 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006293 if (c != '\\' || s >= end) {
6294 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006295 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006296 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006297
Victor Stinner62ec3312016-09-06 17:04:34 -07006298 c = (unsigned char) *s++;
6299 if (c == 'u') {
6300 count = 4;
6301 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006302 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006303 else if (c == 'U') {
6304 count = 8;
6305 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006306 }
6307 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006308 assert(writer.pos < writer.size);
6309 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6310 WRITE_CHAR(c);
6311 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006312 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006313 startinpos = s - starts - 2;
6314
6315 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6316 for (ch = 0; count && s < end; ++s, --count) {
6317 c = (unsigned char)*s;
6318 ch <<= 4;
6319 if (c >= '0' && c <= '9') {
6320 ch += c - '0';
6321 }
6322 else if (c >= 'a' && c <= 'f') {
6323 ch += c - ('a' - 10);
6324 }
6325 else if (c >= 'A' && c <= 'F') {
6326 ch += c - ('A' - 10);
6327 }
6328 else {
6329 break;
6330 }
6331 }
6332 if (!count) {
6333 if (ch <= MAX_UNICODE) {
6334 WRITE_CHAR(ch);
6335 continue;
6336 }
6337 message = "\\Uxxxxxxxx out of range";
6338 }
6339
6340 endinpos = s-starts;
6341 writer.min_length = end - s + writer.pos;
6342 if (unicode_decode_call_errorhandler_writer(
6343 errors, &errorHandler,
6344 "rawunicodeescape", message,
6345 &starts, &end, &startinpos, &endinpos, &exc, &s,
6346 &writer)) {
6347 goto onError;
6348 }
6349 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6350 goto onError;
6351 }
6352
6353#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006354 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006355 Py_XDECREF(errorHandler);
6356 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006357 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006358
Benjamin Peterson29060642009-01-31 22:14:21 +00006359 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006360 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006361 Py_XDECREF(errorHandler);
6362 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006363 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006364
Guido van Rossumd57fd912000-03-10 22:53:23 +00006365}
6366
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006367
Alexander Belopolsky40018472011-02-26 01:02:56 +00006368PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006369PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006370{
Victor Stinner62ec3312016-09-06 17:04:34 -07006371 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006372 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006373 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006374 int kind;
6375 void *data;
6376 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006377
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006378 if (!PyUnicode_Check(unicode)) {
6379 PyErr_BadArgument();
6380 return NULL;
6381 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006382 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006383 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006384 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006385 kind = PyUnicode_KIND(unicode);
6386 data = PyUnicode_DATA(unicode);
6387 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006388 if (kind == PyUnicode_1BYTE_KIND) {
6389 return PyBytes_FromStringAndSize(data, len);
6390 }
Victor Stinner0e368262011-11-10 20:12:49 +01006391
Victor Stinner62ec3312016-09-06 17:04:34 -07006392 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6393 bytes, and 1 byte characters 4. */
6394 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006395
Victor Stinner62ec3312016-09-06 17:04:34 -07006396 if (len > PY_SSIZE_T_MAX / expandsize) {
6397 return PyErr_NoMemory();
6398 }
6399 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6400 if (repr == NULL) {
6401 return NULL;
6402 }
6403 if (len == 0) {
6404 return repr;
6405 }
6406
6407 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006408 for (pos = 0; pos < len; pos++) {
6409 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006410
Victor Stinner62ec3312016-09-06 17:04:34 -07006411 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6412 if (ch < 0x100) {
6413 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006414 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006415 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6416 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006417 *p++ = '\\';
6418 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006419 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6420 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6421 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6422 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006423 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006424 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6425 else {
6426 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6427 *p++ = '\\';
6428 *p++ = 'U';
6429 *p++ = '0';
6430 *p++ = '0';
6431 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6432 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6433 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6434 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6435 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6436 *p++ = Py_hexdigits[ch & 15];
6437 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006438 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006439
Victor Stinner62ec3312016-09-06 17:04:34 -07006440 assert(p > PyBytes_AS_STRING(repr));
6441 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6442 return NULL;
6443 }
6444 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006445}
6446
Alexander Belopolsky40018472011-02-26 01:02:56 +00006447PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006448PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6449 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006450{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006451 PyObject *result;
6452 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6453 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006454 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006455 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6456 Py_DECREF(tmp);
6457 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006458}
6459
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006460/* --- Unicode Internal Codec ------------------------------------------- */
6461
Alexander Belopolsky40018472011-02-26 01:02:56 +00006462PyObject *
6463_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006464 Py_ssize_t size,
6465 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006466{
6467 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006468 Py_ssize_t startinpos;
6469 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006470 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006471 const char *end;
6472 const char *reason;
6473 PyObject *errorHandler = NULL;
6474 PyObject *exc = NULL;
6475
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006476 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006477 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006478 1))
6479 return NULL;
6480
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006481 if (size == 0)
6482 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006483
Victor Stinner8f674cc2013-04-17 23:02:17 +02006484 _PyUnicodeWriter_Init(&writer);
6485 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6486 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006487 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006488 }
6489 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006490
Victor Stinner8f674cc2013-04-17 23:02:17 +02006491 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006492 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006493 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006494 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006495 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006496 endinpos = end-starts;
6497 reason = "truncated input";
6498 goto error;
6499 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006500 /* We copy the raw representation one byte at a time because the
6501 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006502 ((char *) &uch)[0] = s[0];
6503 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006504#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006505 ((char *) &uch)[2] = s[2];
6506 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006507#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006508 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006509#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006510 /* We have to sanity check the raw data, otherwise doom looms for
6511 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006512 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006513 endinpos = s - starts + Py_UNICODE_SIZE;
6514 reason = "illegal code point (> 0x10FFFF)";
6515 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006516 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006517#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006518 s += Py_UNICODE_SIZE;
6519#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006520 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006521 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006522 Py_UNICODE uch2;
6523 ((char *) &uch2)[0] = s[0];
6524 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006525 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006526 {
Victor Stinner551ac952011-11-29 22:58:13 +01006527 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006528 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006529 }
6530 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006531#endif
6532
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006533 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006534 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006535 continue;
6536
6537 error:
6538 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006539 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006540 errors, &errorHandler,
6541 "unicode_internal", reason,
6542 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006543 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006544 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006545 }
6546
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006547 Py_XDECREF(errorHandler);
6548 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006549 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006550
Benjamin Peterson29060642009-01-31 22:14:21 +00006551 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006552 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006553 Py_XDECREF(errorHandler);
6554 Py_XDECREF(exc);
6555 return NULL;
6556}
6557
Guido van Rossumd57fd912000-03-10 22:53:23 +00006558/* --- Latin-1 Codec ------------------------------------------------------ */
6559
Alexander Belopolsky40018472011-02-26 01:02:56 +00006560PyObject *
6561PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006562 Py_ssize_t size,
6563 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006564{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006565 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006566 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006567}
6568
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006569/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006570static void
6571make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006572 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006573 PyObject *unicode,
6574 Py_ssize_t startpos, Py_ssize_t endpos,
6575 const char *reason)
6576{
6577 if (*exceptionObject == NULL) {
6578 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006579 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006580 encoding, unicode, startpos, endpos, reason);
6581 }
6582 else {
6583 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6584 goto onError;
6585 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6586 goto onError;
6587 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6588 goto onError;
6589 return;
6590 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006591 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006592 }
6593}
6594
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006595/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006596static void
6597raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006598 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006599 PyObject *unicode,
6600 Py_ssize_t startpos, Py_ssize_t endpos,
6601 const char *reason)
6602{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006603 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006604 encoding, unicode, startpos, endpos, reason);
6605 if (*exceptionObject != NULL)
6606 PyCodec_StrictErrors(*exceptionObject);
6607}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006608
6609/* error handling callback helper:
6610 build arguments, call the callback and check the arguments,
6611 put the result into newpos and return the replacement string, which
6612 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006613static PyObject *
6614unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006615 PyObject **errorHandler,
6616 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006617 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006618 Py_ssize_t startpos, Py_ssize_t endpos,
6619 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006620{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006621 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006622 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006623 PyObject *restuple;
6624 PyObject *resunicode;
6625
6626 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006627 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006628 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006629 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006630 }
6631
Benjamin Petersonbac79492012-01-14 13:34:47 -05006632 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006633 return NULL;
6634 len = PyUnicode_GET_LENGTH(unicode);
6635
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006636 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006638 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006639 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006640
6641 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006642 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006643 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006644 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006645 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006646 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006647 Py_DECREF(restuple);
6648 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006649 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006650 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006651 &resunicode, newpos)) {
6652 Py_DECREF(restuple);
6653 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006654 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006655 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6656 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6657 Py_DECREF(restuple);
6658 return NULL;
6659 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006660 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006661 *newpos = len + *newpos;
6662 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006663 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006664 Py_DECREF(restuple);
6665 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006666 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006667 Py_INCREF(resunicode);
6668 Py_DECREF(restuple);
6669 return resunicode;
6670}
6671
Alexander Belopolsky40018472011-02-26 01:02:56 +00006672static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006673unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006674 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006675 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006676{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006677 /* input state */
6678 Py_ssize_t pos=0, size;
6679 int kind;
6680 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006681 /* pointer into the output */
6682 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006683 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6684 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006685 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006686 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006687 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006688 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006689 /* output object */
6690 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006691
Benjamin Petersonbac79492012-01-14 13:34:47 -05006692 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006693 return NULL;
6694 size = PyUnicode_GET_LENGTH(unicode);
6695 kind = PyUnicode_KIND(unicode);
6696 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697 /* allocate enough for a simple encoding without
6698 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006699 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006700 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006701
6702 _PyBytesWriter_Init(&writer);
6703 str = _PyBytesWriter_Alloc(&writer, size);
6704 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006705 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006706
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006707 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006708 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006709
Benjamin Peterson29060642009-01-31 22:14:21 +00006710 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006711 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006712 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006713 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006714 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006715 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006716 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006717 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006719 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006720 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006721 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006722
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006723 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006725
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006726 /* Only overallocate the buffer if it's not the last write */
6727 writer.overallocate = (collend < size);
6728
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006730 if (error_handler == _Py_ERROR_UNKNOWN)
6731 error_handler = get_error_handler(errors);
6732
6733 switch (error_handler) {
6734 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006735 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006737
6738 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006739 memset(str, '?', collend - collstart);
6740 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006741 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006742 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006743 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006744 break;
Victor Stinner50149202015-09-22 00:26:54 +02006745
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006746 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006747 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006748 writer.min_size -= (collend - collstart);
6749 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006750 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006751 if (str == NULL)
6752 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006753 pos = collend;
6754 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006755
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006756 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006757 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006758 writer.min_size -= (collend - collstart);
6759 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006760 unicode, collstart, collend);
6761 if (str == NULL)
6762 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006763 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006764 break;
Victor Stinner50149202015-09-22 00:26:54 +02006765
Victor Stinnerc3713e92015-09-29 12:32:13 +02006766 case _Py_ERROR_SURROGATEESCAPE:
6767 for (i = collstart; i < collend; ++i) {
6768 ch = PyUnicode_READ(kind, data, i);
6769 if (ch < 0xdc80 || 0xdcff < ch) {
6770 /* Not a UTF-8b surrogate */
6771 break;
6772 }
6773 *str++ = (char)(ch - 0xdc00);
6774 ++pos;
6775 }
6776 if (i >= collend)
6777 break;
6778 collstart = pos;
6779 assert(collstart != collend);
6780 /* fallback to general error handling */
6781
Benjamin Peterson29060642009-01-31 22:14:21 +00006782 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006783 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6784 encoding, reason, unicode, &exc,
6785 collstart, collend, &newpos);
6786 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006787 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006788
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006789 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006790 writer.min_size -= 1;
6791
Victor Stinner6bd525b2015-10-09 13:10:05 +02006792 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006793 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006794 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006795 PyBytes_AS_STRING(rep),
6796 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006797 if (str == NULL)
6798 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006799 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006800 else {
6801 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006802
Victor Stinner6bd525b2015-10-09 13:10:05 +02006803 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006804 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006805
6806 if (PyUnicode_IS_ASCII(rep)) {
6807 /* Fast path: all characters are smaller than limit */
6808 assert(limit >= 128);
6809 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6810 str = _PyBytesWriter_WriteBytes(&writer, str,
6811 PyUnicode_DATA(rep),
6812 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006813 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006814 else {
6815 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6816
6817 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6818 if (str == NULL)
6819 goto onError;
6820
6821 /* check if there is anything unencodable in the
6822 replacement and copy it to the output */
6823 for (i = 0; repsize-->0; ++i, ++str) {
6824 ch = PyUnicode_READ_CHAR(rep, i);
6825 if (ch >= limit) {
6826 raise_encode_exception(&exc, encoding, unicode,
6827 pos, pos+1, reason);
6828 goto onError;
6829 }
6830 *str = (char)ch;
6831 }
6832 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006833 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006834 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006835 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006836 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006837
6838 /* If overallocation was disabled, ensure that it was the last
6839 write. Otherwise, we missed an optimization */
6840 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006841 }
6842 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006843
Victor Stinner50149202015-09-22 00:26:54 +02006844 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006845 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006846 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006847
6848 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006849 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006850 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006851 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006852 Py_XDECREF(exc);
6853 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006854}
6855
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006856/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006857PyObject *
6858PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006859 Py_ssize_t size,
6860 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006861{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006862 PyObject *result;
6863 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6864 if (unicode == NULL)
6865 return NULL;
6866 result = unicode_encode_ucs1(unicode, errors, 256);
6867 Py_DECREF(unicode);
6868 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006869}
6870
Alexander Belopolsky40018472011-02-26 01:02:56 +00006871PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006872_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006873{
6874 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006875 PyErr_BadArgument();
6876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006877 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006878 if (PyUnicode_READY(unicode) == -1)
6879 return NULL;
6880 /* Fast path: if it is a one-byte string, construct
6881 bytes object directly. */
6882 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6883 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6884 PyUnicode_GET_LENGTH(unicode));
6885 /* Non-Latin-1 characters present. Defer to above function to
6886 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006887 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006888}
6889
6890PyObject*
6891PyUnicode_AsLatin1String(PyObject *unicode)
6892{
6893 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006894}
6895
6896/* --- 7-bit ASCII Codec -------------------------------------------------- */
6897
Alexander Belopolsky40018472011-02-26 01:02:56 +00006898PyObject *
6899PyUnicode_DecodeASCII(const char *s,
6900 Py_ssize_t size,
6901 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006902{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006903 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006904 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006905 int kind;
6906 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006907 Py_ssize_t startinpos;
6908 Py_ssize_t endinpos;
6909 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006910 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006911 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006912 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006913 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006914
Guido van Rossumd57fd912000-03-10 22:53:23 +00006915 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006916 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006917
Guido van Rossumd57fd912000-03-10 22:53:23 +00006918 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006919 if (size == 1 && (unsigned char)s[0] < 128)
6920 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006921
Victor Stinner8f674cc2013-04-17 23:02:17 +02006922 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006923 writer.min_length = size;
6924 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006925 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006926
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006927 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006928 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006929 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006930 writer.pos = outpos;
6931 if (writer.pos == size)
6932 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006933
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006934 s += writer.pos;
6935 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006936 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006937 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006938 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006939 PyUnicode_WRITE(kind, data, writer.pos, c);
6940 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006941 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006942 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006943 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006944
6945 /* byte outsize range 0x00..0x7f: call the error handler */
6946
6947 if (error_handler == _Py_ERROR_UNKNOWN)
6948 error_handler = get_error_handler(errors);
6949
6950 switch (error_handler)
6951 {
6952 case _Py_ERROR_REPLACE:
6953 case _Py_ERROR_SURROGATEESCAPE:
6954 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006955 but we may switch to UCS2 at the first write */
6956 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6957 goto onError;
6958 kind = writer.kind;
6959 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006960
6961 if (error_handler == _Py_ERROR_REPLACE)
6962 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6963 else
6964 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6965 writer.pos++;
6966 ++s;
6967 break;
6968
6969 case _Py_ERROR_IGNORE:
6970 ++s;
6971 break;
6972
6973 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006974 startinpos = s-starts;
6975 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006976 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006977 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006978 "ascii", "ordinal not in range(128)",
6979 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006980 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006981 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006982 kind = writer.kind;
6983 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006984 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006985 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006986 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006987 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006988 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006989
Benjamin Peterson29060642009-01-31 22:14:21 +00006990 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006991 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006992 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006993 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006994 return NULL;
6995}
6996
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006997/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006998PyObject *
6999PyUnicode_EncodeASCII(const Py_UNICODE *p,
7000 Py_ssize_t size,
7001 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007002{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007003 PyObject *result;
7004 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7005 if (unicode == NULL)
7006 return NULL;
7007 result = unicode_encode_ucs1(unicode, errors, 128);
7008 Py_DECREF(unicode);
7009 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007010}
7011
Alexander Belopolsky40018472011-02-26 01:02:56 +00007012PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007013_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007014{
7015 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007016 PyErr_BadArgument();
7017 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007018 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007019 if (PyUnicode_READY(unicode) == -1)
7020 return NULL;
7021 /* Fast path: if it is an ASCII-only string, construct bytes object
7022 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007023 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007024 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7025 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007026 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007027}
7028
7029PyObject *
7030PyUnicode_AsASCIIString(PyObject *unicode)
7031{
7032 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007033}
7034
Steve Dowercc16be82016-09-08 10:35:16 -07007035#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007036
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007037/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007038
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007039#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007040#define NEED_RETRY
7041#endif
7042
Victor Stinner3a50e702011-10-18 21:21:00 +02007043#ifndef WC_ERR_INVALID_CHARS
7044# define WC_ERR_INVALID_CHARS 0x0080
7045#endif
7046
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007047static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007048code_page_name(UINT code_page, PyObject **obj)
7049{
7050 *obj = NULL;
7051 if (code_page == CP_ACP)
7052 return "mbcs";
7053 if (code_page == CP_UTF7)
7054 return "CP_UTF7";
7055 if (code_page == CP_UTF8)
7056 return "CP_UTF8";
7057
7058 *obj = PyBytes_FromFormat("cp%u", code_page);
7059 if (*obj == NULL)
7060 return NULL;
7061 return PyBytes_AS_STRING(*obj);
7062}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063
Victor Stinner3a50e702011-10-18 21:21:00 +02007064static DWORD
7065decode_code_page_flags(UINT code_page)
7066{
7067 if (code_page == CP_UTF7) {
7068 /* The CP_UTF7 decoder only supports flags=0 */
7069 return 0;
7070 }
7071 else
7072 return MB_ERR_INVALID_CHARS;
7073}
7074
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007075/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 * Decode a byte string from a Windows code page into unicode object in strict
7077 * mode.
7078 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007079 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7080 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007082static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007083decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007084 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007085 const char *in,
7086 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087{
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007089 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007090 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007091
7092 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007093 assert(insize > 0);
7094 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7095 if (outsize <= 0)
7096 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007097
7098 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007099 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007100 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007101 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007102 if (*v == NULL)
7103 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105 }
7106 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007107 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007108 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007109 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007110 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007111 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007112 }
7113
7114 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007115 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7116 if (outsize <= 0)
7117 goto error;
7118 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007119
Victor Stinner3a50e702011-10-18 21:21:00 +02007120error:
7121 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7122 return -2;
7123 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007124 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007125}
7126
Victor Stinner3a50e702011-10-18 21:21:00 +02007127/*
7128 * Decode a byte string from a code page into unicode object with an error
7129 * handler.
7130 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007131 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007132 * UnicodeDecodeError exception and returns -1 on error.
7133 */
7134static int
7135decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007136 PyObject **v,
7137 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007138 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007139{
7140 const char *startin = in;
7141 const char *endin = in + size;
7142 const DWORD flags = decode_code_page_flags(code_page);
7143 /* Ideally, we should get reason from FormatMessage. This is the Windows
7144 2000 English version of the message. */
7145 const char *reason = "No mapping for the Unicode character exists "
7146 "in the target code page.";
7147 /* each step cannot decode more than 1 character, but a character can be
7148 represented as a surrogate pair */
7149 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007150 int insize;
7151 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007152 PyObject *errorHandler = NULL;
7153 PyObject *exc = NULL;
7154 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007155 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007156 DWORD err;
7157 int ret = -1;
7158
7159 assert(size > 0);
7160
7161 encoding = code_page_name(code_page, &encoding_obj);
7162 if (encoding == NULL)
7163 return -1;
7164
Victor Stinner7d00cc12014-03-17 23:08:06 +01007165 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007166 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7167 UnicodeDecodeError. */
7168 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7169 if (exc != NULL) {
7170 PyCodec_StrictErrors(exc);
7171 Py_CLEAR(exc);
7172 }
7173 goto error;
7174 }
7175
7176 if (*v == NULL) {
7177 /* Create unicode object */
7178 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7179 PyErr_NoMemory();
7180 goto error;
7181 }
Victor Stinnerab595942011-12-17 04:59:06 +01007182 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007183 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007184 if (*v == NULL)
7185 goto error;
7186 startout = PyUnicode_AS_UNICODE(*v);
7187 }
7188 else {
7189 /* Extend unicode object */
7190 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7191 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7192 PyErr_NoMemory();
7193 goto error;
7194 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007195 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007196 goto error;
7197 startout = PyUnicode_AS_UNICODE(*v) + n;
7198 }
7199
7200 /* Decode the byte string character per character */
7201 out = startout;
7202 while (in < endin)
7203 {
7204 /* Decode a character */
7205 insize = 1;
7206 do
7207 {
7208 outsize = MultiByteToWideChar(code_page, flags,
7209 in, insize,
7210 buffer, Py_ARRAY_LENGTH(buffer));
7211 if (outsize > 0)
7212 break;
7213 err = GetLastError();
7214 if (err != ERROR_NO_UNICODE_TRANSLATION
7215 && err != ERROR_INSUFFICIENT_BUFFER)
7216 {
7217 PyErr_SetFromWindowsErr(0);
7218 goto error;
7219 }
7220 insize++;
7221 }
7222 /* 4=maximum length of a UTF-8 sequence */
7223 while (insize <= 4 && (in + insize) <= endin);
7224
7225 if (outsize <= 0) {
7226 Py_ssize_t startinpos, endinpos, outpos;
7227
Victor Stinner7d00cc12014-03-17 23:08:06 +01007228 /* last character in partial decode? */
7229 if (in + insize >= endin && !final)
7230 break;
7231
Victor Stinner3a50e702011-10-18 21:21:00 +02007232 startinpos = in - startin;
7233 endinpos = startinpos + 1;
7234 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007235 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 errors, &errorHandler,
7237 encoding, reason,
7238 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007239 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007240 {
7241 goto error;
7242 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007243 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007244 }
7245 else {
7246 in += insize;
7247 memcpy(out, buffer, outsize * sizeof(wchar_t));
7248 out += outsize;
7249 }
7250 }
7251
7252 /* write a NUL character at the end */
7253 *out = 0;
7254
7255 /* Extend unicode object */
7256 outsize = out - startout;
7257 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007258 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007260 /* (in - startin) <= size and size is an int */
7261 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007262
7263error:
7264 Py_XDECREF(encoding_obj);
7265 Py_XDECREF(errorHandler);
7266 Py_XDECREF(exc);
7267 return ret;
7268}
7269
Victor Stinner3a50e702011-10-18 21:21:00 +02007270static PyObject *
7271decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007272 const char *s, Py_ssize_t size,
7273 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007274{
Victor Stinner76a31a62011-11-04 00:05:13 +01007275 PyObject *v = NULL;
7276 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007277
Victor Stinner3a50e702011-10-18 21:21:00 +02007278 if (code_page < 0) {
7279 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7280 return NULL;
7281 }
7282
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007283 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007284 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007285
Victor Stinner76a31a62011-11-04 00:05:13 +01007286 do
7287 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007288#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007289 if (size > INT_MAX) {
7290 chunk_size = INT_MAX;
7291 final = 0;
7292 done = 0;
7293 }
7294 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007295#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007296 {
7297 chunk_size = (int)size;
7298 final = (consumed == NULL);
7299 done = 1;
7300 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007301
Victor Stinner76a31a62011-11-04 00:05:13 +01007302 if (chunk_size == 0 && done) {
7303 if (v != NULL)
7304 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007305 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007306 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007307
Victor Stinner76a31a62011-11-04 00:05:13 +01007308 converted = decode_code_page_strict(code_page, &v,
7309 s, chunk_size);
7310 if (converted == -2)
7311 converted = decode_code_page_errors(code_page, &v,
7312 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007313 errors, final);
7314 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007315
7316 if (converted < 0) {
7317 Py_XDECREF(v);
7318 return NULL;
7319 }
7320
7321 if (consumed)
7322 *consumed += converted;
7323
7324 s += converted;
7325 size -= converted;
7326 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007327
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007328 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007329}
7330
Alexander Belopolsky40018472011-02-26 01:02:56 +00007331PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007332PyUnicode_DecodeCodePageStateful(int code_page,
7333 const char *s,
7334 Py_ssize_t size,
7335 const char *errors,
7336 Py_ssize_t *consumed)
7337{
7338 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7339}
7340
7341PyObject *
7342PyUnicode_DecodeMBCSStateful(const char *s,
7343 Py_ssize_t size,
7344 const char *errors,
7345 Py_ssize_t *consumed)
7346{
7347 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7348}
7349
7350PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007351PyUnicode_DecodeMBCS(const char *s,
7352 Py_ssize_t size,
7353 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007354{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007355 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7356}
7357
Victor Stinner3a50e702011-10-18 21:21:00 +02007358static DWORD
7359encode_code_page_flags(UINT code_page, const char *errors)
7360{
7361 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007362 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007363 }
7364 else if (code_page == CP_UTF7) {
7365 /* CP_UTF7 only supports flags=0 */
7366 return 0;
7367 }
7368 else {
7369 if (errors != NULL && strcmp(errors, "replace") == 0)
7370 return 0;
7371 else
7372 return WC_NO_BEST_FIT_CHARS;
7373 }
7374}
7375
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007376/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007377 * Encode a Unicode string to a Windows code page into a byte string in strict
7378 * mode.
7379 *
7380 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007381 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007382 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007383static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007384encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007385 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007386 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007387{
Victor Stinner554f3f02010-06-16 23:33:54 +00007388 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007389 BOOL *pusedDefaultChar = &usedDefaultChar;
7390 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007391 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007392 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007393 const DWORD flags = encode_code_page_flags(code_page, NULL);
7394 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007395 /* Create a substring so that we can get the UTF-16 representation
7396 of just the slice under consideration. */
7397 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007398
Martin v. Löwis3d325192011-11-04 18:23:06 +01007399 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007400
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007402 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007403 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007404 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007405
Victor Stinner2fc507f2011-11-04 20:06:39 +01007406 substring = PyUnicode_Substring(unicode, offset, offset+len);
7407 if (substring == NULL)
7408 return -1;
7409 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7410 if (p == NULL) {
7411 Py_DECREF(substring);
7412 return -1;
7413 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007414 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007415
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007416 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007417 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007418 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007419 NULL, 0,
7420 NULL, pusedDefaultChar);
7421 if (outsize <= 0)
7422 goto error;
7423 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007424 if (pusedDefaultChar && *pusedDefaultChar) {
7425 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007427 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007428
Victor Stinner3a50e702011-10-18 21:21:00 +02007429 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007430 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007431 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007432 if (*outbytes == NULL) {
7433 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007434 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007435 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007436 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007437 }
7438 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007439 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 const Py_ssize_t n = PyBytes_Size(*outbytes);
7441 if (outsize > PY_SSIZE_T_MAX - n) {
7442 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007443 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007444 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007446 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7447 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007448 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007449 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007450 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007451 }
7452
7453 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007455 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 out, outsize,
7457 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007458 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 if (outsize <= 0)
7460 goto error;
7461 if (pusedDefaultChar && *pusedDefaultChar)
7462 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007463 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007464
Victor Stinner3a50e702011-10-18 21:21:00 +02007465error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007466 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007467 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7468 return -2;
7469 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007470 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007471}
7472
Victor Stinner3a50e702011-10-18 21:21:00 +02007473/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007474 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 * error handler.
7476 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007477 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007478 * -1 on other error.
7479 */
7480static int
7481encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007482 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007483 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007484{
Victor Stinner3a50e702011-10-18 21:21:00 +02007485 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007486 Py_ssize_t pos = unicode_offset;
7487 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007488 /* Ideally, we should get reason from FormatMessage. This is the Windows
7489 2000 English version of the message. */
7490 const char *reason = "invalid character";
7491 /* 4=maximum length of a UTF-8 sequence */
7492 char buffer[4];
7493 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7494 Py_ssize_t outsize;
7495 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007496 PyObject *errorHandler = NULL;
7497 PyObject *exc = NULL;
7498 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007499 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007500 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007501 PyObject *rep;
7502 int ret = -1;
7503
7504 assert(insize > 0);
7505
7506 encoding = code_page_name(code_page, &encoding_obj);
7507 if (encoding == NULL)
7508 return -1;
7509
7510 if (errors == NULL || strcmp(errors, "strict") == 0) {
7511 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7512 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007513 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007514 if (exc != NULL) {
7515 PyCodec_StrictErrors(exc);
7516 Py_DECREF(exc);
7517 }
7518 Py_XDECREF(encoding_obj);
7519 return -1;
7520 }
7521
7522 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7523 pusedDefaultChar = &usedDefaultChar;
7524 else
7525 pusedDefaultChar = NULL;
7526
7527 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7528 PyErr_NoMemory();
7529 goto error;
7530 }
7531 outsize = insize * Py_ARRAY_LENGTH(buffer);
7532
7533 if (*outbytes == NULL) {
7534 /* Create string object */
7535 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7536 if (*outbytes == NULL)
7537 goto error;
7538 out = PyBytes_AS_STRING(*outbytes);
7539 }
7540 else {
7541 /* Extend string object */
7542 Py_ssize_t n = PyBytes_Size(*outbytes);
7543 if (n > PY_SSIZE_T_MAX - outsize) {
7544 PyErr_NoMemory();
7545 goto error;
7546 }
7547 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7548 goto error;
7549 out = PyBytes_AS_STRING(*outbytes) + n;
7550 }
7551
7552 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007553 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007554 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007555 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7556 wchar_t chars[2];
7557 int charsize;
7558 if (ch < 0x10000) {
7559 chars[0] = (wchar_t)ch;
7560 charsize = 1;
7561 }
7562 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007563 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7564 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007565 charsize = 2;
7566 }
7567
Victor Stinner3a50e702011-10-18 21:21:00 +02007568 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007569 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007570 buffer, Py_ARRAY_LENGTH(buffer),
7571 NULL, pusedDefaultChar);
7572 if (outsize > 0) {
7573 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7574 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007575 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007576 memcpy(out, buffer, outsize);
7577 out += outsize;
7578 continue;
7579 }
7580 }
7581 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7582 PyErr_SetFromWindowsErr(0);
7583 goto error;
7584 }
7585
Victor Stinner3a50e702011-10-18 21:21:00 +02007586 rep = unicode_encode_call_errorhandler(
7587 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007588 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007589 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007590 if (rep == NULL)
7591 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007592 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007593
7594 if (PyBytes_Check(rep)) {
7595 outsize = PyBytes_GET_SIZE(rep);
7596 if (outsize != 1) {
7597 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7598 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7599 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7600 Py_DECREF(rep);
7601 goto error;
7602 }
7603 out = PyBytes_AS_STRING(*outbytes) + offset;
7604 }
7605 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7606 out += outsize;
7607 }
7608 else {
7609 Py_ssize_t i;
7610 enum PyUnicode_Kind kind;
7611 void *data;
7612
Benjamin Petersonbac79492012-01-14 13:34:47 -05007613 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007614 Py_DECREF(rep);
7615 goto error;
7616 }
7617
7618 outsize = PyUnicode_GET_LENGTH(rep);
7619 if (outsize != 1) {
7620 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7621 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7622 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7623 Py_DECREF(rep);
7624 goto error;
7625 }
7626 out = PyBytes_AS_STRING(*outbytes) + offset;
7627 }
7628 kind = PyUnicode_KIND(rep);
7629 data = PyUnicode_DATA(rep);
7630 for (i=0; i < outsize; i++) {
7631 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7632 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007633 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007634 encoding, unicode,
7635 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007636 "unable to encode error handler result to ASCII");
7637 Py_DECREF(rep);
7638 goto error;
7639 }
7640 *out = (unsigned char)ch;
7641 out++;
7642 }
7643 }
7644 Py_DECREF(rep);
7645 }
7646 /* write a NUL byte */
7647 *out = 0;
7648 outsize = out - PyBytes_AS_STRING(*outbytes);
7649 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7650 if (_PyBytes_Resize(outbytes, outsize) < 0)
7651 goto error;
7652 ret = 0;
7653
7654error:
7655 Py_XDECREF(encoding_obj);
7656 Py_XDECREF(errorHandler);
7657 Py_XDECREF(exc);
7658 return ret;
7659}
7660
Victor Stinner3a50e702011-10-18 21:21:00 +02007661static PyObject *
7662encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007663 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007664 const char *errors)
7665{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007666 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007667 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007668 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007669 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007670
Victor Stinner29dacf22015-01-26 16:41:32 +01007671 if (!PyUnicode_Check(unicode)) {
7672 PyErr_BadArgument();
7673 return NULL;
7674 }
7675
Benjamin Petersonbac79492012-01-14 13:34:47 -05007676 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007677 return NULL;
7678 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007679
Victor Stinner3a50e702011-10-18 21:21:00 +02007680 if (code_page < 0) {
7681 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7682 return NULL;
7683 }
7684
Martin v. Löwis3d325192011-11-04 18:23:06 +01007685 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007686 return PyBytes_FromStringAndSize(NULL, 0);
7687
Victor Stinner7581cef2011-11-03 22:32:33 +01007688 offset = 0;
7689 do
7690 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007691#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007692 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007693 chunks. */
7694 if (len > INT_MAX/2) {
7695 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007696 done = 0;
7697 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007698 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007699#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007700 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007701 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007702 done = 1;
7703 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007704
Victor Stinner76a31a62011-11-04 00:05:13 +01007705 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007706 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007707 errors);
7708 if (ret == -2)
7709 ret = encode_code_page_errors(code_page, &outbytes,
7710 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007711 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007712 if (ret < 0) {
7713 Py_XDECREF(outbytes);
7714 return NULL;
7715 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007716
Victor Stinner7581cef2011-11-03 22:32:33 +01007717 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007718 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007719 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007720
Victor Stinner3a50e702011-10-18 21:21:00 +02007721 return outbytes;
7722}
7723
7724PyObject *
7725PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7726 Py_ssize_t size,
7727 const char *errors)
7728{
Victor Stinner7581cef2011-11-03 22:32:33 +01007729 PyObject *unicode, *res;
7730 unicode = PyUnicode_FromUnicode(p, size);
7731 if (unicode == NULL)
7732 return NULL;
7733 res = encode_code_page(CP_ACP, unicode, errors);
7734 Py_DECREF(unicode);
7735 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007736}
7737
7738PyObject *
7739PyUnicode_EncodeCodePage(int code_page,
7740 PyObject *unicode,
7741 const char *errors)
7742{
Victor Stinner7581cef2011-11-03 22:32:33 +01007743 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007744}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007745
Alexander Belopolsky40018472011-02-26 01:02:56 +00007746PyObject *
7747PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007748{
Victor Stinner7581cef2011-11-03 22:32:33 +01007749 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007750}
7751
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007752#undef NEED_RETRY
7753
Steve Dowercc16be82016-09-08 10:35:16 -07007754#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007755
Guido van Rossumd57fd912000-03-10 22:53:23 +00007756/* --- Character Mapping Codec -------------------------------------------- */
7757
Victor Stinnerfb161b12013-04-18 01:44:27 +02007758static int
7759charmap_decode_string(const char *s,
7760 Py_ssize_t size,
7761 PyObject *mapping,
7762 const char *errors,
7763 _PyUnicodeWriter *writer)
7764{
7765 const char *starts = s;
7766 const char *e;
7767 Py_ssize_t startinpos, endinpos;
7768 PyObject *errorHandler = NULL, *exc = NULL;
7769 Py_ssize_t maplen;
7770 enum PyUnicode_Kind mapkind;
7771 void *mapdata;
7772 Py_UCS4 x;
7773 unsigned char ch;
7774
7775 if (PyUnicode_READY(mapping) == -1)
7776 return -1;
7777
7778 maplen = PyUnicode_GET_LENGTH(mapping);
7779 mapdata = PyUnicode_DATA(mapping);
7780 mapkind = PyUnicode_KIND(mapping);
7781
7782 e = s + size;
7783
7784 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7785 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7786 * is disabled in encoding aliases, latin1 is preferred because
7787 * its implementation is faster. */
7788 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7789 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7790 Py_UCS4 maxchar = writer->maxchar;
7791
7792 assert (writer->kind == PyUnicode_1BYTE_KIND);
7793 while (s < e) {
7794 ch = *s;
7795 x = mapdata_ucs1[ch];
7796 if (x > maxchar) {
7797 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7798 goto onError;
7799 maxchar = writer->maxchar;
7800 outdata = (Py_UCS1 *)writer->data;
7801 }
7802 outdata[writer->pos] = x;
7803 writer->pos++;
7804 ++s;
7805 }
7806 return 0;
7807 }
7808
7809 while (s < e) {
7810 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7811 enum PyUnicode_Kind outkind = writer->kind;
7812 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7813 if (outkind == PyUnicode_1BYTE_KIND) {
7814 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7815 Py_UCS4 maxchar = writer->maxchar;
7816 while (s < e) {
7817 ch = *s;
7818 x = mapdata_ucs2[ch];
7819 if (x > maxchar)
7820 goto Error;
7821 outdata[writer->pos] = x;
7822 writer->pos++;
7823 ++s;
7824 }
7825 break;
7826 }
7827 else if (outkind == PyUnicode_2BYTE_KIND) {
7828 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7829 while (s < e) {
7830 ch = *s;
7831 x = mapdata_ucs2[ch];
7832 if (x == 0xFFFE)
7833 goto Error;
7834 outdata[writer->pos] = x;
7835 writer->pos++;
7836 ++s;
7837 }
7838 break;
7839 }
7840 }
7841 ch = *s;
7842
7843 if (ch < maplen)
7844 x = PyUnicode_READ(mapkind, mapdata, ch);
7845 else
7846 x = 0xfffe; /* invalid value */
7847Error:
7848 if (x == 0xfffe)
7849 {
7850 /* undefined mapping */
7851 startinpos = s-starts;
7852 endinpos = startinpos+1;
7853 if (unicode_decode_call_errorhandler_writer(
7854 errors, &errorHandler,
7855 "charmap", "character maps to <undefined>",
7856 &starts, &e, &startinpos, &endinpos, &exc, &s,
7857 writer)) {
7858 goto onError;
7859 }
7860 continue;
7861 }
7862
7863 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7864 goto onError;
7865 ++s;
7866 }
7867 Py_XDECREF(errorHandler);
7868 Py_XDECREF(exc);
7869 return 0;
7870
7871onError:
7872 Py_XDECREF(errorHandler);
7873 Py_XDECREF(exc);
7874 return -1;
7875}
7876
7877static int
7878charmap_decode_mapping(const char *s,
7879 Py_ssize_t size,
7880 PyObject *mapping,
7881 const char *errors,
7882 _PyUnicodeWriter *writer)
7883{
7884 const char *starts = s;
7885 const char *e;
7886 Py_ssize_t startinpos, endinpos;
7887 PyObject *errorHandler = NULL, *exc = NULL;
7888 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007889 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007890
7891 e = s + size;
7892
7893 while (s < e) {
7894 ch = *s;
7895
7896 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7897 key = PyLong_FromLong((long)ch);
7898 if (key == NULL)
7899 goto onError;
7900
7901 item = PyObject_GetItem(mapping, key);
7902 Py_DECREF(key);
7903 if (item == NULL) {
7904 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7905 /* No mapping found means: mapping is undefined. */
7906 PyErr_Clear();
7907 goto Undefined;
7908 } else
7909 goto onError;
7910 }
7911
7912 /* Apply mapping */
7913 if (item == Py_None)
7914 goto Undefined;
7915 if (PyLong_Check(item)) {
7916 long value = PyLong_AS_LONG(item);
7917 if (value == 0xFFFE)
7918 goto Undefined;
7919 if (value < 0 || value > MAX_UNICODE) {
7920 PyErr_Format(PyExc_TypeError,
7921 "character mapping must be in range(0x%lx)",
7922 (unsigned long)MAX_UNICODE + 1);
7923 goto onError;
7924 }
7925
7926 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7927 goto onError;
7928 }
7929 else if (PyUnicode_Check(item)) {
7930 if (PyUnicode_READY(item) == -1)
7931 goto onError;
7932 if (PyUnicode_GET_LENGTH(item) == 1) {
7933 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7934 if (value == 0xFFFE)
7935 goto Undefined;
7936 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7937 goto onError;
7938 }
7939 else {
7940 writer->overallocate = 1;
7941 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7942 goto onError;
7943 }
7944 }
7945 else {
7946 /* wrong return value */
7947 PyErr_SetString(PyExc_TypeError,
7948 "character mapping must return integer, None or str");
7949 goto onError;
7950 }
7951 Py_CLEAR(item);
7952 ++s;
7953 continue;
7954
7955Undefined:
7956 /* undefined mapping */
7957 Py_CLEAR(item);
7958 startinpos = s-starts;
7959 endinpos = startinpos+1;
7960 if (unicode_decode_call_errorhandler_writer(
7961 errors, &errorHandler,
7962 "charmap", "character maps to <undefined>",
7963 &starts, &e, &startinpos, &endinpos, &exc, &s,
7964 writer)) {
7965 goto onError;
7966 }
7967 }
7968 Py_XDECREF(errorHandler);
7969 Py_XDECREF(exc);
7970 return 0;
7971
7972onError:
7973 Py_XDECREF(item);
7974 Py_XDECREF(errorHandler);
7975 Py_XDECREF(exc);
7976 return -1;
7977}
7978
Alexander Belopolsky40018472011-02-26 01:02:56 +00007979PyObject *
7980PyUnicode_DecodeCharmap(const char *s,
7981 Py_ssize_t size,
7982 PyObject *mapping,
7983 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007984{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007985 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007986
Guido van Rossumd57fd912000-03-10 22:53:23 +00007987 /* Default to Latin-1 */
7988 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007989 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007990
Guido van Rossumd57fd912000-03-10 22:53:23 +00007991 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007992 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007993 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007994 writer.min_length = size;
7995 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007996 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007997
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007998 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007999 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8000 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008001 }
8002 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008003 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8004 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008005 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008006 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008007
Benjamin Peterson29060642009-01-31 22:14:21 +00008008 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008009 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008010 return NULL;
8011}
8012
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008013/* Charmap encoding: the lookup table */
8014
Alexander Belopolsky40018472011-02-26 01:02:56 +00008015struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 PyObject_HEAD
8017 unsigned char level1[32];
8018 int count2, count3;
8019 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020};
8021
8022static PyObject*
8023encoding_map_size(PyObject *obj, PyObject* args)
8024{
8025 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008026 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028}
8029
8030static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008031 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008032 PyDoc_STR("Return the size (in bytes) of this object") },
8033 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008034};
8035
8036static void
8037encoding_map_dealloc(PyObject* o)
8038{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008039 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008040}
8041
8042static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008043 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 "EncodingMap", /*tp_name*/
8045 sizeof(struct encoding_map), /*tp_basicsize*/
8046 0, /*tp_itemsize*/
8047 /* methods */
8048 encoding_map_dealloc, /*tp_dealloc*/
8049 0, /*tp_print*/
8050 0, /*tp_getattr*/
8051 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008052 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008053 0, /*tp_repr*/
8054 0, /*tp_as_number*/
8055 0, /*tp_as_sequence*/
8056 0, /*tp_as_mapping*/
8057 0, /*tp_hash*/
8058 0, /*tp_call*/
8059 0, /*tp_str*/
8060 0, /*tp_getattro*/
8061 0, /*tp_setattro*/
8062 0, /*tp_as_buffer*/
8063 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8064 0, /*tp_doc*/
8065 0, /*tp_traverse*/
8066 0, /*tp_clear*/
8067 0, /*tp_richcompare*/
8068 0, /*tp_weaklistoffset*/
8069 0, /*tp_iter*/
8070 0, /*tp_iternext*/
8071 encoding_map_methods, /*tp_methods*/
8072 0, /*tp_members*/
8073 0, /*tp_getset*/
8074 0, /*tp_base*/
8075 0, /*tp_dict*/
8076 0, /*tp_descr_get*/
8077 0, /*tp_descr_set*/
8078 0, /*tp_dictoffset*/
8079 0, /*tp_init*/
8080 0, /*tp_alloc*/
8081 0, /*tp_new*/
8082 0, /*tp_free*/
8083 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008084};
8085
8086PyObject*
8087PyUnicode_BuildEncodingMap(PyObject* string)
8088{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008089 PyObject *result;
8090 struct encoding_map *mresult;
8091 int i;
8092 int need_dict = 0;
8093 unsigned char level1[32];
8094 unsigned char level2[512];
8095 unsigned char *mlevel1, *mlevel2, *mlevel3;
8096 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008097 int kind;
8098 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008099 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008100 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008101
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008102 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008103 PyErr_BadArgument();
8104 return NULL;
8105 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008106 kind = PyUnicode_KIND(string);
8107 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008108 length = PyUnicode_GET_LENGTH(string);
8109 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008110 memset(level1, 0xFF, sizeof level1);
8111 memset(level2, 0xFF, sizeof level2);
8112
8113 /* If there isn't a one-to-one mapping of NULL to \0,
8114 or if there are non-BMP characters, we need to use
8115 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008116 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008117 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008118 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008119 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008120 ch = PyUnicode_READ(kind, data, i);
8121 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008122 need_dict = 1;
8123 break;
8124 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008125 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008126 /* unmapped character */
8127 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008128 l1 = ch >> 11;
8129 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008130 if (level1[l1] == 0xFF)
8131 level1[l1] = count2++;
8132 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008133 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 }
8135
8136 if (count2 >= 0xFF || count3 >= 0xFF)
8137 need_dict = 1;
8138
8139 if (need_dict) {
8140 PyObject *result = PyDict_New();
8141 PyObject *key, *value;
8142 if (!result)
8143 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008144 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008145 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008146 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008147 if (!key || !value)
8148 goto failed1;
8149 if (PyDict_SetItem(result, key, value) == -1)
8150 goto failed1;
8151 Py_DECREF(key);
8152 Py_DECREF(value);
8153 }
8154 return result;
8155 failed1:
8156 Py_XDECREF(key);
8157 Py_XDECREF(value);
8158 Py_DECREF(result);
8159 return NULL;
8160 }
8161
8162 /* Create a three-level trie */
8163 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8164 16*count2 + 128*count3 - 1);
8165 if (!result)
8166 return PyErr_NoMemory();
8167 PyObject_Init(result, &EncodingMapType);
8168 mresult = (struct encoding_map*)result;
8169 mresult->count2 = count2;
8170 mresult->count3 = count3;
8171 mlevel1 = mresult->level1;
8172 mlevel2 = mresult->level23;
8173 mlevel3 = mresult->level23 + 16*count2;
8174 memcpy(mlevel1, level1, 32);
8175 memset(mlevel2, 0xFF, 16*count2);
8176 memset(mlevel3, 0, 128*count3);
8177 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008178 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008179 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008180 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8181 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008182 /* unmapped character */
8183 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008184 o1 = ch>>11;
8185 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008186 i2 = 16*mlevel1[o1] + o2;
8187 if (mlevel2[i2] == 0xFF)
8188 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008189 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190 i3 = 128*mlevel2[i2] + o3;
8191 mlevel3[i3] = i;
8192 }
8193 return result;
8194}
8195
8196static int
Victor Stinner22168992011-11-20 17:09:18 +01008197encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008198{
8199 struct encoding_map *map = (struct encoding_map*)mapping;
8200 int l1 = c>>11;
8201 int l2 = (c>>7) & 0xF;
8202 int l3 = c & 0x7F;
8203 int i;
8204
Victor Stinner22168992011-11-20 17:09:18 +01008205 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008206 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008207 if (c == 0)
8208 return 0;
8209 /* level 1*/
8210 i = map->level1[l1];
8211 if (i == 0xFF) {
8212 return -1;
8213 }
8214 /* level 2*/
8215 i = map->level23[16*i+l2];
8216 if (i == 0xFF) {
8217 return -1;
8218 }
8219 /* level 3 */
8220 i = map->level23[16*map->count2 + 128*i + l3];
8221 if (i == 0) {
8222 return -1;
8223 }
8224 return i;
8225}
8226
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008227/* Lookup the character ch in the mapping. If the character
8228 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008229 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008230static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008231charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008232{
Christian Heimes217cfd12007-12-02 14:31:20 +00008233 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008234 PyObject *x;
8235
8236 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008238 x = PyObject_GetItem(mapping, w);
8239 Py_DECREF(w);
8240 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8242 /* No mapping found means: mapping is undefined. */
8243 PyErr_Clear();
8244 x = Py_None;
8245 Py_INCREF(x);
8246 return x;
8247 } else
8248 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008249 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008250 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008252 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 long value = PyLong_AS_LONG(x);
8254 if (value < 0 || value > 255) {
8255 PyErr_SetString(PyExc_TypeError,
8256 "character mapping must be in range(256)");
8257 Py_DECREF(x);
8258 return NULL;
8259 }
8260 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008261 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008262 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008264 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 /* wrong return value */
8266 PyErr_Format(PyExc_TypeError,
8267 "character mapping must return integer, bytes or None, not %.400s",
8268 x->ob_type->tp_name);
8269 Py_DECREF(x);
8270 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008271 }
8272}
8273
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008274static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008275charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008276{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008277 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8278 /* exponentially overallocate to minimize reallocations */
8279 if (requiredsize < 2*outsize)
8280 requiredsize = 2*outsize;
8281 if (_PyBytes_Resize(outobj, requiredsize))
8282 return -1;
8283 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008284}
8285
Benjamin Peterson14339b62009-01-31 16:36:08 +00008286typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008287 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008288} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008290 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008291 space is available. Return a new reference to the object that
8292 was put in the output buffer, or Py_None, if the mapping was undefined
8293 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008294 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008295static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008296charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008297 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008298{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008299 PyObject *rep;
8300 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008301 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008302
Christian Heimes90aa7642007-12-19 02:45:37 +00008303 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008304 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008305 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008306 if (res == -1)
8307 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008308 if (outsize<requiredsize)
8309 if (charmapencode_resize(outobj, outpos, requiredsize))
8310 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008311 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 outstart[(*outpos)++] = (char)res;
8313 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008314 }
8315
8316 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008319 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 Py_DECREF(rep);
8321 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008322 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 if (PyLong_Check(rep)) {
8324 Py_ssize_t requiredsize = *outpos+1;
8325 if (outsize<requiredsize)
8326 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8327 Py_DECREF(rep);
8328 return enc_EXCEPTION;
8329 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008330 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008331 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008332 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008333 else {
8334 const char *repchars = PyBytes_AS_STRING(rep);
8335 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8336 Py_ssize_t requiredsize = *outpos+repsize;
8337 if (outsize<requiredsize)
8338 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8339 Py_DECREF(rep);
8340 return enc_EXCEPTION;
8341 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008342 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008343 memcpy(outstart + *outpos, repchars, repsize);
8344 *outpos += repsize;
8345 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008347 Py_DECREF(rep);
8348 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008349}
8350
8351/* handle an error in PyUnicode_EncodeCharmap
8352 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008353static int
8354charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008355 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008357 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008358 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359{
8360 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008361 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008362 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008363 enum PyUnicode_Kind kind;
8364 void *data;
8365 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008366 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008367 Py_ssize_t collstartpos = *inpos;
8368 Py_ssize_t collendpos = *inpos+1;
8369 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008370 char *encoding = "charmap";
8371 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008372 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008373 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008374 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008375
Benjamin Petersonbac79492012-01-14 13:34:47 -05008376 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008377 return -1;
8378 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008379 /* find all unencodable characters */
8380 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008381 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008382 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008383 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008384 val = encoding_map_lookup(ch, mapping);
8385 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 break;
8387 ++collendpos;
8388 continue;
8389 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008390
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008391 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8392 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 if (rep==NULL)
8394 return -1;
8395 else if (rep!=Py_None) {
8396 Py_DECREF(rep);
8397 break;
8398 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008399 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401 }
8402 /* cache callback name lookup
8403 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008404 if (*error_handler == _Py_ERROR_UNKNOWN)
8405 *error_handler = get_error_handler(errors);
8406
8407 switch (*error_handler) {
8408 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008409 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008410 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008411
8412 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008413 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008414 x = charmapencode_output('?', mapping, res, respos);
8415 if (x==enc_EXCEPTION) {
8416 return -1;
8417 }
8418 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008419 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 return -1;
8421 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008422 }
8423 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008424 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008425 *inpos = collendpos;
8426 break;
Victor Stinner50149202015-09-22 00:26:54 +02008427
8428 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008429 /* generate replacement (temporarily (mis)uses p) */
8430 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008431 char buffer[2+29+1+1];
8432 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008433 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 for (cp = buffer; *cp; ++cp) {
8435 x = charmapencode_output(*cp, mapping, res, respos);
8436 if (x==enc_EXCEPTION)
8437 return -1;
8438 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008439 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 return -1;
8441 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008442 }
8443 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008444 *inpos = collendpos;
8445 break;
Victor Stinner50149202015-09-22 00:26:54 +02008446
Benjamin Peterson14339b62009-01-31 16:36:08 +00008447 default:
Victor Stinner50149202015-09-22 00:26:54 +02008448 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008449 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008451 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008453 if (PyBytes_Check(repunicode)) {
8454 /* Directly copy bytes result to output. */
8455 Py_ssize_t outsize = PyBytes_Size(*res);
8456 Py_ssize_t requiredsize;
8457 repsize = PyBytes_Size(repunicode);
8458 requiredsize = *respos + repsize;
8459 if (requiredsize > outsize)
8460 /* Make room for all additional bytes. */
8461 if (charmapencode_resize(res, respos, requiredsize)) {
8462 Py_DECREF(repunicode);
8463 return -1;
8464 }
8465 memcpy(PyBytes_AsString(*res) + *respos,
8466 PyBytes_AsString(repunicode), repsize);
8467 *respos += repsize;
8468 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008469 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008470 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008471 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008472 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008473 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008474 Py_DECREF(repunicode);
8475 return -1;
8476 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008477 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008478 data = PyUnicode_DATA(repunicode);
8479 kind = PyUnicode_KIND(repunicode);
8480 for (index = 0; index < repsize; index++) {
8481 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8482 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008484 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 return -1;
8486 }
8487 else if (x==enc_FAILED) {
8488 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008489 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008490 return -1;
8491 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008492 }
8493 *inpos = newpos;
8494 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008495 }
8496 return 0;
8497}
8498
Alexander Belopolsky40018472011-02-26 01:02:56 +00008499PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008500_PyUnicode_EncodeCharmap(PyObject *unicode,
8501 PyObject *mapping,
8502 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008503{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008504 /* output object */
8505 PyObject *res = NULL;
8506 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008507 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008508 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008509 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008510 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008511 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008512 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008513 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008514 void *data;
8515 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008516
Benjamin Petersonbac79492012-01-14 13:34:47 -05008517 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008518 return NULL;
8519 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008520 data = PyUnicode_DATA(unicode);
8521 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008522
Guido van Rossumd57fd912000-03-10 22:53:23 +00008523 /* Default to Latin-1 */
8524 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008525 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008526
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 /* allocate enough for a simple encoding without
8528 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008529 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008530 if (res == NULL)
8531 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008532 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008533 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008534
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008535 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008536 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008538 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 if (x==enc_EXCEPTION) /* error */
8540 goto onError;
8541 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008542 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008544 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 &res, &respos)) {
8546 goto onError;
8547 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008548 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008549 else
8550 /* done with this character => adjust input position */
8551 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008552 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008553
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008554 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008555 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008556 if (_PyBytes_Resize(&res, respos) < 0)
8557 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008558
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008559 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008560 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008561 return res;
8562
Benjamin Peterson29060642009-01-31 22:14:21 +00008563 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008564 Py_XDECREF(res);
8565 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008566 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008567 return NULL;
8568}
8569
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008570/* Deprecated */
8571PyObject *
8572PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8573 Py_ssize_t size,
8574 PyObject *mapping,
8575 const char *errors)
8576{
8577 PyObject *result;
8578 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8579 if (unicode == NULL)
8580 return NULL;
8581 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8582 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008583 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008584}
8585
Alexander Belopolsky40018472011-02-26 01:02:56 +00008586PyObject *
8587PyUnicode_AsCharmapString(PyObject *unicode,
8588 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008589{
8590 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008591 PyErr_BadArgument();
8592 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008593 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008594 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008595}
8596
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008597/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008598static void
8599make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008601 Py_ssize_t startpos, Py_ssize_t endpos,
8602 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008603{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008604 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008605 *exceptionObject = _PyUnicodeTranslateError_Create(
8606 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008607 }
8608 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008609 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8610 goto onError;
8611 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8612 goto onError;
8613 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8614 goto onError;
8615 return;
8616 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008617 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008618 }
8619}
8620
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008621/* error handling callback helper:
8622 build arguments, call the callback and check the arguments,
8623 put the result into newpos and return the replacement string, which
8624 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008625static PyObject *
8626unicode_translate_call_errorhandler(const char *errors,
8627 PyObject **errorHandler,
8628 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008630 Py_ssize_t startpos, Py_ssize_t endpos,
8631 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008632{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02008633 static const char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008634
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008635 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008636 PyObject *restuple;
8637 PyObject *resunicode;
8638
8639 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008641 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008643 }
8644
8645 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008646 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008647 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649
8650 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008651 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008652 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008654 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008655 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008656 Py_DECREF(restuple);
8657 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008658 }
8659 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008660 &resunicode, &i_newpos)) {
8661 Py_DECREF(restuple);
8662 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008663 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008664 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008666 else
8667 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008669 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008670 Py_DECREF(restuple);
8671 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008672 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008673 Py_INCREF(resunicode);
8674 Py_DECREF(restuple);
8675 return resunicode;
8676}
8677
8678/* Lookup the character ch in the mapping and put the result in result,
8679 which must be decrefed by the caller.
8680 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008681static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008682charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008683{
Christian Heimes217cfd12007-12-02 14:31:20 +00008684 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008685 PyObject *x;
8686
8687 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008689 x = PyObject_GetItem(mapping, w);
8690 Py_DECREF(w);
8691 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8693 /* No mapping found means: use 1:1 mapping. */
8694 PyErr_Clear();
8695 *result = NULL;
8696 return 0;
8697 } else
8698 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008699 }
8700 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008701 *result = x;
8702 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008703 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008704 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008706 if (value < 0 || value > MAX_UNICODE) {
8707 PyErr_Format(PyExc_ValueError,
8708 "character mapping must be in range(0x%x)",
8709 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 Py_DECREF(x);
8711 return -1;
8712 }
8713 *result = x;
8714 return 0;
8715 }
8716 else if (PyUnicode_Check(x)) {
8717 *result = x;
8718 return 0;
8719 }
8720 else {
8721 /* wrong return value */
8722 PyErr_SetString(PyExc_TypeError,
8723 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008724 Py_DECREF(x);
8725 return -1;
8726 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008727}
Victor Stinner1194ea02014-04-04 19:37:40 +02008728
8729/* lookup the character, write the result into the writer.
8730 Return 1 if the result was written into the writer, return 0 if the mapping
8731 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008732static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008733charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8734 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008735{
Victor Stinner1194ea02014-04-04 19:37:40 +02008736 PyObject *item;
8737
8738 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008739 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008740
8741 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008743 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008745 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008746 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008747 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008748
8749 if (item == Py_None) {
8750 Py_DECREF(item);
8751 return 0;
8752 }
8753
8754 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008755 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8756 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8757 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008758 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8759 Py_DECREF(item);
8760 return -1;
8761 }
8762 Py_DECREF(item);
8763 return 1;
8764 }
8765
8766 if (!PyUnicode_Check(item)) {
8767 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008769 }
8770
8771 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8772 Py_DECREF(item);
8773 return -1;
8774 }
8775
8776 Py_DECREF(item);
8777 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008778}
8779
Victor Stinner89a76ab2014-04-05 11:44:04 +02008780static int
8781unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8782 Py_UCS1 *translate)
8783{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008784 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008785 int ret = 0;
8786
Victor Stinner89a76ab2014-04-05 11:44:04 +02008787 if (charmaptranslate_lookup(ch, mapping, &item)) {
8788 return -1;
8789 }
8790
8791 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008792 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008793 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008794 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008795 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008796 /* not found => default to 1:1 mapping */
8797 translate[ch] = ch;
8798 return 1;
8799 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008800 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008801 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008802 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8803 used it */
8804 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008805 /* invalid character or character outside ASCII:
8806 skip the fast translate */
8807 goto exit;
8808 }
8809 translate[ch] = (Py_UCS1)replace;
8810 }
8811 else if (PyUnicode_Check(item)) {
8812 Py_UCS4 replace;
8813
8814 if (PyUnicode_READY(item) == -1) {
8815 Py_DECREF(item);
8816 return -1;
8817 }
8818 if (PyUnicode_GET_LENGTH(item) != 1)
8819 goto exit;
8820
8821 replace = PyUnicode_READ_CHAR(item, 0);
8822 if (replace > 127)
8823 goto exit;
8824 translate[ch] = (Py_UCS1)replace;
8825 }
8826 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008827 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008828 goto exit;
8829 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008830 ret = 1;
8831
Benjamin Peterson1365de72014-04-07 20:15:41 -04008832 exit:
8833 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008834 return ret;
8835}
8836
8837/* Fast path for ascii => ascii translation. Return 1 if the whole string
8838 was translated into writer, return 0 if the input string was partially
8839 translated into writer, raise an exception and return -1 on error. */
8840static int
8841unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008842 _PyUnicodeWriter *writer, int ignore,
8843 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008844{
Victor Stinner872b2912014-04-05 14:27:07 +02008845 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008846 Py_ssize_t len;
8847 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008848 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008849
Victor Stinner89a76ab2014-04-05 11:44:04 +02008850 len = PyUnicode_GET_LENGTH(input);
8851
Victor Stinner872b2912014-04-05 14:27:07 +02008852 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008853
8854 in = PyUnicode_1BYTE_DATA(input);
8855 end = in + len;
8856
8857 assert(PyUnicode_IS_ASCII(writer->buffer));
8858 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8859 out = PyUnicode_1BYTE_DATA(writer->buffer);
8860
Victor Stinner872b2912014-04-05 14:27:07 +02008861 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008862 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008863 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008864 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008865 int translate = unicode_fast_translate_lookup(mapping, ch,
8866 ascii_table);
8867 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008868 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008869 if (translate == 0)
8870 goto exit;
8871 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008872 }
Victor Stinner872b2912014-04-05 14:27:07 +02008873 if (ch2 == 0xfe) {
8874 if (ignore)
8875 continue;
8876 goto exit;
8877 }
8878 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008879 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008880 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008881 }
Victor Stinner872b2912014-04-05 14:27:07 +02008882 res = 1;
8883
8884exit:
8885 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008886 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008887 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008888}
8889
Victor Stinner3222da22015-10-01 22:07:32 +02008890static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008891_PyUnicode_TranslateCharmap(PyObject *input,
8892 PyObject *mapping,
8893 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008894{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008895 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008896 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008897 Py_ssize_t size, i;
8898 int kind;
8899 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008900 _PyUnicodeWriter writer;
8901 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008902 char *reason = "character maps to <undefined>";
8903 PyObject *errorHandler = NULL;
8904 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008905 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008906 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008907
Guido van Rossumd57fd912000-03-10 22:53:23 +00008908 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008909 PyErr_BadArgument();
8910 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008911 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008912
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008913 if (PyUnicode_READY(input) == -1)
8914 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008915 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008916 kind = PyUnicode_KIND(input);
8917 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008918
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008919 if (size == 0)
8920 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008921
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008922 /* allocate enough for a simple 1:1 translation without
8923 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008924 _PyUnicodeWriter_Init(&writer);
8925 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008926 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008927
Victor Stinner872b2912014-04-05 14:27:07 +02008928 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8929
Victor Stinner33798672016-03-01 21:59:58 +01008930 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008931 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008932 if (PyUnicode_IS_ASCII(input)) {
8933 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8934 if (res < 0) {
8935 _PyUnicodeWriter_Dealloc(&writer);
8936 return NULL;
8937 }
8938 if (res == 1)
8939 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008940 }
Victor Stinner33798672016-03-01 21:59:58 +01008941 else {
8942 i = 0;
8943 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008945 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008946 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008947 int translate;
8948 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8949 Py_ssize_t newpos;
8950 /* startpos for collecting untranslatable chars */
8951 Py_ssize_t collstart;
8952 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008953 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008954
Victor Stinner1194ea02014-04-04 19:37:40 +02008955 ch = PyUnicode_READ(kind, data, i);
8956 translate = charmaptranslate_output(ch, mapping, &writer);
8957 if (translate < 0)
8958 goto onError;
8959
8960 if (translate != 0) {
8961 /* it worked => adjust input pointer */
8962 ++i;
8963 continue;
8964 }
8965
8966 /* untranslatable character */
8967 collstart = i;
8968 collend = i+1;
8969
8970 /* find all untranslatable characters */
8971 while (collend < size) {
8972 PyObject *x;
8973 ch = PyUnicode_READ(kind, data, collend);
8974 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008975 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008976 Py_XDECREF(x);
8977 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008978 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008979 ++collend;
8980 }
8981
8982 if (ignore) {
8983 i = collend;
8984 }
8985 else {
8986 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8987 reason, input, &exc,
8988 collstart, collend, &newpos);
8989 if (repunicode == NULL)
8990 goto onError;
8991 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008992 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008993 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008994 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008995 Py_DECREF(repunicode);
8996 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008997 }
8998 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008999 Py_XDECREF(exc);
9000 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009001 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009002
Benjamin Peterson29060642009-01-31 22:14:21 +00009003 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009004 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009005 Py_XDECREF(exc);
9006 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009007 return NULL;
9008}
9009
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009010/* Deprecated. Use PyUnicode_Translate instead. */
9011PyObject *
9012PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9013 Py_ssize_t size,
9014 PyObject *mapping,
9015 const char *errors)
9016{
Christian Heimes5f520f42012-09-11 14:03:25 +02009017 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009018 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9019 if (!unicode)
9020 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009021 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9022 Py_DECREF(unicode);
9023 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009024}
9025
Alexander Belopolsky40018472011-02-26 01:02:56 +00009026PyObject *
9027PyUnicode_Translate(PyObject *str,
9028 PyObject *mapping,
9029 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009030{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009031 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009032 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009033 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009034}
Tim Petersced69f82003-09-16 20:30:58 +00009035
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009036static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009037fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009038{
9039 /* No need to call PyUnicode_READY(self) because this function is only
9040 called as a callback from fixup() which does it already. */
9041 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9042 const int kind = PyUnicode_KIND(self);
9043 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009044 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009045 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009046 Py_ssize_t i;
9047
9048 for (i = 0; i < len; ++i) {
9049 ch = PyUnicode_READ(kind, data, i);
9050 fixed = 0;
9051 if (ch > 127) {
9052 if (Py_UNICODE_ISSPACE(ch))
9053 fixed = ' ';
9054 else {
9055 const int decimal = Py_UNICODE_TODECIMAL(ch);
9056 if (decimal >= 0)
9057 fixed = '0' + decimal;
9058 }
9059 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009060 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009061 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009062 PyUnicode_WRITE(kind, data, i, fixed);
9063 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009064 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009065 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067 }
9068
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009069 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009070}
9071
9072PyObject *
9073_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9074{
9075 if (!PyUnicode_Check(unicode)) {
9076 PyErr_BadInternalCall();
9077 return NULL;
9078 }
9079 if (PyUnicode_READY(unicode) == -1)
9080 return NULL;
9081 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9082 /* If the string is already ASCII, just return the same string */
9083 Py_INCREF(unicode);
9084 return unicode;
9085 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009086 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009087}
9088
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009089PyObject *
9090PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9091 Py_ssize_t length)
9092{
Victor Stinnerf0124502011-11-21 23:12:56 +01009093 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009094 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009095 Py_UCS4 maxchar;
9096 enum PyUnicode_Kind kind;
9097 void *data;
9098
Victor Stinner99d7ad02012-02-22 13:37:39 +01009099 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009100 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009101 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009102 if (ch > 127) {
9103 int decimal = Py_UNICODE_TODECIMAL(ch);
9104 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009105 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009106 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009107 }
9108 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009109
9110 /* Copy to a new string */
9111 decimal = PyUnicode_New(length, maxchar);
9112 if (decimal == NULL)
9113 return decimal;
9114 kind = PyUnicode_KIND(decimal);
9115 data = PyUnicode_DATA(decimal);
9116 /* Iterate over code points */
9117 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009118 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009119 if (ch > 127) {
9120 int decimal = Py_UNICODE_TODECIMAL(ch);
9121 if (decimal >= 0)
9122 ch = '0' + decimal;
9123 }
9124 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009125 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009126 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009127}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009128/* --- Decimal Encoder ---------------------------------------------------- */
9129
Alexander Belopolsky40018472011-02-26 01:02:56 +00009130int
9131PyUnicode_EncodeDecimal(Py_UNICODE *s,
9132 Py_ssize_t length,
9133 char *output,
9134 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009135{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009136 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009137 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009138 enum PyUnicode_Kind kind;
9139 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009140
9141 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009142 PyErr_BadArgument();
9143 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009144 }
9145
Victor Stinner42bf7752011-11-21 22:52:58 +01009146 unicode = PyUnicode_FromUnicode(s, length);
9147 if (unicode == NULL)
9148 return -1;
9149
Benjamin Petersonbac79492012-01-14 13:34:47 -05009150 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009151 Py_DECREF(unicode);
9152 return -1;
9153 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009154 kind = PyUnicode_KIND(unicode);
9155 data = PyUnicode_DATA(unicode);
9156
Victor Stinnerb84d7232011-11-22 01:50:07 +01009157 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009158 PyObject *exc;
9159 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009160 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009161 Py_ssize_t startpos;
9162
9163 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009164
Benjamin Peterson29060642009-01-31 22:14:21 +00009165 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009166 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009167 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009168 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009169 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009170 decimal = Py_UNICODE_TODECIMAL(ch);
9171 if (decimal >= 0) {
9172 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009173 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009174 continue;
9175 }
9176 if (0 < ch && ch < 256) {
9177 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009178 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009179 continue;
9180 }
Victor Stinner6345be92011-11-25 20:09:01 +01009181
Victor Stinner42bf7752011-11-21 22:52:58 +01009182 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009183 exc = NULL;
9184 raise_encode_exception(&exc, "decimal", unicode,
9185 startpos, startpos+1,
9186 "invalid decimal Unicode string");
9187 Py_XDECREF(exc);
9188 Py_DECREF(unicode);
9189 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009190 }
9191 /* 0-terminate the output string */
9192 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009193 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009194 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009195}
9196
Guido van Rossumd57fd912000-03-10 22:53:23 +00009197/* --- Helpers ------------------------------------------------------------ */
9198
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009199/* helper macro to fixup start/end slice values */
9200#define ADJUST_INDICES(start, end, len) \
9201 if (end > len) \
9202 end = len; \
9203 else if (end < 0) { \
9204 end += len; \
9205 if (end < 0) \
9206 end = 0; \
9207 } \
9208 if (start < 0) { \
9209 start += len; \
9210 if (start < 0) \
9211 start = 0; \
9212 }
9213
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009214static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009215any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009216 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009217 Py_ssize_t end,
9218 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009220 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009221 void *buf1, *buf2;
9222 Py_ssize_t len1, len2, result;
9223
9224 kind1 = PyUnicode_KIND(s1);
9225 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009226 if (kind1 < kind2)
9227 return -1;
9228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009229 len1 = PyUnicode_GET_LENGTH(s1);
9230 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009231 ADJUST_INDICES(start, end, len1);
9232 if (end - start < len2)
9233 return -1;
9234
9235 buf1 = PyUnicode_DATA(s1);
9236 buf2 = PyUnicode_DATA(s2);
9237 if (len2 == 1) {
9238 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9239 result = findchar((const char *)buf1 + kind1*start,
9240 kind1, end - start, ch, direction);
9241 if (result == -1)
9242 return -1;
9243 else
9244 return start + result;
9245 }
9246
9247 if (kind2 != kind1) {
9248 buf2 = _PyUnicode_AsKind(s2, kind1);
9249 if (!buf2)
9250 return -2;
9251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009252
Victor Stinner794d5672011-10-10 03:21:36 +02009253 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009254 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009255 case PyUnicode_1BYTE_KIND:
9256 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9257 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9258 else
9259 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9260 break;
9261 case PyUnicode_2BYTE_KIND:
9262 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9263 break;
9264 case PyUnicode_4BYTE_KIND:
9265 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9266 break;
9267 default:
9268 assert(0); result = -2;
9269 }
9270 }
9271 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009272 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009273 case PyUnicode_1BYTE_KIND:
9274 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9275 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9276 else
9277 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9278 break;
9279 case PyUnicode_2BYTE_KIND:
9280 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9281 break;
9282 case PyUnicode_4BYTE_KIND:
9283 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9284 break;
9285 default:
9286 assert(0); result = -2;
9287 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 }
9289
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009290 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009291 PyMem_Free(buf2);
9292
9293 return result;
9294}
9295
9296Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009297_PyUnicode_InsertThousandsGrouping(
9298 PyObject *unicode, Py_ssize_t index,
9299 Py_ssize_t n_buffer,
9300 void *digits, Py_ssize_t n_digits,
9301 Py_ssize_t min_width,
9302 const char *grouping, PyObject *thousands_sep,
9303 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009304{
Victor Stinner41a863c2012-02-24 00:37:51 +01009305 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009306 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009307 Py_ssize_t thousands_sep_len;
9308 Py_ssize_t len;
9309
9310 if (unicode != NULL) {
9311 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009312 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009313 }
9314 else {
9315 kind = PyUnicode_1BYTE_KIND;
9316 data = NULL;
9317 }
9318 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9319 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9320 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9321 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009322 if (thousands_sep_kind < kind) {
9323 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9324 if (!thousands_sep_data)
9325 return -1;
9326 }
9327 else {
9328 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9329 if (!data)
9330 return -1;
9331 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009332 }
9333
Benjamin Petersonead6b532011-12-20 17:23:42 -06009334 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009336 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009337 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009338 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009339 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009340 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009341 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009342 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009343 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009344 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009345 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009346 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009347 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009348 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009349 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009350 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009351 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009352 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009354 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009355 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009356 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009357 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009358 break;
9359 default:
9360 assert(0);
9361 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009362 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009363 if (unicode != NULL && thousands_sep_kind != kind) {
9364 if (thousands_sep_kind < kind)
9365 PyMem_Free(thousands_sep_data);
9366 else
9367 PyMem_Free(data);
9368 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009369 if (unicode == NULL) {
9370 *maxchar = 127;
9371 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009372 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009373 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009374 }
9375 }
9376 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377}
9378
9379
Alexander Belopolsky40018472011-02-26 01:02:56 +00009380Py_ssize_t
9381PyUnicode_Count(PyObject *str,
9382 PyObject *substr,
9383 Py_ssize_t start,
9384 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009385{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009386 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009387 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388 void *buf1 = NULL, *buf2 = NULL;
9389 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009390
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009391 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009392 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009393
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009394 kind1 = PyUnicode_KIND(str);
9395 kind2 = PyUnicode_KIND(substr);
9396 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009397 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009398
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009399 len1 = PyUnicode_GET_LENGTH(str);
9400 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009401 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009402 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009403 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009404
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009405 buf1 = PyUnicode_DATA(str);
9406 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009407 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009408 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009409 if (!buf2)
9410 goto onError;
9411 }
9412
9413 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009415 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009416 result = asciilib_count(
9417 ((Py_UCS1*)buf1) + start, end - start,
9418 buf2, len2, PY_SSIZE_T_MAX
9419 );
9420 else
9421 result = ucs1lib_count(
9422 ((Py_UCS1*)buf1) + start, end - start,
9423 buf2, len2, PY_SSIZE_T_MAX
9424 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 break;
9426 case PyUnicode_2BYTE_KIND:
9427 result = ucs2lib_count(
9428 ((Py_UCS2*)buf1) + start, end - start,
9429 buf2, len2, PY_SSIZE_T_MAX
9430 );
9431 break;
9432 case PyUnicode_4BYTE_KIND:
9433 result = ucs4lib_count(
9434 ((Py_UCS4*)buf1) + start, end - start,
9435 buf2, len2, PY_SSIZE_T_MAX
9436 );
9437 break;
9438 default:
9439 assert(0); result = 0;
9440 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009441
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009442 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 PyMem_Free(buf2);
9444
Guido van Rossumd57fd912000-03-10 22:53:23 +00009445 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009447 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009448 PyMem_Free(buf2);
9449 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009450}
9451
Alexander Belopolsky40018472011-02-26 01:02:56 +00009452Py_ssize_t
9453PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009454 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009455 Py_ssize_t start,
9456 Py_ssize_t end,
9457 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009458{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009459 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009460 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009461
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009462 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009463}
9464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465Py_ssize_t
9466PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9467 Py_ssize_t start, Py_ssize_t end,
9468 int direction)
9469{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009471 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472 if (PyUnicode_READY(str) == -1)
9473 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009474 if (start < 0 || end < 0) {
9475 PyErr_SetString(PyExc_IndexError, "string index out of range");
9476 return -2;
9477 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009478 if (end > PyUnicode_GET_LENGTH(str))
9479 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009480 if (start >= end)
9481 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009482 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009483 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9484 kind, end-start, ch, direction);
9485 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009487 else
9488 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009489}
9490
Alexander Belopolsky40018472011-02-26 01:02:56 +00009491static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009492tailmatch(PyObject *self,
9493 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009494 Py_ssize_t start,
9495 Py_ssize_t end,
9496 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498 int kind_self;
9499 int kind_sub;
9500 void *data_self;
9501 void *data_sub;
9502 Py_ssize_t offset;
9503 Py_ssize_t i;
9504 Py_ssize_t end_sub;
9505
9506 if (PyUnicode_READY(self) == -1 ||
9507 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009508 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009510 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9511 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009512 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009513 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009514
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009515 if (PyUnicode_GET_LENGTH(substring) == 0)
9516 return 1;
9517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518 kind_self = PyUnicode_KIND(self);
9519 data_self = PyUnicode_DATA(self);
9520 kind_sub = PyUnicode_KIND(substring);
9521 data_sub = PyUnicode_DATA(substring);
9522 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9523
9524 if (direction > 0)
9525 offset = end;
9526 else
9527 offset = start;
9528
9529 if (PyUnicode_READ(kind_self, data_self, offset) ==
9530 PyUnicode_READ(kind_sub, data_sub, 0) &&
9531 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9532 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9533 /* If both are of the same kind, memcmp is sufficient */
9534 if (kind_self == kind_sub) {
9535 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009536 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009537 data_sub,
9538 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009539 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009540 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009541 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542 else {
9543 /* We do not need to compare 0 and len(substring)-1 because
9544 the if statement above ensured already that they are equal
9545 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 for (i = 1; i < end_sub; ++i) {
9547 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9548 PyUnicode_READ(kind_sub, data_sub, i))
9549 return 0;
9550 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009551 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009552 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009553 }
9554
9555 return 0;
9556}
9557
Alexander Belopolsky40018472011-02-26 01:02:56 +00009558Py_ssize_t
9559PyUnicode_Tailmatch(PyObject *str,
9560 PyObject *substr,
9561 Py_ssize_t start,
9562 Py_ssize_t end,
9563 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009565 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009566 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009567
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009568 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009569}
9570
Guido van Rossumd57fd912000-03-10 22:53:23 +00009571/* Apply fixfct filter to the Unicode object self and return a
9572 reference to the modified object */
9573
Alexander Belopolsky40018472011-02-26 01:02:56 +00009574static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009575fixup(PyObject *self,
9576 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009577{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009578 PyObject *u;
9579 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009580 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009581
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009582 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009584 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009585 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009586
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587 /* fix functions return the new maximum character in a string,
9588 if the kind of the resulting unicode object does not change,
9589 everything is fine. Otherwise we need to change the string kind
9590 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009591 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009592
9593 if (maxchar_new == 0) {
9594 /* no changes */;
9595 if (PyUnicode_CheckExact(self)) {
9596 Py_DECREF(u);
9597 Py_INCREF(self);
9598 return self;
9599 }
9600 else
9601 return u;
9602 }
9603
Victor Stinnere6abb482012-05-02 01:15:40 +02009604 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605
Victor Stinnereaab6042011-12-11 22:22:39 +01009606 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009607 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009608
9609 /* In case the maximum character changed, we need to
9610 convert the string to the new category. */
9611 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9612 if (v == NULL) {
9613 Py_DECREF(u);
9614 return NULL;
9615 }
9616 if (maxchar_new > maxchar_old) {
9617 /* If the maxchar increased so that the kind changed, not all
9618 characters are representable anymore and we need to fix the
9619 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009620 _PyUnicode_FastCopyCharacters(v, 0,
9621 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009622 maxchar_old = fixfct(v);
9623 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009624 }
9625 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009626 _PyUnicode_FastCopyCharacters(v, 0,
9627 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009628 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009629 Py_DECREF(u);
9630 assert(_PyUnicode_CheckConsistency(v, 1));
9631 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009632}
9633
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009634static PyObject *
9635ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009636{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009637 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9638 char *resdata, *data = PyUnicode_DATA(self);
9639 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009640
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009641 res = PyUnicode_New(len, 127);
9642 if (res == NULL)
9643 return NULL;
9644 resdata = PyUnicode_DATA(res);
9645 if (lower)
9646 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009647 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009648 _Py_bytes_upper(resdata, data, len);
9649 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650}
9651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009652static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009653handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009655 Py_ssize_t j;
9656 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009657 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009658 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009659
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009660 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9661
9662 where ! is a negation and \p{xxx} is a character with property xxx.
9663 */
9664 for (j = i - 1; j >= 0; j--) {
9665 c = PyUnicode_READ(kind, data, j);
9666 if (!_PyUnicode_IsCaseIgnorable(c))
9667 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009669 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9670 if (final_sigma) {
9671 for (j = i + 1; j < length; j++) {
9672 c = PyUnicode_READ(kind, data, j);
9673 if (!_PyUnicode_IsCaseIgnorable(c))
9674 break;
9675 }
9676 final_sigma = j == length || !_PyUnicode_IsCased(c);
9677 }
9678 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009679}
9680
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009681static int
9682lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9683 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009684{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009685 /* Obscure special case. */
9686 if (c == 0x3A3) {
9687 mapped[0] = handle_capital_sigma(kind, data, length, i);
9688 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009689 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009690 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009691}
9692
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009693static Py_ssize_t
9694do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009695{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009696 Py_ssize_t i, k = 0;
9697 int n_res, j;
9698 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009699
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009700 c = PyUnicode_READ(kind, data, 0);
9701 n_res = _PyUnicode_ToUpperFull(c, mapped);
9702 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009703 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009704 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009705 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009706 for (i = 1; i < length; i++) {
9707 c = PyUnicode_READ(kind, data, i);
9708 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9709 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009710 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009711 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009712 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009713 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009714 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009715}
9716
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009717static Py_ssize_t
9718do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9719 Py_ssize_t i, k = 0;
9720
9721 for (i = 0; i < length; i++) {
9722 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9723 int n_res, j;
9724 if (Py_UNICODE_ISUPPER(c)) {
9725 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9726 }
9727 else if (Py_UNICODE_ISLOWER(c)) {
9728 n_res = _PyUnicode_ToUpperFull(c, mapped);
9729 }
9730 else {
9731 n_res = 1;
9732 mapped[0] = c;
9733 }
9734 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009735 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009736 res[k++] = mapped[j];
9737 }
9738 }
9739 return k;
9740}
9741
9742static Py_ssize_t
9743do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9744 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009745{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009746 Py_ssize_t i, k = 0;
9747
9748 for (i = 0; i < length; i++) {
9749 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9750 int n_res, j;
9751 if (lower)
9752 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9753 else
9754 n_res = _PyUnicode_ToUpperFull(c, mapped);
9755 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009756 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009757 res[k++] = mapped[j];
9758 }
9759 }
9760 return k;
9761}
9762
9763static Py_ssize_t
9764do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9765{
9766 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9767}
9768
9769static Py_ssize_t
9770do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9771{
9772 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9773}
9774
Benjamin Petersone51757f2012-01-12 21:10:29 -05009775static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009776do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9777{
9778 Py_ssize_t i, k = 0;
9779
9780 for (i = 0; i < length; i++) {
9781 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9782 Py_UCS4 mapped[3];
9783 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9784 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009785 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009786 res[k++] = mapped[j];
9787 }
9788 }
9789 return k;
9790}
9791
9792static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009793do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9794{
9795 Py_ssize_t i, k = 0;
9796 int previous_is_cased;
9797
9798 previous_is_cased = 0;
9799 for (i = 0; i < length; i++) {
9800 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9801 Py_UCS4 mapped[3];
9802 int n_res, j;
9803
9804 if (previous_is_cased)
9805 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9806 else
9807 n_res = _PyUnicode_ToTitleFull(c, mapped);
9808
9809 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009810 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009811 res[k++] = mapped[j];
9812 }
9813
9814 previous_is_cased = _PyUnicode_IsCased(c);
9815 }
9816 return k;
9817}
9818
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009819static PyObject *
9820case_operation(PyObject *self,
9821 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9822{
9823 PyObject *res = NULL;
9824 Py_ssize_t length, newlength = 0;
9825 int kind, outkind;
9826 void *data, *outdata;
9827 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9828
Benjamin Petersoneea48462012-01-16 14:28:50 -05009829 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009830
9831 kind = PyUnicode_KIND(self);
9832 data = PyUnicode_DATA(self);
9833 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009834 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009835 PyErr_SetString(PyExc_OverflowError, "string is too long");
9836 return NULL;
9837 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009838 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009839 if (tmp == NULL)
9840 return PyErr_NoMemory();
9841 newlength = perform(kind, data, length, tmp, &maxchar);
9842 res = PyUnicode_New(newlength, maxchar);
9843 if (res == NULL)
9844 goto leave;
9845 tmpend = tmp + newlength;
9846 outdata = PyUnicode_DATA(res);
9847 outkind = PyUnicode_KIND(res);
9848 switch (outkind) {
9849 case PyUnicode_1BYTE_KIND:
9850 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9851 break;
9852 case PyUnicode_2BYTE_KIND:
9853 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9854 break;
9855 case PyUnicode_4BYTE_KIND:
9856 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9857 break;
9858 default:
9859 assert(0);
9860 break;
9861 }
9862 leave:
9863 PyMem_FREE(tmp);
9864 return res;
9865}
9866
Tim Peters8ce9f162004-08-27 01:49:32 +00009867PyObject *
9868PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009869{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009870 PyObject *res;
9871 PyObject *fseq;
9872 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009873 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009874
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009875 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009876 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009877 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009878 }
9879
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009880 /* NOTE: the following code can't call back into Python code,
9881 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009882 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009883
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009884 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009885 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009886 res = _PyUnicode_JoinArray(separator, items, seqlen);
9887 Py_DECREF(fseq);
9888 return res;
9889}
9890
9891PyObject *
9892_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9893{
9894 PyObject *res = NULL; /* the result */
9895 PyObject *sep = NULL;
9896 Py_ssize_t seplen;
9897 PyObject *item;
9898 Py_ssize_t sz, i, res_offset;
9899 Py_UCS4 maxchar;
9900 Py_UCS4 item_maxchar;
9901 int use_memcpy;
9902 unsigned char *res_data = NULL, *sep_data = NULL;
9903 PyObject *last_obj;
9904 unsigned int kind = 0;
9905
Tim Peters05eba1f2004-08-27 21:32:02 +00009906 /* If empty sequence, return u"". */
9907 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009908 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009909 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009910
Tim Peters05eba1f2004-08-27 21:32:02 +00009911 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009912 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009913 if (seqlen == 1) {
9914 if (PyUnicode_CheckExact(items[0])) {
9915 res = items[0];
9916 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009917 return res;
9918 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009919 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009920 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009921 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009922 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009923 /* Set up sep and seplen */
9924 if (separator == NULL) {
9925 /* fall back to a blank space separator */
9926 sep = PyUnicode_FromOrdinal(' ');
9927 if (!sep)
9928 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009929 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009930 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009931 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009932 else {
9933 if (!PyUnicode_Check(separator)) {
9934 PyErr_Format(PyExc_TypeError,
9935 "separator: expected str instance,"
9936 " %.80s found",
9937 Py_TYPE(separator)->tp_name);
9938 goto onError;
9939 }
9940 if (PyUnicode_READY(separator))
9941 goto onError;
9942 sep = separator;
9943 seplen = PyUnicode_GET_LENGTH(separator);
9944 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9945 /* inc refcount to keep this code path symmetric with the
9946 above case of a blank separator */
9947 Py_INCREF(sep);
9948 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009949 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009950 }
9951
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009952 /* There are at least two things to join, or else we have a subclass
9953 * of str in the sequence.
9954 * Do a pre-pass to figure out the total amount of space we'll
9955 * need (sz), and see whether all argument are strings.
9956 */
9957 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009958#ifdef Py_DEBUG
9959 use_memcpy = 0;
9960#else
9961 use_memcpy = 1;
9962#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009963 for (i = 0; i < seqlen; i++) {
9964 const Py_ssize_t old_sz = sz;
9965 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009966 if (!PyUnicode_Check(item)) {
9967 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009968 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009969 " %.80s found",
9970 i, Py_TYPE(item)->tp_name);
9971 goto onError;
9972 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 if (PyUnicode_READY(item) == -1)
9974 goto onError;
9975 sz += PyUnicode_GET_LENGTH(item);
9976 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009977 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009978 if (i != 0)
9979 sz += seplen;
9980 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9981 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009982 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009983 goto onError;
9984 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009985 if (use_memcpy && last_obj != NULL) {
9986 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9987 use_memcpy = 0;
9988 }
9989 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009990 }
Tim Petersced69f82003-09-16 20:30:58 +00009991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009992 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009993 if (res == NULL)
9994 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009995
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009996 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009997#ifdef Py_DEBUG
9998 use_memcpy = 0;
9999#else
10000 if (use_memcpy) {
10001 res_data = PyUnicode_1BYTE_DATA(res);
10002 kind = PyUnicode_KIND(res);
10003 if (seplen != 0)
10004 sep_data = PyUnicode_1BYTE_DATA(sep);
10005 }
10006#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010007 if (use_memcpy) {
10008 for (i = 0; i < seqlen; ++i) {
10009 Py_ssize_t itemlen;
10010 item = items[i];
10011
10012 /* Copy item, and maybe the separator. */
10013 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010014 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010015 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010016 kind * seplen);
10017 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010018 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010019
10020 itemlen = PyUnicode_GET_LENGTH(item);
10021 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010022 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010023 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010024 kind * itemlen);
10025 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010026 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010027 }
10028 assert(res_data == PyUnicode_1BYTE_DATA(res)
10029 + kind * PyUnicode_GET_LENGTH(res));
10030 }
10031 else {
10032 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10033 Py_ssize_t itemlen;
10034 item = items[i];
10035
10036 /* Copy item, and maybe the separator. */
10037 if (i && seplen != 0) {
10038 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10039 res_offset += seplen;
10040 }
10041
10042 itemlen = PyUnicode_GET_LENGTH(item);
10043 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010044 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010045 res_offset += itemlen;
10046 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010047 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010048 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010049 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010050
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010052 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010054
Benjamin Peterson29060642009-01-31 22:14:21 +000010055 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010057 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010058 return NULL;
10059}
10060
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010061#define FILL(kind, data, value, start, length) \
10062 do { \
10063 Py_ssize_t i_ = 0; \
10064 assert(kind != PyUnicode_WCHAR_KIND); \
10065 switch ((kind)) { \
10066 case PyUnicode_1BYTE_KIND: { \
10067 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010068 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 break; \
10070 } \
10071 case PyUnicode_2BYTE_KIND: { \
10072 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10073 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10074 break; \
10075 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010076 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10078 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10079 break; \
10080 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010081 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082 } \
10083 } while (0)
10084
Victor Stinnerd3f08822012-05-29 12:57:52 +020010085void
10086_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10087 Py_UCS4 fill_char)
10088{
10089 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10090 const void *data = PyUnicode_DATA(unicode);
10091 assert(PyUnicode_IS_READY(unicode));
10092 assert(unicode_modifiable(unicode));
10093 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10094 assert(start >= 0);
10095 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10096 FILL(kind, data, fill_char, start, length);
10097}
10098
Victor Stinner3fe55312012-01-04 00:33:50 +010010099Py_ssize_t
10100PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10101 Py_UCS4 fill_char)
10102{
10103 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010104
10105 if (!PyUnicode_Check(unicode)) {
10106 PyErr_BadInternalCall();
10107 return -1;
10108 }
10109 if (PyUnicode_READY(unicode) == -1)
10110 return -1;
10111 if (unicode_check_modifiable(unicode))
10112 return -1;
10113
Victor Stinnerd3f08822012-05-29 12:57:52 +020010114 if (start < 0) {
10115 PyErr_SetString(PyExc_IndexError, "string index out of range");
10116 return -1;
10117 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010118 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10119 PyErr_SetString(PyExc_ValueError,
10120 "fill character is bigger than "
10121 "the string maximum character");
10122 return -1;
10123 }
10124
10125 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10126 length = Py_MIN(maxlen, length);
10127 if (length <= 0)
10128 return 0;
10129
Victor Stinnerd3f08822012-05-29 12:57:52 +020010130 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010131 return length;
10132}
10133
Victor Stinner9310abb2011-10-05 00:59:23 +020010134static PyObject *
10135pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010136 Py_ssize_t left,
10137 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010139{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 PyObject *u;
10141 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010142 int kind;
10143 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010144
10145 if (left < 0)
10146 left = 0;
10147 if (right < 0)
10148 right = 0;
10149
Victor Stinnerc4b49542011-12-11 22:44:26 +010010150 if (left == 0 && right == 0)
10151 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10154 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010155 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10156 return NULL;
10157 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010159 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010161 if (!u)
10162 return NULL;
10163
10164 kind = PyUnicode_KIND(u);
10165 data = PyUnicode_DATA(u);
10166 if (left)
10167 FILL(kind, data, fill, 0, left);
10168 if (right)
10169 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010170 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010171 assert(_PyUnicode_CheckConsistency(u, 1));
10172 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010173}
10174
Alexander Belopolsky40018472011-02-26 01:02:56 +000010175PyObject *
10176PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010177{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010178 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010179
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010180 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010181 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010182
Benjamin Petersonead6b532011-12-20 17:23:42 -060010183 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010185 if (PyUnicode_IS_ASCII(string))
10186 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010187 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010188 PyUnicode_GET_LENGTH(string), keepends);
10189 else
10190 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010191 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010192 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 break;
10194 case PyUnicode_2BYTE_KIND:
10195 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010196 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010197 PyUnicode_GET_LENGTH(string), keepends);
10198 break;
10199 case PyUnicode_4BYTE_KIND:
10200 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010201 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 PyUnicode_GET_LENGTH(string), keepends);
10203 break;
10204 default:
10205 assert(0);
10206 list = 0;
10207 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010208 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010209}
10210
Alexander Belopolsky40018472011-02-26 01:02:56 +000010211static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010212split(PyObject *self,
10213 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010214 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010215{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010216 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 void *buf1, *buf2;
10218 Py_ssize_t len1, len2;
10219 PyObject* out;
10220
Guido van Rossumd57fd912000-03-10 22:53:23 +000010221 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010222 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 if (PyUnicode_READY(self) == -1)
10225 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010228 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010230 if (PyUnicode_IS_ASCII(self))
10231 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010232 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010233 PyUnicode_GET_LENGTH(self), maxcount
10234 );
10235 else
10236 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010237 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010238 PyUnicode_GET_LENGTH(self), maxcount
10239 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 case PyUnicode_2BYTE_KIND:
10241 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010242 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 PyUnicode_GET_LENGTH(self), maxcount
10244 );
10245 case PyUnicode_4BYTE_KIND:
10246 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010247 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 PyUnicode_GET_LENGTH(self), maxcount
10249 );
10250 default:
10251 assert(0);
10252 return NULL;
10253 }
10254
10255 if (PyUnicode_READY(substring) == -1)
10256 return NULL;
10257
10258 kind1 = PyUnicode_KIND(self);
10259 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 len1 = PyUnicode_GET_LENGTH(self);
10261 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010262 if (kind1 < kind2 || len1 < len2) {
10263 out = PyList_New(1);
10264 if (out == NULL)
10265 return NULL;
10266 Py_INCREF(self);
10267 PyList_SET_ITEM(out, 0, self);
10268 return out;
10269 }
10270 buf1 = PyUnicode_DATA(self);
10271 buf2 = PyUnicode_DATA(substring);
10272 if (kind2 != kind1) {
10273 buf2 = _PyUnicode_AsKind(substring, kind1);
10274 if (!buf2)
10275 return NULL;
10276 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010278 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010280 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10281 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010282 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010283 else
10284 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010285 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 break;
10287 case PyUnicode_2BYTE_KIND:
10288 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010289 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 break;
10291 case PyUnicode_4BYTE_KIND:
10292 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010293 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 break;
10295 default:
10296 out = NULL;
10297 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010298 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 PyMem_Free(buf2);
10300 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301}
10302
Alexander Belopolsky40018472011-02-26 01:02:56 +000010303static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010304rsplit(PyObject *self,
10305 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010306 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010307{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010308 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 void *buf1, *buf2;
10310 Py_ssize_t len1, len2;
10311 PyObject* out;
10312
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010313 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010314 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010315
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 if (PyUnicode_READY(self) == -1)
10317 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010320 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010321 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010322 if (PyUnicode_IS_ASCII(self))
10323 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010324 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010325 PyUnicode_GET_LENGTH(self), maxcount
10326 );
10327 else
10328 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010329 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010330 PyUnicode_GET_LENGTH(self), maxcount
10331 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 case PyUnicode_2BYTE_KIND:
10333 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010334 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010335 PyUnicode_GET_LENGTH(self), maxcount
10336 );
10337 case PyUnicode_4BYTE_KIND:
10338 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010339 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340 PyUnicode_GET_LENGTH(self), maxcount
10341 );
10342 default:
10343 assert(0);
10344 return NULL;
10345 }
10346
10347 if (PyUnicode_READY(substring) == -1)
10348 return NULL;
10349
10350 kind1 = PyUnicode_KIND(self);
10351 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 len1 = PyUnicode_GET_LENGTH(self);
10353 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010354 if (kind1 < kind2 || len1 < len2) {
10355 out = PyList_New(1);
10356 if (out == NULL)
10357 return NULL;
10358 Py_INCREF(self);
10359 PyList_SET_ITEM(out, 0, self);
10360 return out;
10361 }
10362 buf1 = PyUnicode_DATA(self);
10363 buf2 = PyUnicode_DATA(substring);
10364 if (kind2 != kind1) {
10365 buf2 = _PyUnicode_AsKind(substring, kind1);
10366 if (!buf2)
10367 return NULL;
10368 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010370 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010372 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10373 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010374 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010375 else
10376 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010377 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 break;
10379 case PyUnicode_2BYTE_KIND:
10380 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010381 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 break;
10383 case PyUnicode_4BYTE_KIND:
10384 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010385 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 break;
10387 default:
10388 out = NULL;
10389 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010390 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 PyMem_Free(buf2);
10392 return out;
10393}
10394
10395static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010396anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10397 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010399 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010401 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10402 return asciilib_find(buf1, len1, buf2, len2, offset);
10403 else
10404 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 case PyUnicode_2BYTE_KIND:
10406 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10407 case PyUnicode_4BYTE_KIND:
10408 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10409 }
10410 assert(0);
10411 return -1;
10412}
10413
10414static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010415anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10416 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010418 switch (kind) {
10419 case PyUnicode_1BYTE_KIND:
10420 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10421 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10422 else
10423 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10424 case PyUnicode_2BYTE_KIND:
10425 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10426 case PyUnicode_4BYTE_KIND:
10427 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10428 }
10429 assert(0);
10430 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010431}
10432
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010433static void
10434replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10435 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10436{
10437 int kind = PyUnicode_KIND(u);
10438 void *data = PyUnicode_DATA(u);
10439 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10440 if (kind == PyUnicode_1BYTE_KIND) {
10441 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10442 (Py_UCS1 *)data + len,
10443 u1, u2, maxcount);
10444 }
10445 else if (kind == PyUnicode_2BYTE_KIND) {
10446 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10447 (Py_UCS2 *)data + len,
10448 u1, u2, maxcount);
10449 }
10450 else {
10451 assert(kind == PyUnicode_4BYTE_KIND);
10452 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10453 (Py_UCS4 *)data + len,
10454 u1, u2, maxcount);
10455 }
10456}
10457
Alexander Belopolsky40018472011-02-26 01:02:56 +000010458static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459replace(PyObject *self, PyObject *str1,
10460 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010462 PyObject *u;
10463 char *sbuf = PyUnicode_DATA(self);
10464 char *buf1 = PyUnicode_DATA(str1);
10465 char *buf2 = PyUnicode_DATA(str2);
10466 int srelease = 0, release1 = 0, release2 = 0;
10467 int skind = PyUnicode_KIND(self);
10468 int kind1 = PyUnicode_KIND(str1);
10469 int kind2 = PyUnicode_KIND(str2);
10470 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10471 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10472 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010473 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010474 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010475
10476 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010477 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010478 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010479 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010480
Victor Stinner59de0ee2011-10-07 10:01:28 +020010481 if (str1 == str2)
10482 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483
Victor Stinner49a0a212011-10-12 23:46:10 +020010484 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010485 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10486 if (maxchar < maxchar_str1)
10487 /* substring too wide to be present */
10488 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010489 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10490 /* Replacing str1 with str2 may cause a maxchar reduction in the
10491 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010492 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010493 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010496 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010498 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010500 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010501 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010502 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010503
Victor Stinner69ed0f42013-04-09 21:48:24 +020010504 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010505 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010506 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010507 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010508 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010510 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010512
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010513 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10514 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010515 }
10516 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 int rkind = skind;
10518 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010519 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010520
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 if (kind1 < rkind) {
10522 /* widen substring */
10523 buf1 = _PyUnicode_AsKind(str1, rkind);
10524 if (!buf1) goto error;
10525 release1 = 1;
10526 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010527 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010528 if (i < 0)
10529 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 if (rkind > kind2) {
10531 /* widen replacement */
10532 buf2 = _PyUnicode_AsKind(str2, rkind);
10533 if (!buf2) goto error;
10534 release2 = 1;
10535 }
10536 else if (rkind < kind2) {
10537 /* widen self and buf1 */
10538 rkind = kind2;
10539 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010540 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 sbuf = _PyUnicode_AsKind(self, rkind);
10542 if (!sbuf) goto error;
10543 srelease = 1;
10544 buf1 = _PyUnicode_AsKind(str1, rkind);
10545 if (!buf1) goto error;
10546 release1 = 1;
10547 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010548 u = PyUnicode_New(slen, maxchar);
10549 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010551 assert(PyUnicode_KIND(u) == rkind);
10552 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010553
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010554 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010555 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010556 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010558 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010560
10561 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010562 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010563 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010564 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010565 if (i == -1)
10566 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010567 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010568 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010569 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010571 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010572 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010573 }
10574 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010576 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 int rkind = skind;
10578 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010579
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010581 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 buf1 = _PyUnicode_AsKind(str1, rkind);
10583 if (!buf1) goto error;
10584 release1 = 1;
10585 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010586 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010587 if (n == 0)
10588 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010590 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 buf2 = _PyUnicode_AsKind(str2, rkind);
10592 if (!buf2) goto error;
10593 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010594 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010596 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 rkind = kind2;
10598 sbuf = _PyUnicode_AsKind(self, rkind);
10599 if (!sbuf) goto error;
10600 srelease = 1;
10601 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010602 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 buf1 = _PyUnicode_AsKind(str1, rkind);
10604 if (!buf1) goto error;
10605 release1 = 1;
10606 }
10607 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10608 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010609 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 PyErr_SetString(PyExc_OverflowError,
10611 "replace string is too long");
10612 goto error;
10613 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010614 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010615 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010616 _Py_INCREF_UNICODE_EMPTY();
10617 if (!unicode_empty)
10618 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010619 u = unicode_empty;
10620 goto done;
10621 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010622 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 PyErr_SetString(PyExc_OverflowError,
10624 "replace string is too long");
10625 goto error;
10626 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010627 u = PyUnicode_New(new_size, maxchar);
10628 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010630 assert(PyUnicode_KIND(u) == rkind);
10631 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010632 ires = i = 0;
10633 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010634 while (n-- > 0) {
10635 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010636 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010637 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010638 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010639 if (j == -1)
10640 break;
10641 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010642 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010643 memcpy(res + rkind * ires,
10644 sbuf + rkind * i,
10645 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010647 }
10648 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010650 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010652 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010656 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010658 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010659 memcpy(res + rkind * ires,
10660 sbuf + rkind * i,
10661 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010662 }
10663 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010664 /* interleave */
10665 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010666 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010667 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010668 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010670 if (--n <= 0)
10671 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010672 memcpy(res + rkind * ires,
10673 sbuf + rkind * i,
10674 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 ires++;
10676 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010677 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010678 memcpy(res + rkind * ires,
10679 sbuf + rkind * i,
10680 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010681 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010682 }
10683
10684 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010685 unicode_adjust_maxchar(&u);
10686 if (u == NULL)
10687 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010688 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010689
10690 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010691 if (srelease)
10692 PyMem_FREE(sbuf);
10693 if (release1)
10694 PyMem_FREE(buf1);
10695 if (release2)
10696 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010697 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010699
Benjamin Peterson29060642009-01-31 22:14:21 +000010700 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010701 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010702 if (srelease)
10703 PyMem_FREE(sbuf);
10704 if (release1)
10705 PyMem_FREE(buf1);
10706 if (release2)
10707 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010708 return unicode_result_unchanged(self);
10709
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010710 error:
10711 if (srelease && sbuf)
10712 PyMem_FREE(sbuf);
10713 if (release1 && buf1)
10714 PyMem_FREE(buf1);
10715 if (release2 && buf2)
10716 PyMem_FREE(buf2);
10717 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718}
10719
10720/* --- Unicode Object Methods --------------------------------------------- */
10721
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010722PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010723 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724\n\
10725Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010726characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010727
10728static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010729unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010730{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010731 if (PyUnicode_READY(self) == -1)
10732 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010733 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010734}
10735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010736PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010737 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010738\n\
10739Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010740have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010741
10742static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010743unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010745 if (PyUnicode_READY(self) == -1)
10746 return NULL;
10747 if (PyUnicode_GET_LENGTH(self) == 0)
10748 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010749 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750}
10751
Benjamin Petersond5890c82012-01-14 13:23:30 -050010752PyDoc_STRVAR(casefold__doc__,
10753 "S.casefold() -> str\n\
10754\n\
10755Return a version of S suitable for caseless comparisons.");
10756
10757static PyObject *
10758unicode_casefold(PyObject *self)
10759{
10760 if (PyUnicode_READY(self) == -1)
10761 return NULL;
10762 if (PyUnicode_IS_ASCII(self))
10763 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010764 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010765}
10766
10767
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010768/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010769
10770static int
10771convert_uc(PyObject *obj, void *addr)
10772{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010774
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010775 if (!PyUnicode_Check(obj)) {
10776 PyErr_Format(PyExc_TypeError,
10777 "The fill character must be a unicode character, "
10778 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010779 return 0;
10780 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010781 if (PyUnicode_READY(obj) < 0)
10782 return 0;
10783 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010784 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010785 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010786 return 0;
10787 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010788 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010789 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010790}
10791
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010792PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010793 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010794\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010795Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010796done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010797
10798static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010799unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010800{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010801 Py_ssize_t marg, left;
10802 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010803 Py_UCS4 fillchar = ' ';
10804
Victor Stinnere9a29352011-10-01 02:14:59 +020010805 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010807
Benjamin Petersonbac79492012-01-14 13:34:47 -050010808 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010809 return NULL;
10810
Victor Stinnerc4b49542011-12-11 22:44:26 +010010811 if (PyUnicode_GET_LENGTH(self) >= width)
10812 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813
Victor Stinnerc4b49542011-12-11 22:44:26 +010010814 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010815 left = marg / 2 + (marg & width & 1);
10816
Victor Stinner9310abb2011-10-05 00:59:23 +020010817 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818}
10819
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010820/* This function assumes that str1 and str2 are readied by the caller. */
10821
Marc-André Lemburge5034372000-08-08 08:04:29 +000010822static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010823unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010824{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010825#define COMPARE(TYPE1, TYPE2) \
10826 do { \
10827 TYPE1* p1 = (TYPE1 *)data1; \
10828 TYPE2* p2 = (TYPE2 *)data2; \
10829 TYPE1* end = p1 + len; \
10830 Py_UCS4 c1, c2; \
10831 for (; p1 != end; p1++, p2++) { \
10832 c1 = *p1; \
10833 c2 = *p2; \
10834 if (c1 != c2) \
10835 return (c1 < c2) ? -1 : 1; \
10836 } \
10837 } \
10838 while (0)
10839
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010840 int kind1, kind2;
10841 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010842 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010843
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010844 kind1 = PyUnicode_KIND(str1);
10845 kind2 = PyUnicode_KIND(str2);
10846 data1 = PyUnicode_DATA(str1);
10847 data2 = PyUnicode_DATA(str2);
10848 len1 = PyUnicode_GET_LENGTH(str1);
10849 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010850 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010851
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010852 switch(kind1) {
10853 case PyUnicode_1BYTE_KIND:
10854 {
10855 switch(kind2) {
10856 case PyUnicode_1BYTE_KIND:
10857 {
10858 int cmp = memcmp(data1, data2, len);
10859 /* normalize result of memcmp() into the range [-1; 1] */
10860 if (cmp < 0)
10861 return -1;
10862 if (cmp > 0)
10863 return 1;
10864 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010865 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010866 case PyUnicode_2BYTE_KIND:
10867 COMPARE(Py_UCS1, Py_UCS2);
10868 break;
10869 case PyUnicode_4BYTE_KIND:
10870 COMPARE(Py_UCS1, Py_UCS4);
10871 break;
10872 default:
10873 assert(0);
10874 }
10875 break;
10876 }
10877 case PyUnicode_2BYTE_KIND:
10878 {
10879 switch(kind2) {
10880 case PyUnicode_1BYTE_KIND:
10881 COMPARE(Py_UCS2, Py_UCS1);
10882 break;
10883 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010884 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010885 COMPARE(Py_UCS2, Py_UCS2);
10886 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010887 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010888 case PyUnicode_4BYTE_KIND:
10889 COMPARE(Py_UCS2, Py_UCS4);
10890 break;
10891 default:
10892 assert(0);
10893 }
10894 break;
10895 }
10896 case PyUnicode_4BYTE_KIND:
10897 {
10898 switch(kind2) {
10899 case PyUnicode_1BYTE_KIND:
10900 COMPARE(Py_UCS4, Py_UCS1);
10901 break;
10902 case PyUnicode_2BYTE_KIND:
10903 COMPARE(Py_UCS4, Py_UCS2);
10904 break;
10905 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010906 {
10907#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10908 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10909 /* normalize result of wmemcmp() into the range [-1; 1] */
10910 if (cmp < 0)
10911 return -1;
10912 if (cmp > 0)
10913 return 1;
10914#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010915 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010916#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010917 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010918 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010919 default:
10920 assert(0);
10921 }
10922 break;
10923 }
10924 default:
10925 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010926 }
10927
Victor Stinner770e19e2012-10-04 22:59:45 +020010928 if (len1 == len2)
10929 return 0;
10930 if (len1 < len2)
10931 return -1;
10932 else
10933 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010934
10935#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010936}
10937
Benjamin Peterson621b4302016-09-09 13:54:34 -070010938static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010939unicode_compare_eq(PyObject *str1, PyObject *str2)
10940{
10941 int kind;
10942 void *data1, *data2;
10943 Py_ssize_t len;
10944 int cmp;
10945
Victor Stinnere5567ad2012-10-23 02:48:49 +020010946 len = PyUnicode_GET_LENGTH(str1);
10947 if (PyUnicode_GET_LENGTH(str2) != len)
10948 return 0;
10949 kind = PyUnicode_KIND(str1);
10950 if (PyUnicode_KIND(str2) != kind)
10951 return 0;
10952 data1 = PyUnicode_DATA(str1);
10953 data2 = PyUnicode_DATA(str2);
10954
10955 cmp = memcmp(data1, data2, len * kind);
10956 return (cmp == 0);
10957}
10958
10959
Alexander Belopolsky40018472011-02-26 01:02:56 +000010960int
10961PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010963 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10964 if (PyUnicode_READY(left) == -1 ||
10965 PyUnicode_READY(right) == -1)
10966 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010967
10968 /* a string is equal to itself */
10969 if (left == right)
10970 return 0;
10971
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010972 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010973 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010974 PyErr_Format(PyExc_TypeError,
10975 "Can't compare %.100s and %.100s",
10976 left->ob_type->tp_name,
10977 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978 return -1;
10979}
10980
Martin v. Löwis5b222132007-06-10 09:51:05 +000010981int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010982_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10983{
10984 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10985 if (right_str == NULL)
10986 return -1;
10987 return PyUnicode_Compare(left, right_str);
10988}
10989
10990int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010991PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10992{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010993 Py_ssize_t i;
10994 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010995 Py_UCS4 chr;
10996
Victor Stinner910337b2011-10-03 03:20:16 +020010997 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010998 if (PyUnicode_READY(uni) == -1)
10999 return -1;
11000 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011001 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011002 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011003 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011004 size_t len, len2 = strlen(str);
11005 int cmp;
11006
11007 len = Py_MIN(len1, len2);
11008 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011009 if (cmp != 0) {
11010 if (cmp < 0)
11011 return -1;
11012 else
11013 return 1;
11014 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011015 if (len1 > len2)
11016 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011017 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011018 return -1; /* str is longer */
11019 return 0;
11020 }
11021 else {
11022 void *data = PyUnicode_DATA(uni);
11023 /* Compare Unicode string and source character set string */
11024 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011025 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011026 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11027 /* This check keeps Python strings that end in '\0' from comparing equal
11028 to C strings identical up to that point. */
11029 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11030 return 1; /* uni is longer */
11031 if (str[i])
11032 return -1; /* str is longer */
11033 return 0;
11034 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011035}
11036
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011037
Benjamin Peterson29060642009-01-31 22:14:21 +000011038#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011039 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011040
Alexander Belopolsky40018472011-02-26 01:02:56 +000011041PyObject *
11042PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011043{
11044 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011045 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011046
Victor Stinnere5567ad2012-10-23 02:48:49 +020011047 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11048 Py_RETURN_NOTIMPLEMENTED;
11049
11050 if (PyUnicode_READY(left) == -1 ||
11051 PyUnicode_READY(right) == -1)
11052 return NULL;
11053
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011054 if (left == right) {
11055 switch (op) {
11056 case Py_EQ:
11057 case Py_LE:
11058 case Py_GE:
11059 /* a string is equal to itself */
11060 v = Py_True;
11061 break;
11062 case Py_NE:
11063 case Py_LT:
11064 case Py_GT:
11065 v = Py_False;
11066 break;
11067 default:
11068 PyErr_BadArgument();
11069 return NULL;
11070 }
11071 }
11072 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011073 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011074 result ^= (op == Py_NE);
11075 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011076 }
11077 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011078 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011079
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011080 /* Convert the return value to a Boolean */
11081 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011082 case Py_LE:
11083 v = TEST_COND(result <= 0);
11084 break;
11085 case Py_GE:
11086 v = TEST_COND(result >= 0);
11087 break;
11088 case Py_LT:
11089 v = TEST_COND(result == -1);
11090 break;
11091 case Py_GT:
11092 v = TEST_COND(result == 1);
11093 break;
11094 default:
11095 PyErr_BadArgument();
11096 return NULL;
11097 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011098 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011099 Py_INCREF(v);
11100 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011101}
11102
Alexander Belopolsky40018472011-02-26 01:02:56 +000011103int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011104_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11105{
11106 return unicode_eq(aa, bb);
11107}
11108
11109int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011110PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011111{
Victor Stinner77282cb2013-04-14 19:22:47 +020011112 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011113 void *buf1, *buf2;
11114 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011115 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011116
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011117 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011118 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011119 "'in <string>' requires string as left operand, not %.100s",
11120 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011121 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011122 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011123 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011124 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011125 if (ensure_unicode(str) < 0)
11126 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011128 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011129 kind2 = PyUnicode_KIND(substr);
11130 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011131 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011132 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011133 len2 = PyUnicode_GET_LENGTH(substr);
11134 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011135 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011136 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011137 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011138 if (len2 == 1) {
11139 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11140 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011141 return result;
11142 }
11143 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011144 buf2 = _PyUnicode_AsKind(substr, kind1);
11145 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011146 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011147 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011148
Victor Stinner77282cb2013-04-14 19:22:47 +020011149 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150 case PyUnicode_1BYTE_KIND:
11151 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11152 break;
11153 case PyUnicode_2BYTE_KIND:
11154 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11155 break;
11156 case PyUnicode_4BYTE_KIND:
11157 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11158 break;
11159 default:
11160 result = -1;
11161 assert(0);
11162 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011163
Victor Stinner77282cb2013-04-14 19:22:47 +020011164 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165 PyMem_Free(buf2);
11166
Guido van Rossum403d68b2000-03-13 15:55:09 +000011167 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011168}
11169
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170/* Concat to string or Unicode object giving a new Unicode object. */
11171
Alexander Belopolsky40018472011-02-26 01:02:56 +000011172PyObject *
11173PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011175 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011176 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011177 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011178
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011179 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11180 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181
11182 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011183 if (left == unicode_empty)
11184 return PyUnicode_FromObject(right);
11185 if (right == unicode_empty)
11186 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011188 left_len = PyUnicode_GET_LENGTH(left);
11189 right_len = PyUnicode_GET_LENGTH(right);
11190 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011191 PyErr_SetString(PyExc_OverflowError,
11192 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011193 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011194 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011195 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011196
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011197 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11198 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011199 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011200
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011202 result = PyUnicode_New(new_len, maxchar);
11203 if (result == NULL)
11204 return NULL;
11205 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11206 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11207 assert(_PyUnicode_CheckConsistency(result, 1));
11208 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011209}
11210
Walter Dörwald1ab83302007-05-18 17:15:44 +000011211void
Victor Stinner23e56682011-10-03 03:54:37 +020011212PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011213{
Victor Stinner23e56682011-10-03 03:54:37 +020011214 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011215 Py_UCS4 maxchar, maxchar2;
11216 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011217
11218 if (p_left == NULL) {
11219 if (!PyErr_Occurred())
11220 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011221 return;
11222 }
Victor Stinner23e56682011-10-03 03:54:37 +020011223 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011224 if (right == NULL || left == NULL
11225 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011226 if (!PyErr_Occurred())
11227 PyErr_BadInternalCall();
11228 goto error;
11229 }
11230
Benjamin Petersonbac79492012-01-14 13:34:47 -050011231 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011232 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011233 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011234 goto error;
11235
Victor Stinner488fa492011-12-12 00:01:39 +010011236 /* Shortcuts */
11237 if (left == unicode_empty) {
11238 Py_DECREF(left);
11239 Py_INCREF(right);
11240 *p_left = right;
11241 return;
11242 }
11243 if (right == unicode_empty)
11244 return;
11245
11246 left_len = PyUnicode_GET_LENGTH(left);
11247 right_len = PyUnicode_GET_LENGTH(right);
11248 if (left_len > PY_SSIZE_T_MAX - right_len) {
11249 PyErr_SetString(PyExc_OverflowError,
11250 "strings are too large to concat");
11251 goto error;
11252 }
11253 new_len = left_len + right_len;
11254
11255 if (unicode_modifiable(left)
11256 && PyUnicode_CheckExact(right)
11257 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011258 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11259 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011260 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011261 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011262 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11263 {
11264 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011265 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011266 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011267
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011268 /* copy 'right' into the newly allocated area of 'left' */
11269 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011270 }
Victor Stinner488fa492011-12-12 00:01:39 +010011271 else {
11272 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11273 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011274 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011275
Victor Stinner488fa492011-12-12 00:01:39 +010011276 /* Concat the two Unicode strings */
11277 res = PyUnicode_New(new_len, maxchar);
11278 if (res == NULL)
11279 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011280 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11281 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011282 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011283 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011284 }
11285 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011286 return;
11287
11288error:
Victor Stinner488fa492011-12-12 00:01:39 +010011289 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011290}
11291
11292void
11293PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11294{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011295 PyUnicode_Append(pleft, right);
11296 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011297}
11298
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011299/*
11300Wraps stringlib_parse_args_finds() and additionally ensures that the
11301first argument is a unicode object.
11302*/
11303
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011304static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011305parse_args_finds_unicode(const char * function_name, PyObject *args,
11306 PyObject **substring,
11307 Py_ssize_t *start, Py_ssize_t *end)
11308{
11309 if(stringlib_parse_args_finds(function_name, args, substring,
11310 start, end)) {
11311 if (ensure_unicode(*substring) < 0)
11312 return 0;
11313 return 1;
11314 }
11315 return 0;
11316}
11317
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011318PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011319 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011321Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011322string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011323interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324
11325static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011326unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011328 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011329 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011330 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011332 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011333 void *buf1, *buf2;
11334 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011335
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011336 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011337 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011339 kind1 = PyUnicode_KIND(self);
11340 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011341 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011342 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011343
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011344 len1 = PyUnicode_GET_LENGTH(self);
11345 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011347 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011348 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011349
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011350 buf1 = PyUnicode_DATA(self);
11351 buf2 = PyUnicode_DATA(substring);
11352 if (kind2 != kind1) {
11353 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011354 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011355 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011356 }
11357 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011358 case PyUnicode_1BYTE_KIND:
11359 iresult = ucs1lib_count(
11360 ((Py_UCS1*)buf1) + start, end - start,
11361 buf2, len2, PY_SSIZE_T_MAX
11362 );
11363 break;
11364 case PyUnicode_2BYTE_KIND:
11365 iresult = ucs2lib_count(
11366 ((Py_UCS2*)buf1) + start, end - start,
11367 buf2, len2, PY_SSIZE_T_MAX
11368 );
11369 break;
11370 case PyUnicode_4BYTE_KIND:
11371 iresult = ucs4lib_count(
11372 ((Py_UCS4*)buf1) + start, end - start,
11373 buf2, len2, PY_SSIZE_T_MAX
11374 );
11375 break;
11376 default:
11377 assert(0); iresult = 0;
11378 }
11379
11380 result = PyLong_FromSsize_t(iresult);
11381
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011382 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011383 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385 return result;
11386}
11387
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011388PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011389 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011391Encode S using the codec registered for encoding. Default encoding\n\
11392is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011393handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011394a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11395'xmlcharrefreplace' as well as any other name registered with\n\
11396codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011397
11398static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011399unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011401 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402 char *encoding = NULL;
11403 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011404
Benjamin Peterson308d6372009-09-18 21:42:35 +000011405 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11406 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011408 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011409}
11410
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011411PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011412 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413\n\
11414Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011415If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416
11417static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011418unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011420 Py_ssize_t i, j, line_pos, src_len, incr;
11421 Py_UCS4 ch;
11422 PyObject *u;
11423 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011424 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011426 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011427 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428
Ezio Melotti745d54d2013-11-16 19:10:57 +020011429 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11430 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011431 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432
Antoine Pitrou22425222011-10-04 19:10:51 +020011433 if (PyUnicode_READY(self) == -1)
11434 return NULL;
11435
Thomas Wouters7e474022000-07-16 12:04:32 +000011436 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011437 src_len = PyUnicode_GET_LENGTH(self);
11438 i = j = line_pos = 0;
11439 kind = PyUnicode_KIND(self);
11440 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011441 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011442 for (; i < src_len; i++) {
11443 ch = PyUnicode_READ(kind, src_data, i);
11444 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011445 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011447 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011449 goto overflow;
11450 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011451 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011452 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011453 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011455 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011456 goto overflow;
11457 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011459 if (ch == '\n' || ch == '\r')
11460 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011461 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011462 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011463 if (!found)
11464 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011465
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011467 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468 if (!u)
11469 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011470 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471
Antoine Pitroue71d5742011-10-04 15:55:09 +020011472 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473
Antoine Pitroue71d5742011-10-04 15:55:09 +020011474 for (; i < src_len; i++) {
11475 ch = PyUnicode_READ(kind, src_data, i);
11476 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011477 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011478 incr = tabsize - (line_pos % tabsize);
11479 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011480 FILL(kind, dest_data, ' ', j, incr);
11481 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011482 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011483 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011485 line_pos++;
11486 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011487 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011488 if (ch == '\n' || ch == '\r')
11489 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011491 }
11492 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011493 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011494
Antoine Pitroue71d5742011-10-04 15:55:09 +020011495 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011496 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11497 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498}
11499
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011500PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011501 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502\n\
11503Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011504such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505arguments start and end are interpreted as in slice notation.\n\
11506\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011507Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508
11509static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011512 /* initialize variables to prevent gcc warning */
11513 PyObject *substring = NULL;
11514 Py_ssize_t start = 0;
11515 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011516 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011518 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011521 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011522 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011523
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011524 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011525
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011526 if (result == -2)
11527 return NULL;
11528
Christian Heimes217cfd12007-12-02 14:31:20 +000011529 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530}
11531
11532static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011533unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011535 void *data;
11536 enum PyUnicode_Kind kind;
11537 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011538
11539 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11540 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011541 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011542 }
11543 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11544 PyErr_SetString(PyExc_IndexError, "string index out of range");
11545 return NULL;
11546 }
11547 kind = PyUnicode_KIND(self);
11548 data = PyUnicode_DATA(self);
11549 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011550 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551}
11552
Guido van Rossumc2504932007-09-18 19:42:40 +000011553/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011554 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011555static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011556unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557{
Guido van Rossumc2504932007-09-18 19:42:40 +000011558 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011559 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011560
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011561#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011562 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011563#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011564 if (_PyUnicode_HASH(self) != -1)
11565 return _PyUnicode_HASH(self);
11566 if (PyUnicode_READY(self) == -1)
11567 return -1;
11568 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011569 /*
11570 We make the hash of the empty string be 0, rather than using
11571 (prefix ^ suffix), since this slightly obfuscates the hash secret
11572 */
11573 if (len == 0) {
11574 _PyUnicode_HASH(self) = 0;
11575 return 0;
11576 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011577 x = _Py_HashBytes(PyUnicode_DATA(self),
11578 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011579 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011580 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581}
11582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011583PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011584 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011586Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587
11588static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011589unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011591 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011592 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011593 PyObject *substring = NULL;
11594 Py_ssize_t start = 0;
11595 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011597 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011600 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011602
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011603 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011605 if (result == -2)
11606 return NULL;
11607
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608 if (result < 0) {
11609 PyErr_SetString(PyExc_ValueError, "substring not found");
11610 return NULL;
11611 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011612
Christian Heimes217cfd12007-12-02 14:31:20 +000011613 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614}
11615
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011616PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011617 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011619Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011620at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621
11622static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011623unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011625 Py_ssize_t i, length;
11626 int kind;
11627 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628 int cased;
11629
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630 if (PyUnicode_READY(self) == -1)
11631 return NULL;
11632 length = PyUnicode_GET_LENGTH(self);
11633 kind = PyUnicode_KIND(self);
11634 data = PyUnicode_DATA(self);
11635
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011637 if (length == 1)
11638 return PyBool_FromLong(
11639 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011641 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011642 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011643 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011644
Guido van Rossumd57fd912000-03-10 22:53:23 +000011645 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011646 for (i = 0; i < length; i++) {
11647 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011648
Benjamin Peterson29060642009-01-31 22:14:21 +000011649 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11650 return PyBool_FromLong(0);
11651 else if (!cased && Py_UNICODE_ISLOWER(ch))
11652 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011653 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011654 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011655}
11656
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011657PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011658 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011660Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011661at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662
11663static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011664unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011666 Py_ssize_t i, length;
11667 int kind;
11668 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011669 int cased;
11670
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011671 if (PyUnicode_READY(self) == -1)
11672 return NULL;
11673 length = PyUnicode_GET_LENGTH(self);
11674 kind = PyUnicode_KIND(self);
11675 data = PyUnicode_DATA(self);
11676
Guido van Rossumd57fd912000-03-10 22:53:23 +000011677 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011678 if (length == 1)
11679 return PyBool_FromLong(
11680 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011682 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011684 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011685
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011687 for (i = 0; i < length; i++) {
11688 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011689
Benjamin Peterson29060642009-01-31 22:14:21 +000011690 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11691 return PyBool_FromLong(0);
11692 else if (!cased && Py_UNICODE_ISUPPER(ch))
11693 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011695 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696}
11697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011698PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011699 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011701Return True if S is a titlecased string and there is at least one\n\
11702character in S, i.e. upper- and titlecase characters may only\n\
11703follow uncased characters and lowercase characters only cased ones.\n\
11704Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011705
11706static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011707unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011709 Py_ssize_t i, length;
11710 int kind;
11711 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712 int cased, previous_is_cased;
11713
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714 if (PyUnicode_READY(self) == -1)
11715 return NULL;
11716 length = PyUnicode_GET_LENGTH(self);
11717 kind = PyUnicode_KIND(self);
11718 data = PyUnicode_DATA(self);
11719
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011721 if (length == 1) {
11722 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11723 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11724 (Py_UNICODE_ISUPPER(ch) != 0));
11725 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011726
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011727 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011728 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011729 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011730
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731 cased = 0;
11732 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011733 for (i = 0; i < length; i++) {
11734 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011735
Benjamin Peterson29060642009-01-31 22:14:21 +000011736 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11737 if (previous_is_cased)
11738 return PyBool_FromLong(0);
11739 previous_is_cased = 1;
11740 cased = 1;
11741 }
11742 else if (Py_UNICODE_ISLOWER(ch)) {
11743 if (!previous_is_cased)
11744 return PyBool_FromLong(0);
11745 previous_is_cased = 1;
11746 cased = 1;
11747 }
11748 else
11749 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011751 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752}
11753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011754PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011755 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011757Return True if all characters in S are whitespace\n\
11758and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011759
11760static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011761unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763 Py_ssize_t i, length;
11764 int kind;
11765 void *data;
11766
11767 if (PyUnicode_READY(self) == -1)
11768 return NULL;
11769 length = PyUnicode_GET_LENGTH(self);
11770 kind = PyUnicode_KIND(self);
11771 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011772
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011774 if (length == 1)
11775 return PyBool_FromLong(
11776 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011778 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011780 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 for (i = 0; i < length; i++) {
11783 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011784 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011785 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011787 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788}
11789
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011790PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011791 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011792\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011793Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011794and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011795
11796static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011797unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011798{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 Py_ssize_t i, length;
11800 int kind;
11801 void *data;
11802
11803 if (PyUnicode_READY(self) == -1)
11804 return NULL;
11805 length = PyUnicode_GET_LENGTH(self);
11806 kind = PyUnicode_KIND(self);
11807 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011808
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011809 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 if (length == 1)
11811 return PyBool_FromLong(
11812 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011813
11814 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011816 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 for (i = 0; i < length; i++) {
11819 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011820 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011821 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011822 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011823}
11824
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011825PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011826 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011827\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011828Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011829and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011830
11831static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011832unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011833{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011834 int kind;
11835 void *data;
11836 Py_ssize_t len, i;
11837
11838 if (PyUnicode_READY(self) == -1)
11839 return NULL;
11840
11841 kind = PyUnicode_KIND(self);
11842 data = PyUnicode_DATA(self);
11843 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011844
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011845 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 if (len == 1) {
11847 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11848 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11849 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011850
11851 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011853 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011854
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011855 for (i = 0; i < len; i++) {
11856 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011857 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011858 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011859 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011860 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011861}
11862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011863PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011864 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011865\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011866Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011867False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868
11869static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011870unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011871{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011872 Py_ssize_t i, length;
11873 int kind;
11874 void *data;
11875
11876 if (PyUnicode_READY(self) == -1)
11877 return NULL;
11878 length = PyUnicode_GET_LENGTH(self);
11879 kind = PyUnicode_KIND(self);
11880 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011881
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 if (length == 1)
11884 return PyBool_FromLong(
11885 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011887 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011889 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011890
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011891 for (i = 0; i < length; i++) {
11892 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011893 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011895 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896}
11897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011898PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011899 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011901Return True if all characters in S are digits\n\
11902and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011903
11904static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011905unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 Py_ssize_t i, length;
11908 int kind;
11909 void *data;
11910
11911 if (PyUnicode_READY(self) == -1)
11912 return NULL;
11913 length = PyUnicode_GET_LENGTH(self);
11914 kind = PyUnicode_KIND(self);
11915 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 if (length == 1) {
11919 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11920 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11921 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011922
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011923 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011925 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011926
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011927 for (i = 0; i < length; i++) {
11928 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011929 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011931 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932}
11933
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011934PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011935 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011936\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011937Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011938False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939
11940static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011941unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011943 Py_ssize_t i, length;
11944 int kind;
11945 void *data;
11946
11947 if (PyUnicode_READY(self) == -1)
11948 return NULL;
11949 length = PyUnicode_GET_LENGTH(self);
11950 kind = PyUnicode_KIND(self);
11951 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011952
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 if (length == 1)
11955 return PyBool_FromLong(
11956 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011957
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011958 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011960 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011962 for (i = 0; i < length; i++) {
11963 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011964 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011965 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011966 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011967}
11968
Martin v. Löwis47383402007-08-15 07:32:56 +000011969int
11970PyUnicode_IsIdentifier(PyObject *self)
11971{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 int kind;
11973 void *data;
11974 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011975 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011976
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011977 if (PyUnicode_READY(self) == -1) {
11978 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011979 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 }
11981
11982 /* Special case for empty strings */
11983 if (PyUnicode_GET_LENGTH(self) == 0)
11984 return 0;
11985 kind = PyUnicode_KIND(self);
11986 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011987
11988 /* PEP 3131 says that the first character must be in
11989 XID_Start and subsequent characters in XID_Continue,
11990 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011991 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011992 letters, digits, underscore). However, given the current
11993 definition of XID_Start and XID_Continue, it is sufficient
11994 to check just for these, except that _ must be allowed
11995 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011997 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011998 return 0;
11999
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012000 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012003 return 1;
12004}
12005
12006PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012007 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012008\n\
12009Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012010to the language definition.\n\
12011\n\
12012Use keyword.iskeyword() to test for reserved identifiers\n\
12013such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012014
12015static PyObject*
12016unicode_isidentifier(PyObject *self)
12017{
12018 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12019}
12020
Georg Brandl559e5d72008-06-11 18:37:52 +000012021PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012022 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012023\n\
12024Return True if all characters in S are considered\n\
12025printable in repr() or S is empty, False otherwise.");
12026
12027static PyObject*
12028unicode_isprintable(PyObject *self)
12029{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012030 Py_ssize_t i, length;
12031 int kind;
12032 void *data;
12033
12034 if (PyUnicode_READY(self) == -1)
12035 return NULL;
12036 length = PyUnicode_GET_LENGTH(self);
12037 kind = PyUnicode_KIND(self);
12038 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012039
12040 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041 if (length == 1)
12042 return PyBool_FromLong(
12043 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045 for (i = 0; i < length; i++) {
12046 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012047 Py_RETURN_FALSE;
12048 }
12049 }
12050 Py_RETURN_TRUE;
12051}
12052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012053PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012054 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012055\n\
12056Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012057iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012058
12059static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012060unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012061{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012062 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012063}
12064
Martin v. Löwis18e16552006-02-15 17:27:45 +000012065static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012066unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012067{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 if (PyUnicode_READY(self) == -1)
12069 return -1;
12070 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012071}
12072
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012073PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012074 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012075\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012076Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012077done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012078
12079static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012080unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012081{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012082 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012083 Py_UCS4 fillchar = ' ';
12084
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012085 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086 return NULL;
12087
Benjamin Petersonbac79492012-01-14 13:34:47 -050012088 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012089 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090
Victor Stinnerc4b49542011-12-11 22:44:26 +010012091 if (PyUnicode_GET_LENGTH(self) >= width)
12092 return unicode_result_unchanged(self);
12093
12094 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095}
12096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012097PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012098 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012100Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101
12102static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012103unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012105 if (PyUnicode_READY(self) == -1)
12106 return NULL;
12107 if (PyUnicode_IS_ASCII(self))
12108 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012109 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110}
12111
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012112#define LEFTSTRIP 0
12113#define RIGHTSTRIP 1
12114#define BOTHSTRIP 2
12115
12116/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012117static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012118
12119#define STRIPNAME(i) (stripformat[i]+3)
12120
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012121/* externally visible for str.strip(unicode) */
12122PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012123_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012124{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125 void *data;
12126 int kind;
12127 Py_ssize_t i, j, len;
12128 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012129 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012131 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12132 return NULL;
12133
12134 kind = PyUnicode_KIND(self);
12135 data = PyUnicode_DATA(self);
12136 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012137 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012138 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12139 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012140 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012141
Benjamin Peterson14339b62009-01-31 16:36:08 +000012142 i = 0;
12143 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012144 while (i < len) {
12145 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12146 if (!BLOOM(sepmask, ch))
12147 break;
12148 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12149 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012150 i++;
12151 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012152 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012153
Benjamin Peterson14339b62009-01-31 16:36:08 +000012154 j = len;
12155 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012156 j--;
12157 while (j >= i) {
12158 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12159 if (!BLOOM(sepmask, ch))
12160 break;
12161 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12162 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012163 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012164 }
12165
Benjamin Peterson29060642009-01-31 22:14:21 +000012166 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012167 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012168
Victor Stinner7931d9a2011-11-04 00:22:48 +010012169 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170}
12171
12172PyObject*
12173PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12174{
12175 unsigned char *data;
12176 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012177 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012178
Victor Stinnerde636f32011-10-01 03:55:54 +020012179 if (PyUnicode_READY(self) == -1)
12180 return NULL;
12181
Victor Stinner684d5fd2012-05-03 02:32:34 +020012182 length = PyUnicode_GET_LENGTH(self);
12183 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012184
Victor Stinner684d5fd2012-05-03 02:32:34 +020012185 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012186 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012187
Victor Stinnerde636f32011-10-01 03:55:54 +020012188 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012189 PyErr_SetString(PyExc_IndexError, "string index out of range");
12190 return NULL;
12191 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012192 if (start >= length || end < start)
12193 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012194
Victor Stinner684d5fd2012-05-03 02:32:34 +020012195 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012196 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012197 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012198 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012199 }
12200 else {
12201 kind = PyUnicode_KIND(self);
12202 data = PyUnicode_1BYTE_DATA(self);
12203 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012204 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012205 length);
12206 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012207}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208
12209static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012210do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012211{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012212 Py_ssize_t len, i, j;
12213
12214 if (PyUnicode_READY(self) == -1)
12215 return NULL;
12216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012217 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012218
Victor Stinnercc7af722013-04-09 22:39:24 +020012219 if (PyUnicode_IS_ASCII(self)) {
12220 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12221
12222 i = 0;
12223 if (striptype != RIGHTSTRIP) {
12224 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012225 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012226 if (!_Py_ascii_whitespace[ch])
12227 break;
12228 i++;
12229 }
12230 }
12231
12232 j = len;
12233 if (striptype != LEFTSTRIP) {
12234 j--;
12235 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012236 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012237 if (!_Py_ascii_whitespace[ch])
12238 break;
12239 j--;
12240 }
12241 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012242 }
12243 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012244 else {
12245 int kind = PyUnicode_KIND(self);
12246 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012247
Victor Stinnercc7af722013-04-09 22:39:24 +020012248 i = 0;
12249 if (striptype != RIGHTSTRIP) {
12250 while (i < len) {
12251 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12252 if (!Py_UNICODE_ISSPACE(ch))
12253 break;
12254 i++;
12255 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012256 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012257
12258 j = len;
12259 if (striptype != LEFTSTRIP) {
12260 j--;
12261 while (j >= i) {
12262 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12263 if (!Py_UNICODE_ISSPACE(ch))
12264 break;
12265 j--;
12266 }
12267 j++;
12268 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012269 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012270
Victor Stinner7931d9a2011-11-04 00:22:48 +010012271 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272}
12273
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012274
12275static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012276do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012277{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012278 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012279
Serhiy Storchakac6792272013-10-19 21:03:34 +030012280 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012281 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012282
Benjamin Peterson14339b62009-01-31 16:36:08 +000012283 if (sep != NULL && sep != Py_None) {
12284 if (PyUnicode_Check(sep))
12285 return _PyUnicode_XStrip(self, striptype, sep);
12286 else {
12287 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012288 "%s arg must be None or str",
12289 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012290 return NULL;
12291 }
12292 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012293
Benjamin Peterson14339b62009-01-31 16:36:08 +000012294 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012295}
12296
12297
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012298PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012299 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012300\n\
12301Return a copy of the string S with leading and trailing\n\
12302whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012303If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012304
12305static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012306unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012307{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012308 if (PyTuple_GET_SIZE(args) == 0)
12309 return do_strip(self, BOTHSTRIP); /* Common case */
12310 else
12311 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012312}
12313
12314
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012315PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012316 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012317\n\
12318Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012319If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012320
12321static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012322unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012323{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012324 if (PyTuple_GET_SIZE(args) == 0)
12325 return do_strip(self, LEFTSTRIP); /* Common case */
12326 else
12327 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012328}
12329
12330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012331PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012332 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012333\n\
12334Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012335If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012336
12337static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012338unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012339{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012340 if (PyTuple_GET_SIZE(args) == 0)
12341 return do_strip(self, RIGHTSTRIP); /* Common case */
12342 else
12343 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012344}
12345
12346
Guido van Rossumd57fd912000-03-10 22:53:23 +000012347static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012348unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012349{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012350 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012351 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012352
Serhiy Storchaka05997252013-01-26 12:14:02 +020012353 if (len < 1)
12354 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012355
Victor Stinnerc4b49542011-12-11 22:44:26 +010012356 /* no repeat, return original string */
12357 if (len == 1)
12358 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012359
Benjamin Petersonbac79492012-01-14 13:34:47 -050012360 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 return NULL;
12362
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012363 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012364 PyErr_SetString(PyExc_OverflowError,
12365 "repeated string is too long");
12366 return NULL;
12367 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012368 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012369
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012370 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012371 if (!u)
12372 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012373 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012375 if (PyUnicode_GET_LENGTH(str) == 1) {
12376 const int kind = PyUnicode_KIND(str);
12377 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012378 if (kind == PyUnicode_1BYTE_KIND) {
12379 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012380 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012381 }
12382 else if (kind == PyUnicode_2BYTE_KIND) {
12383 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012384 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012385 ucs2[n] = fill_char;
12386 } else {
12387 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12388 assert(kind == PyUnicode_4BYTE_KIND);
12389 for (n = 0; n < len; ++n)
12390 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012391 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012392 }
12393 else {
12394 /* number of characters copied this far */
12395 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012396 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012397 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012398 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012399 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012400 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012402 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012403 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012404 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012405 }
12406
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012407 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012408 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012409}
12410
Alexander Belopolsky40018472011-02-26 01:02:56 +000012411PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012412PyUnicode_Replace(PyObject *str,
12413 PyObject *substr,
12414 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012415 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012416{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012417 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12418 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012419 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012420 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012421}
12422
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012423PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012424 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012425\n\
12426Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012427old replaced by new. If the optional argument count is\n\
12428given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012429
12430static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012431unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012432{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012433 PyObject *str1;
12434 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012435 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012436
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012437 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012438 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012439 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012440 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012441 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012442}
12443
Alexander Belopolsky40018472011-02-26 01:02:56 +000012444static PyObject *
12445unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012446{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012447 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 Py_ssize_t isize;
12449 Py_ssize_t osize, squote, dquote, i, o;
12450 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012451 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012452 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012453
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012454 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012455 return NULL;
12456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012457 isize = PyUnicode_GET_LENGTH(unicode);
12458 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012460 /* Compute length of output, quote characters, and
12461 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012462 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012463 max = 127;
12464 squote = dquote = 0;
12465 ikind = PyUnicode_KIND(unicode);
12466 for (i = 0; i < isize; i++) {
12467 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012468 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012469 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012470 case '\'': squote++; break;
12471 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012472 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012473 incr = 2;
12474 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012475 default:
12476 /* Fast-path ASCII */
12477 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012478 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012479 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012480 ;
12481 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012483 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012484 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012485 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012486 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012487 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012488 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012489 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012490 if (osize > PY_SSIZE_T_MAX - incr) {
12491 PyErr_SetString(PyExc_OverflowError,
12492 "string is too long to generate repr");
12493 return NULL;
12494 }
12495 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012496 }
12497
12498 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012499 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012500 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012501 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012502 if (dquote)
12503 /* Both squote and dquote present. Use squote,
12504 and escape them */
12505 osize += squote;
12506 else
12507 quote = '"';
12508 }
Victor Stinner55c08782013-04-14 18:45:39 +020012509 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012510
12511 repr = PyUnicode_New(osize, max);
12512 if (repr == NULL)
12513 return NULL;
12514 okind = PyUnicode_KIND(repr);
12515 odata = PyUnicode_DATA(repr);
12516
12517 PyUnicode_WRITE(okind, odata, 0, quote);
12518 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012519 if (unchanged) {
12520 _PyUnicode_FastCopyCharacters(repr, 1,
12521 unicode, 0,
12522 isize);
12523 }
12524 else {
12525 for (i = 0, o = 1; i < isize; i++) {
12526 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012527
Victor Stinner55c08782013-04-14 18:45:39 +020012528 /* Escape quotes and backslashes */
12529 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012530 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012531 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012532 continue;
12533 }
12534
12535 /* Map special whitespace to '\t', \n', '\r' */
12536 if (ch == '\t') {
12537 PyUnicode_WRITE(okind, odata, o++, '\\');
12538 PyUnicode_WRITE(okind, odata, o++, 't');
12539 }
12540 else if (ch == '\n') {
12541 PyUnicode_WRITE(okind, odata, o++, '\\');
12542 PyUnicode_WRITE(okind, odata, o++, 'n');
12543 }
12544 else if (ch == '\r') {
12545 PyUnicode_WRITE(okind, odata, o++, '\\');
12546 PyUnicode_WRITE(okind, odata, o++, 'r');
12547 }
12548
12549 /* Map non-printable US ASCII to '\xhh' */
12550 else if (ch < ' ' || ch == 0x7F) {
12551 PyUnicode_WRITE(okind, odata, o++, '\\');
12552 PyUnicode_WRITE(okind, odata, o++, 'x');
12553 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12554 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12555 }
12556
12557 /* Copy ASCII characters as-is */
12558 else if (ch < 0x7F) {
12559 PyUnicode_WRITE(okind, odata, o++, ch);
12560 }
12561
12562 /* Non-ASCII characters */
12563 else {
12564 /* Map Unicode whitespace and control characters
12565 (categories Z* and C* except ASCII space)
12566 */
12567 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12568 PyUnicode_WRITE(okind, odata, o++, '\\');
12569 /* Map 8-bit characters to '\xhh' */
12570 if (ch <= 0xff) {
12571 PyUnicode_WRITE(okind, odata, o++, 'x');
12572 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12573 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12574 }
12575 /* Map 16-bit characters to '\uxxxx' */
12576 else if (ch <= 0xffff) {
12577 PyUnicode_WRITE(okind, odata, o++, 'u');
12578 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12579 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12580 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12581 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12582 }
12583 /* Map 21-bit characters to '\U00xxxxxx' */
12584 else {
12585 PyUnicode_WRITE(okind, odata, o++, 'U');
12586 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12587 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12588 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12589 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12590 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12591 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12592 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12593 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12594 }
12595 }
12596 /* Copy characters as-is */
12597 else {
12598 PyUnicode_WRITE(okind, odata, o++, ch);
12599 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012600 }
12601 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012602 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012603 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012604 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012605 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606}
12607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012608PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012609 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610\n\
12611Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012612such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012613arguments start and end are interpreted as in slice notation.\n\
12614\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012615Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012616
12617static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012618unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012620 /* initialize variables to prevent gcc warning */
12621 PyObject *substring = NULL;
12622 Py_ssize_t start = 0;
12623 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012624 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012626 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012627 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012629 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012630 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012631
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012632 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 if (result == -2)
12635 return NULL;
12636
Christian Heimes217cfd12007-12-02 14:31:20 +000012637 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638}
12639
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012640PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012641 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012643Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644
12645static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012646unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012648 /* initialize variables to prevent gcc warning */
12649 PyObject *substring = NULL;
12650 Py_ssize_t start = 0;
12651 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012652 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012654 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012655 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012656
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012657 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012658 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012659
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012660 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012661
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012662 if (result == -2)
12663 return NULL;
12664
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665 if (result < 0) {
12666 PyErr_SetString(PyExc_ValueError, "substring not found");
12667 return NULL;
12668 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012669
Christian Heimes217cfd12007-12-02 14:31:20 +000012670 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012671}
12672
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012673PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012674 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012675\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012676Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012677done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678
12679static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012680unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012681{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012682 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012683 Py_UCS4 fillchar = ' ';
12684
Victor Stinnere9a29352011-10-01 02:14:59 +020012685 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012687
Benjamin Petersonbac79492012-01-14 13:34:47 -050012688 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689 return NULL;
12690
Victor Stinnerc4b49542011-12-11 22:44:26 +010012691 if (PyUnicode_GET_LENGTH(self) >= width)
12692 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012693
Victor Stinnerc4b49542011-12-11 22:44:26 +010012694 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695}
12696
Alexander Belopolsky40018472011-02-26 01:02:56 +000012697PyObject *
12698PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012700 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012701 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012703 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012704}
12705
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012706PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012707 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708\n\
12709Return a list of the words in S, using sep as the\n\
12710delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012711splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012712whitespace string is a separator and empty strings are\n\
12713removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714
12715static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012716unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012717{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012718 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012720 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012721
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012722 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12723 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724 return NULL;
12725
12726 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012727 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012728
12729 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012730 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012731
12732 PyErr_Format(PyExc_TypeError,
12733 "must be str or None, not %.100s",
12734 Py_TYPE(substring)->tp_name);
12735 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012736}
12737
Thomas Wouters477c8d52006-05-27 19:21:47 +000012738PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012739PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012740{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012741 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012742 int kind1, kind2;
12743 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012744 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012745
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012746 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012747 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012748
Victor Stinner14f8f022011-10-05 20:58:25 +020012749 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012750 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012751 len1 = PyUnicode_GET_LENGTH(str_obj);
12752 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012753 if (kind1 < kind2 || len1 < len2) {
12754 _Py_INCREF_UNICODE_EMPTY();
12755 if (!unicode_empty)
12756 out = NULL;
12757 else {
12758 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12759 Py_DECREF(unicode_empty);
12760 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012761 return out;
12762 }
12763 buf1 = PyUnicode_DATA(str_obj);
12764 buf2 = PyUnicode_DATA(sep_obj);
12765 if (kind2 != kind1) {
12766 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12767 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012768 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012769 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012770
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012771 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012772 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012773 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12774 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12775 else
12776 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012777 break;
12778 case PyUnicode_2BYTE_KIND:
12779 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12780 break;
12781 case PyUnicode_4BYTE_KIND:
12782 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12783 break;
12784 default:
12785 assert(0);
12786 out = 0;
12787 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012788
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012789 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012790 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012791
12792 return out;
12793}
12794
12795
12796PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012797PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012798{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012799 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012800 int kind1, kind2;
12801 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012802 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012803
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012804 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012805 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012806
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012807 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012808 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012809 len1 = PyUnicode_GET_LENGTH(str_obj);
12810 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012811 if (kind1 < kind2 || len1 < len2) {
12812 _Py_INCREF_UNICODE_EMPTY();
12813 if (!unicode_empty)
12814 out = NULL;
12815 else {
12816 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12817 Py_DECREF(unicode_empty);
12818 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012819 return out;
12820 }
12821 buf1 = PyUnicode_DATA(str_obj);
12822 buf2 = PyUnicode_DATA(sep_obj);
12823 if (kind2 != kind1) {
12824 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12825 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012826 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012827 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012828
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012829 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012830 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012831 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12832 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12833 else
12834 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012835 break;
12836 case PyUnicode_2BYTE_KIND:
12837 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12838 break;
12839 case PyUnicode_4BYTE_KIND:
12840 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12841 break;
12842 default:
12843 assert(0);
12844 out = 0;
12845 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012846
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012847 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012848 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012849
12850 return out;
12851}
12852
12853PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012854 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012855\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012856Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012857the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012858found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012859
12860static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012861unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012862{
Victor Stinner9310abb2011-10-05 00:59:23 +020012863 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012864}
12865
12866PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012867 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012868\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012869Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012870the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012871separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012872
12873static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012874unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012875{
Victor Stinner9310abb2011-10-05 00:59:23 +020012876 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012877}
12878
Alexander Belopolsky40018472011-02-26 01:02:56 +000012879PyObject *
12880PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012881{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012882 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012883 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012884
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012885 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012886}
12887
12888PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012889 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012890\n\
12891Return a list of the words in S, using sep as the\n\
12892delimiter string, starting at the end of the string and\n\
12893working to the front. If maxsplit is given, at most maxsplit\n\
12894splits are done. If sep is not specified, any whitespace string\n\
12895is a separator.");
12896
12897static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012898unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012899{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012900 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012901 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012902 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012903
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012904 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12905 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012906 return NULL;
12907
12908 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012909 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012910
12911 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012912 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012913
12914 PyErr_Format(PyExc_TypeError,
12915 "must be str or None, not %.100s",
12916 Py_TYPE(substring)->tp_name);
12917 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012918}
12919
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012920PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012921 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012922\n\
12923Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012924Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012925is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012926
12927static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012928unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012929{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012930 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012931 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012933 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12934 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012935 return NULL;
12936
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012937 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012938}
12939
12940static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012941PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012942{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012943 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012944}
12945
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012946PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012947 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012948\n\
12949Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012950and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012951
12952static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012953unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012954{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012955 if (PyUnicode_READY(self) == -1)
12956 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012957 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012958}
12959
Larry Hastings61272b72014-01-07 12:41:53 -080012960/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012961
Larry Hastings31826802013-10-19 00:09:25 -070012962@staticmethod
12963str.maketrans as unicode_maketrans
12964
12965 x: object
12966
12967 y: unicode=NULL
12968
12969 z: unicode=NULL
12970
12971 /
12972
12973Return a translation table usable for str.translate().
12974
12975If there is only one argument, it must be a dictionary mapping Unicode
12976ordinals (integers) or characters to Unicode ordinals, strings or None.
12977Character keys will be then converted to ordinals.
12978If there are two arguments, they must be strings of equal length, and
12979in the resulting dictionary, each character in x will be mapped to the
12980character at the same position in y. If there is a third argument, it
12981must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012982[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012983
Larry Hastings31826802013-10-19 00:09:25 -070012984static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012985unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012986/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012987{
Georg Brandlceee0772007-11-27 23:48:05 +000012988 PyObject *new = NULL, *key, *value;
12989 Py_ssize_t i = 0;
12990 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012991
Georg Brandlceee0772007-11-27 23:48:05 +000012992 new = PyDict_New();
12993 if (!new)
12994 return NULL;
12995 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012996 int x_kind, y_kind, z_kind;
12997 void *x_data, *y_data, *z_data;
12998
Georg Brandlceee0772007-11-27 23:48:05 +000012999 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013000 if (!PyUnicode_Check(x)) {
13001 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13002 "be a string if there is a second argument");
13003 goto err;
13004 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013005 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013006 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13007 "arguments must have equal length");
13008 goto err;
13009 }
13010 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013011 x_kind = PyUnicode_KIND(x);
13012 y_kind = PyUnicode_KIND(y);
13013 x_data = PyUnicode_DATA(x);
13014 y_data = PyUnicode_DATA(y);
13015 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13016 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013017 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013018 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013019 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013020 if (!value) {
13021 Py_DECREF(key);
13022 goto err;
13023 }
Georg Brandlceee0772007-11-27 23:48:05 +000013024 res = PyDict_SetItem(new, key, value);
13025 Py_DECREF(key);
13026 Py_DECREF(value);
13027 if (res < 0)
13028 goto err;
13029 }
13030 /* create entries for deleting chars in z */
13031 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013032 z_kind = PyUnicode_KIND(z);
13033 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013034 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013035 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013036 if (!key)
13037 goto err;
13038 res = PyDict_SetItem(new, key, Py_None);
13039 Py_DECREF(key);
13040 if (res < 0)
13041 goto err;
13042 }
13043 }
13044 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013045 int kind;
13046 void *data;
13047
Georg Brandlceee0772007-11-27 23:48:05 +000013048 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013049 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013050 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13051 "to maketrans it must be a dict");
13052 goto err;
13053 }
13054 /* copy entries into the new dict, converting string keys to int keys */
13055 while (PyDict_Next(x, &i, &key, &value)) {
13056 if (PyUnicode_Check(key)) {
13057 /* convert string keys to integer keys */
13058 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013059 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013060 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13061 "table must be of length 1");
13062 goto err;
13063 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013064 kind = PyUnicode_KIND(key);
13065 data = PyUnicode_DATA(key);
13066 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013067 if (!newkey)
13068 goto err;
13069 res = PyDict_SetItem(new, newkey, value);
13070 Py_DECREF(newkey);
13071 if (res < 0)
13072 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013073 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013074 /* just keep integer keys */
13075 if (PyDict_SetItem(new, key, value) < 0)
13076 goto err;
13077 } else {
13078 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13079 "be strings or integers");
13080 goto err;
13081 }
13082 }
13083 }
13084 return new;
13085 err:
13086 Py_DECREF(new);
13087 return NULL;
13088}
13089
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013090PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013091 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013092\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013093Return a copy of the string S in which each character has been mapped\n\
13094through the given translation table. The table must implement\n\
13095lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13096mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13097this operation raises LookupError, the character is left untouched.\n\
13098Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099
13100static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013101unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013103 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104}
13105
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013106PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013107 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013109Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110
13111static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013112unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013114 if (PyUnicode_READY(self) == -1)
13115 return NULL;
13116 if (PyUnicode_IS_ASCII(self))
13117 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013118 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119}
13120
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013121PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013122 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013123\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013124Pad a numeric string S with zeros on the left, to fill a field\n\
13125of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013126
13127static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013128unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013129{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013130 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013131 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013132 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013133 int kind;
13134 void *data;
13135 Py_UCS4 chr;
13136
Martin v. Löwis18e16552006-02-15 17:27:45 +000013137 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013138 return NULL;
13139
Benjamin Petersonbac79492012-01-14 13:34:47 -050013140 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013141 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013142
Victor Stinnerc4b49542011-12-11 22:44:26 +010013143 if (PyUnicode_GET_LENGTH(self) >= width)
13144 return unicode_result_unchanged(self);
13145
13146 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013147
13148 u = pad(self, fill, 0, '0');
13149
Walter Dörwald068325e2002-04-15 13:36:47 +000013150 if (u == NULL)
13151 return NULL;
13152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013153 kind = PyUnicode_KIND(u);
13154 data = PyUnicode_DATA(u);
13155 chr = PyUnicode_READ(kind, data, fill);
13156
13157 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013159 PyUnicode_WRITE(kind, data, 0, chr);
13160 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013161 }
13162
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013163 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013164 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013165}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166
13167#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013168static PyObject *
13169unicode__decimal2ascii(PyObject *self)
13170{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013171 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013172}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013173#endif
13174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013175PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013176 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013178Return True if S starts with the specified prefix, False otherwise.\n\
13179With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013180With optional end, stop comparing S at that position.\n\
13181prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013182
13183static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013184unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013185 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013187 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013188 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013189 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013190 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013191 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192
Jesus Ceaac451502011-04-20 17:09:23 +020013193 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013194 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013195 if (PyTuple_Check(subobj)) {
13196 Py_ssize_t i;
13197 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013198 substring = PyTuple_GET_ITEM(subobj, i);
13199 if (!PyUnicode_Check(substring)) {
13200 PyErr_Format(PyExc_TypeError,
13201 "tuple for startswith must only contain str, "
13202 "not %.100s",
13203 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013204 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013205 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013206 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013207 if (result == -1)
13208 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013209 if (result) {
13210 Py_RETURN_TRUE;
13211 }
13212 }
13213 /* nothing matched */
13214 Py_RETURN_FALSE;
13215 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013216 if (!PyUnicode_Check(subobj)) {
13217 PyErr_Format(PyExc_TypeError,
13218 "startswith first arg must be str or "
13219 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013220 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013221 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013222 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013223 if (result == -1)
13224 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013225 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013226}
13227
13228
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013229PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013230 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013232Return True if S ends with the specified suffix, False otherwise.\n\
13233With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013234With optional end, stop comparing S at that position.\n\
13235suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013236
13237static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013238unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013241 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013242 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013243 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013244 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013245 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013246
Jesus Ceaac451502011-04-20 17:09:23 +020013247 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013248 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013249 if (PyTuple_Check(subobj)) {
13250 Py_ssize_t i;
13251 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013252 substring = PyTuple_GET_ITEM(subobj, i);
13253 if (!PyUnicode_Check(substring)) {
13254 PyErr_Format(PyExc_TypeError,
13255 "tuple for endswith must only contain str, "
13256 "not %.100s",
13257 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013259 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013260 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013261 if (result == -1)
13262 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013263 if (result) {
13264 Py_RETURN_TRUE;
13265 }
13266 }
13267 Py_RETURN_FALSE;
13268 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013269 if (!PyUnicode_Check(subobj)) {
13270 PyErr_Format(PyExc_TypeError,
13271 "endswith first arg must be str or "
13272 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013273 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013274 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013275 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013276 if (result == -1)
13277 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013278 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013279}
13280
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013281static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013282_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013283{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013284 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13285 writer->data = PyUnicode_DATA(writer->buffer);
13286
13287 if (!writer->readonly) {
13288 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013289 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013290 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013291 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013292 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13293 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13294 writer->kind = PyUnicode_WCHAR_KIND;
13295 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13296
Victor Stinner8f674cc2013-04-17 23:02:17 +020013297 /* Copy-on-write mode: set buffer size to 0 so
13298 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13299 * next write. */
13300 writer->size = 0;
13301 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013302}
13303
Victor Stinnerd3f08822012-05-29 12:57:52 +020013304void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013305_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013306{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013307 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013308
13309 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013310 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013311
13312 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13313 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13314 writer->kind = PyUnicode_WCHAR_KIND;
13315 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013316}
13317
Victor Stinnerd3f08822012-05-29 12:57:52 +020013318int
13319_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13320 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013321{
13322 Py_ssize_t newlen;
13323 PyObject *newbuffer;
13324
Victor Stinner2740e462016-09-06 16:58:36 -070013325 assert(maxchar <= MAX_UNICODE);
13326
Victor Stinnerca9381e2015-09-22 00:58:32 +020013327 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013328 assert((maxchar > writer->maxchar && length >= 0)
13329 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013330
Victor Stinner202fdca2012-05-07 12:47:02 +020013331 if (length > PY_SSIZE_T_MAX - writer->pos) {
13332 PyErr_NoMemory();
13333 return -1;
13334 }
13335 newlen = writer->pos + length;
13336
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013337 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013338
Victor Stinnerd3f08822012-05-29 12:57:52 +020013339 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013340 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013341 if (writer->overallocate
13342 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13343 /* overallocate to limit the number of realloc() */
13344 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013345 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013346 if (newlen < writer->min_length)
13347 newlen = writer->min_length;
13348
Victor Stinnerd3f08822012-05-29 12:57:52 +020013349 writer->buffer = PyUnicode_New(newlen, maxchar);
13350 if (writer->buffer == NULL)
13351 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013352 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013353 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013354 if (writer->overallocate
13355 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13356 /* overallocate to limit the number of realloc() */
13357 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013358 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013359 if (newlen < writer->min_length)
13360 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013361
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013362 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013363 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013364 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013365 newbuffer = PyUnicode_New(newlen, maxchar);
13366 if (newbuffer == NULL)
13367 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013368 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13369 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013370 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013371 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013372 }
13373 else {
13374 newbuffer = resize_compact(writer->buffer, newlen);
13375 if (newbuffer == NULL)
13376 return -1;
13377 }
13378 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013379 }
13380 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013381 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013382 newbuffer = PyUnicode_New(writer->size, maxchar);
13383 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013384 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013385 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13386 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013387 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013388 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013389 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013390 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013391
13392#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013393}
13394
Victor Stinnerca9381e2015-09-22 00:58:32 +020013395int
13396_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13397 enum PyUnicode_Kind kind)
13398{
13399 Py_UCS4 maxchar;
13400
13401 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13402 assert(writer->kind < kind);
13403
13404 switch (kind)
13405 {
13406 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13407 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13408 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13409 default:
13410 assert(0 && "invalid kind");
13411 return -1;
13412 }
13413
13414 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13415}
13416
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013417static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013418_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013419{
Victor Stinner2740e462016-09-06 16:58:36 -070013420 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013421 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13422 return -1;
13423 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13424 writer->pos++;
13425 return 0;
13426}
13427
13428int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013429_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13430{
13431 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13432}
13433
13434int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013435_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13436{
13437 Py_UCS4 maxchar;
13438 Py_ssize_t len;
13439
13440 if (PyUnicode_READY(str) == -1)
13441 return -1;
13442 len = PyUnicode_GET_LENGTH(str);
13443 if (len == 0)
13444 return 0;
13445 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13446 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013447 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013448 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013449 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013450 Py_INCREF(str);
13451 writer->buffer = str;
13452 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013453 writer->pos += len;
13454 return 0;
13455 }
13456 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13457 return -1;
13458 }
13459 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13460 str, 0, len);
13461 writer->pos += len;
13462 return 0;
13463}
13464
Victor Stinnere215d962012-10-06 23:03:36 +020013465int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013466_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13467 Py_ssize_t start, Py_ssize_t end)
13468{
13469 Py_UCS4 maxchar;
13470 Py_ssize_t len;
13471
13472 if (PyUnicode_READY(str) == -1)
13473 return -1;
13474
13475 assert(0 <= start);
13476 assert(end <= PyUnicode_GET_LENGTH(str));
13477 assert(start <= end);
13478
13479 if (end == 0)
13480 return 0;
13481
13482 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13483 return _PyUnicodeWriter_WriteStr(writer, str);
13484
13485 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13486 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13487 else
13488 maxchar = writer->maxchar;
13489 len = end - start;
13490
13491 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13492 return -1;
13493
13494 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13495 str, start, len);
13496 writer->pos += len;
13497 return 0;
13498}
13499
13500int
Victor Stinner4a587072013-11-19 12:54:53 +010013501_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13502 const char *ascii, Py_ssize_t len)
13503{
13504 if (len == -1)
13505 len = strlen(ascii);
13506
13507 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13508
13509 if (writer->buffer == NULL && !writer->overallocate) {
13510 PyObject *str;
13511
13512 str = _PyUnicode_FromASCII(ascii, len);
13513 if (str == NULL)
13514 return -1;
13515
13516 writer->readonly = 1;
13517 writer->buffer = str;
13518 _PyUnicodeWriter_Update(writer);
13519 writer->pos += len;
13520 return 0;
13521 }
13522
13523 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13524 return -1;
13525
13526 switch (writer->kind)
13527 {
13528 case PyUnicode_1BYTE_KIND:
13529 {
13530 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13531 Py_UCS1 *data = writer->data;
13532
Christian Heimesf051e432016-09-13 20:22:02 +020013533 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013534 break;
13535 }
13536 case PyUnicode_2BYTE_KIND:
13537 {
13538 _PyUnicode_CONVERT_BYTES(
13539 Py_UCS1, Py_UCS2,
13540 ascii, ascii + len,
13541 (Py_UCS2 *)writer->data + writer->pos);
13542 break;
13543 }
13544 case PyUnicode_4BYTE_KIND:
13545 {
13546 _PyUnicode_CONVERT_BYTES(
13547 Py_UCS1, Py_UCS4,
13548 ascii, ascii + len,
13549 (Py_UCS4 *)writer->data + writer->pos);
13550 break;
13551 }
13552 default:
13553 assert(0);
13554 }
13555
13556 writer->pos += len;
13557 return 0;
13558}
13559
13560int
13561_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13562 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013563{
13564 Py_UCS4 maxchar;
13565
13566 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13567 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13568 return -1;
13569 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13570 writer->pos += len;
13571 return 0;
13572}
13573
Victor Stinnerd3f08822012-05-29 12:57:52 +020013574PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013575_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013576{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013577 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013578 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013579 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013580 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013581 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013582 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013583 str = writer->buffer;
13584 writer->buffer = NULL;
13585 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13586 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013587 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013588 if (writer->pos == 0) {
13589 Py_CLEAR(writer->buffer);
13590
13591 /* Get the empty Unicode string singleton ('') */
13592 _Py_INCREF_UNICODE_EMPTY();
13593 str = unicode_empty;
Victor Stinner202fdca2012-05-07 12:47:02 +020013594 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013595 else {
13596 str = writer->buffer;
13597 writer->buffer = NULL;
13598
13599 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13600 PyObject *str2;
13601 str2 = resize_compact(str, writer->pos);
13602 if (str2 == NULL)
13603 return NULL;
13604 str = str2;
13605 }
13606 }
13607
Victor Stinner15a0bd32013-07-08 22:29:55 +020013608 assert(_PyUnicode_CheckConsistency(str, 1));
13609 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013610}
13611
Victor Stinnerd3f08822012-05-29 12:57:52 +020013612void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013613_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013614{
13615 Py_CLEAR(writer->buffer);
13616}
13617
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013618#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013619
13620PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013621 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013622\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013623Return a formatted version of S, using substitutions from args and kwargs.\n\
13624The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013625
Eric Smith27bbca62010-11-04 17:06:58 +000013626PyDoc_STRVAR(format_map__doc__,
13627 "S.format_map(mapping) -> str\n\
13628\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013629Return a formatted version of S, using substitutions from mapping.\n\
13630The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013631
Eric Smith4a7d76d2008-05-30 18:10:19 +000013632static PyObject *
13633unicode__format__(PyObject* self, PyObject* args)
13634{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013635 PyObject *format_spec;
13636 _PyUnicodeWriter writer;
13637 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013638
13639 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13640 return NULL;
13641
Victor Stinnerd3f08822012-05-29 12:57:52 +020013642 if (PyUnicode_READY(self) == -1)
13643 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013644 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013645 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13646 self, format_spec, 0,
13647 PyUnicode_GET_LENGTH(format_spec));
13648 if (ret == -1) {
13649 _PyUnicodeWriter_Dealloc(&writer);
13650 return NULL;
13651 }
13652 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013653}
13654
Eric Smith8c663262007-08-25 02:26:07 +000013655PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013656 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013657\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013658Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013659
13660static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013661unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013662{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013663 Py_ssize_t size;
13664
13665 /* If it's a compact object, account for base structure +
13666 character data. */
13667 if (PyUnicode_IS_COMPACT_ASCII(v))
13668 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13669 else if (PyUnicode_IS_COMPACT(v))
13670 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013671 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013672 else {
13673 /* If it is a two-block object, account for base object, and
13674 for character block if present. */
13675 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013676 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013677 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013678 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013679 }
13680 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013681 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013682 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013683 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013684 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013685 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013686
13687 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013688}
13689
13690PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013691 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013692
13693static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013694unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013695{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013696 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013697 if (!copy)
13698 return NULL;
13699 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013700}
13701
Guido van Rossumd57fd912000-03-10 22:53:23 +000013702static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013703 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013704 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013705 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13706 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013707 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13708 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013709 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013710 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13711 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13712 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013713 {"expandtabs", (PyCFunction) unicode_expandtabs,
13714 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013715 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013716 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013717 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13718 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13719 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013720 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013721 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13722 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13723 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013724 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013725 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013726 {"splitlines", (PyCFunction) unicode_splitlines,
13727 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013728 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013729 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13730 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13731 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13732 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13733 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13734 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13735 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13736 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13737 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13738 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13739 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13740 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13741 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13742 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013743 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013744 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013745 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013746 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013747 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013748 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013749 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013750 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013751#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013752 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013753 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013754#endif
13755
Benjamin Peterson14339b62009-01-31 16:36:08 +000013756 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013757 {NULL, NULL}
13758};
13759
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013760static PyObject *
13761unicode_mod(PyObject *v, PyObject *w)
13762{
Brian Curtindfc80e32011-08-10 20:28:54 -050013763 if (!PyUnicode_Check(v))
13764 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013765 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013766}
13767
13768static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013769 0, /*nb_add*/
13770 0, /*nb_subtract*/
13771 0, /*nb_multiply*/
13772 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013773};
13774
Guido van Rossumd57fd912000-03-10 22:53:23 +000013775static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013776 (lenfunc) unicode_length, /* sq_length */
13777 PyUnicode_Concat, /* sq_concat */
13778 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13779 (ssizeargfunc) unicode_getitem, /* sq_item */
13780 0, /* sq_slice */
13781 0, /* sq_ass_item */
13782 0, /* sq_ass_slice */
13783 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013784};
13785
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013786static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013787unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013788{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013789 if (PyUnicode_READY(self) == -1)
13790 return NULL;
13791
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013792 if (PyIndex_Check(item)) {
13793 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013794 if (i == -1 && PyErr_Occurred())
13795 return NULL;
13796 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013797 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013798 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013799 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013800 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013801 PyObject *result;
13802 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013803 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013804 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013806 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013807 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013808 return NULL;
13809 }
13810
13811 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013812 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013813 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013814 slicelength == PyUnicode_GET_LENGTH(self)) {
13815 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013816 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013817 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013818 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013819 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013820 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013821 src_kind = PyUnicode_KIND(self);
13822 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013823 if (!PyUnicode_IS_ASCII(self)) {
13824 kind_limit = kind_maxchar_limit(src_kind);
13825 max_char = 0;
13826 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13827 ch = PyUnicode_READ(src_kind, src_data, cur);
13828 if (ch > max_char) {
13829 max_char = ch;
13830 if (max_char >= kind_limit)
13831 break;
13832 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013833 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013834 }
Victor Stinner55c99112011-10-13 01:17:06 +020013835 else
13836 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013837 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013838 if (result == NULL)
13839 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013840 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013841 dest_data = PyUnicode_DATA(result);
13842
13843 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013844 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13845 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013846 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013847 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013848 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013849 } else {
13850 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13851 return NULL;
13852 }
13853}
13854
13855static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013856 (lenfunc)unicode_length, /* mp_length */
13857 (binaryfunc)unicode_subscript, /* mp_subscript */
13858 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013859};
13860
Guido van Rossumd57fd912000-03-10 22:53:23 +000013861
Guido van Rossumd57fd912000-03-10 22:53:23 +000013862/* Helpers for PyUnicode_Format() */
13863
Victor Stinnera47082312012-10-04 02:19:54 +020013864struct unicode_formatter_t {
13865 PyObject *args;
13866 int args_owned;
13867 Py_ssize_t arglen, argidx;
13868 PyObject *dict;
13869
13870 enum PyUnicode_Kind fmtkind;
13871 Py_ssize_t fmtcnt, fmtpos;
13872 void *fmtdata;
13873 PyObject *fmtstr;
13874
13875 _PyUnicodeWriter writer;
13876};
13877
13878struct unicode_format_arg_t {
13879 Py_UCS4 ch;
13880 int flags;
13881 Py_ssize_t width;
13882 int prec;
13883 int sign;
13884};
13885
Guido van Rossumd57fd912000-03-10 22:53:23 +000013886static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013887unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013888{
Victor Stinnera47082312012-10-04 02:19:54 +020013889 Py_ssize_t argidx = ctx->argidx;
13890
13891 if (argidx < ctx->arglen) {
13892 ctx->argidx++;
13893 if (ctx->arglen < 0)
13894 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013895 else
Victor Stinnera47082312012-10-04 02:19:54 +020013896 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013897 }
13898 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013899 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013900 return NULL;
13901}
13902
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013903/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013904
Victor Stinnera47082312012-10-04 02:19:54 +020013905/* Format a float into the writer if the writer is not NULL, or into *p_output
13906 otherwise.
13907
13908 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013909static int
Victor Stinnera47082312012-10-04 02:19:54 +020013910formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13911 PyObject **p_output,
13912 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013913{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013914 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013915 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013916 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013917 int prec;
13918 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013919
Guido van Rossumd57fd912000-03-10 22:53:23 +000013920 x = PyFloat_AsDouble(v);
13921 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013922 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013923
Victor Stinnera47082312012-10-04 02:19:54 +020013924 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013925 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013926 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013927
Victor Stinnera47082312012-10-04 02:19:54 +020013928 if (arg->flags & F_ALT)
13929 dtoa_flags = Py_DTSF_ALT;
13930 else
13931 dtoa_flags = 0;
13932 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013933 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013934 return -1;
13935 len = strlen(p);
13936 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013937 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013938 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013939 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013940 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013941 }
13942 else
13943 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013944 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013945 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013946}
13947
Victor Stinnerd0880d52012-04-27 23:40:13 +020013948/* formatlong() emulates the format codes d, u, o, x and X, and
13949 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13950 * Python's regular ints.
13951 * Return value: a new PyUnicodeObject*, or NULL if error.
13952 * The output string is of the form
13953 * "-"? ("0x" | "0X")? digit+
13954 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13955 * set in flags. The case of hex digits will be correct,
13956 * There will be at least prec digits, zero-filled on the left if
13957 * necessary to get that many.
13958 * val object to be converted
13959 * flags bitmask of format flags; only F_ALT is looked at
13960 * prec minimum number of digits; 0-fill on left if needed
13961 * type a character in [duoxX]; u acts the same as d
13962 *
13963 * CAUTION: o, x and X conversions on regular ints can never
13964 * produce a '-' sign, but can for Python's unbounded ints.
13965 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013966PyObject *
13967_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013968{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013969 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013970 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013971 Py_ssize_t i;
13972 int sign; /* 1 if '-', else 0 */
13973 int len; /* number of characters */
13974 Py_ssize_t llen;
13975 int numdigits; /* len == numnondigits + numdigits */
13976 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013977
Victor Stinnerd0880d52012-04-27 23:40:13 +020013978 /* Avoid exceeding SSIZE_T_MAX */
13979 if (prec > INT_MAX-3) {
13980 PyErr_SetString(PyExc_OverflowError,
13981 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013982 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013983 }
13984
13985 assert(PyLong_Check(val));
13986
13987 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013988 default:
13989 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013990 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013991 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013992 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013993 /* int and int subclasses should print numerically when a numeric */
13994 /* format code is used (see issue18780) */
13995 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013996 break;
13997 case 'o':
13998 numnondigits = 2;
13999 result = PyNumber_ToBase(val, 8);
14000 break;
14001 case 'x':
14002 case 'X':
14003 numnondigits = 2;
14004 result = PyNumber_ToBase(val, 16);
14005 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014006 }
14007 if (!result)
14008 return NULL;
14009
14010 assert(unicode_modifiable(result));
14011 assert(PyUnicode_IS_READY(result));
14012 assert(PyUnicode_IS_ASCII(result));
14013
14014 /* To modify the string in-place, there can only be one reference. */
14015 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014016 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014017 PyErr_BadInternalCall();
14018 return NULL;
14019 }
14020 buf = PyUnicode_DATA(result);
14021 llen = PyUnicode_GET_LENGTH(result);
14022 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014023 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014024 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014025 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014026 return NULL;
14027 }
14028 len = (int)llen;
14029 sign = buf[0] == '-';
14030 numnondigits += sign;
14031 numdigits = len - numnondigits;
14032 assert(numdigits > 0);
14033
14034 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014035 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014036 (type == 'o' || type == 'x' || type == 'X'))) {
14037 assert(buf[sign] == '0');
14038 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14039 buf[sign+1] == 'o');
14040 numnondigits -= 2;
14041 buf += 2;
14042 len -= 2;
14043 if (sign)
14044 buf[0] = '-';
14045 assert(len == numnondigits + numdigits);
14046 assert(numdigits > 0);
14047 }
14048
14049 /* Fill with leading zeroes to meet minimum width. */
14050 if (prec > numdigits) {
14051 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14052 numnondigits + prec);
14053 char *b1;
14054 if (!r1) {
14055 Py_DECREF(result);
14056 return NULL;
14057 }
14058 b1 = PyBytes_AS_STRING(r1);
14059 for (i = 0; i < numnondigits; ++i)
14060 *b1++ = *buf++;
14061 for (i = 0; i < prec - numdigits; i++)
14062 *b1++ = '0';
14063 for (i = 0; i < numdigits; i++)
14064 *b1++ = *buf++;
14065 *b1 = '\0';
14066 Py_DECREF(result);
14067 result = r1;
14068 buf = PyBytes_AS_STRING(result);
14069 len = numnondigits + prec;
14070 }
14071
14072 /* Fix up case for hex conversions. */
14073 if (type == 'X') {
14074 /* Need to convert all lower case letters to upper case.
14075 and need to convert 0x to 0X (and -0x to -0X). */
14076 for (i = 0; i < len; i++)
14077 if (buf[i] >= 'a' && buf[i] <= 'x')
14078 buf[i] -= 'a'-'A';
14079 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014080 if (!PyUnicode_Check(result)
14081 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014082 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014083 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014084 Py_DECREF(result);
14085 result = unicode;
14086 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014087 else if (len != PyUnicode_GET_LENGTH(result)) {
14088 if (PyUnicode_Resize(&result, len) < 0)
14089 Py_CLEAR(result);
14090 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014091 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014092}
14093
Ethan Furmandf3ed242014-01-05 06:50:30 -080014094/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014095 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014096 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014097 * -1 and raise an exception on error */
14098static int
Victor Stinnera47082312012-10-04 02:19:54 +020014099mainformatlong(PyObject *v,
14100 struct unicode_format_arg_t *arg,
14101 PyObject **p_output,
14102 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014103{
14104 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014105 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014106
14107 if (!PyNumber_Check(v))
14108 goto wrongtype;
14109
Ethan Furman9ab74802014-03-21 06:38:46 -070014110 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014111 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014112 if (type == 'o' || type == 'x' || type == 'X') {
14113 iobj = PyNumber_Index(v);
14114 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014115 if (PyErr_ExceptionMatches(PyExc_TypeError))
14116 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014117 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014118 }
14119 }
14120 else {
14121 iobj = PyNumber_Long(v);
14122 if (iobj == NULL ) {
14123 if (PyErr_ExceptionMatches(PyExc_TypeError))
14124 goto wrongtype;
14125 return -1;
14126 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014127 }
14128 assert(PyLong_Check(iobj));
14129 }
14130 else {
14131 iobj = v;
14132 Py_INCREF(iobj);
14133 }
14134
14135 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014136 && arg->width == -1 && arg->prec == -1
14137 && !(arg->flags & (F_SIGN | F_BLANK))
14138 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014139 {
14140 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014141 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014142 int base;
14143
Victor Stinnera47082312012-10-04 02:19:54 +020014144 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014145 {
14146 default:
14147 assert(0 && "'type' not in [diuoxX]");
14148 case 'd':
14149 case 'i':
14150 case 'u':
14151 base = 10;
14152 break;
14153 case 'o':
14154 base = 8;
14155 break;
14156 case 'x':
14157 case 'X':
14158 base = 16;
14159 break;
14160 }
14161
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014162 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14163 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014164 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014165 }
14166 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014167 return 1;
14168 }
14169
Ethan Furmanb95b5612015-01-23 20:05:18 -080014170 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014171 Py_DECREF(iobj);
14172 if (res == NULL)
14173 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014174 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014175 return 0;
14176
14177wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014178 switch(type)
14179 {
14180 case 'o':
14181 case 'x':
14182 case 'X':
14183 PyErr_Format(PyExc_TypeError,
14184 "%%%c format: an integer is required, "
14185 "not %.200s",
14186 type, Py_TYPE(v)->tp_name);
14187 break;
14188 default:
14189 PyErr_Format(PyExc_TypeError,
14190 "%%%c format: a number is required, "
14191 "not %.200s",
14192 type, Py_TYPE(v)->tp_name);
14193 break;
14194 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014195 return -1;
14196}
14197
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014198static Py_UCS4
14199formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014200{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014201 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014202 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014203 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014204 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014205 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014206 goto onError;
14207 }
14208 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014209 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014210 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014211 /* make sure number is a type of integer */
14212 if (!PyLong_Check(v)) {
14213 iobj = PyNumber_Index(v);
14214 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014215 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014216 }
14217 v = iobj;
14218 Py_DECREF(iobj);
14219 }
14220 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014221 x = PyLong_AsLong(v);
14222 if (x == -1 && PyErr_Occurred())
14223 goto onError;
14224
Victor Stinner8faf8212011-12-08 22:14:11 +010014225 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014226 PyErr_SetString(PyExc_OverflowError,
14227 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014228 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014229 }
14230
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014231 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014232 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014233
Benjamin Peterson29060642009-01-31 22:14:21 +000014234 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014235 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014236 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014237 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014238}
14239
Victor Stinnera47082312012-10-04 02:19:54 +020014240/* Parse options of an argument: flags, width, precision.
14241 Handle also "%(name)" syntax.
14242
14243 Return 0 if the argument has been formatted into arg->str.
14244 Return 1 if the argument has been written into ctx->writer,
14245 Raise an exception and return -1 on error. */
14246static int
14247unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14248 struct unicode_format_arg_t *arg)
14249{
14250#define FORMAT_READ(ctx) \
14251 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14252
14253 PyObject *v;
14254
Victor Stinnera47082312012-10-04 02:19:54 +020014255 if (arg->ch == '(') {
14256 /* Get argument value from a dictionary. Example: "%(name)s". */
14257 Py_ssize_t keystart;
14258 Py_ssize_t keylen;
14259 PyObject *key;
14260 int pcount = 1;
14261
14262 if (ctx->dict == NULL) {
14263 PyErr_SetString(PyExc_TypeError,
14264 "format requires a mapping");
14265 return -1;
14266 }
14267 ++ctx->fmtpos;
14268 --ctx->fmtcnt;
14269 keystart = ctx->fmtpos;
14270 /* Skip over balanced parentheses */
14271 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14272 arg->ch = FORMAT_READ(ctx);
14273 if (arg->ch == ')')
14274 --pcount;
14275 else if (arg->ch == '(')
14276 ++pcount;
14277 ctx->fmtpos++;
14278 }
14279 keylen = ctx->fmtpos - keystart - 1;
14280 if (ctx->fmtcnt < 0 || pcount > 0) {
14281 PyErr_SetString(PyExc_ValueError,
14282 "incomplete format key");
14283 return -1;
14284 }
14285 key = PyUnicode_Substring(ctx->fmtstr,
14286 keystart, keystart + keylen);
14287 if (key == NULL)
14288 return -1;
14289 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014290 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014291 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014292 }
14293 ctx->args = PyObject_GetItem(ctx->dict, key);
14294 Py_DECREF(key);
14295 if (ctx->args == NULL)
14296 return -1;
14297 ctx->args_owned = 1;
14298 ctx->arglen = -1;
14299 ctx->argidx = -2;
14300 }
14301
14302 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014303 while (--ctx->fmtcnt >= 0) {
14304 arg->ch = FORMAT_READ(ctx);
14305 ctx->fmtpos++;
14306 switch (arg->ch) {
14307 case '-': arg->flags |= F_LJUST; continue;
14308 case '+': arg->flags |= F_SIGN; continue;
14309 case ' ': arg->flags |= F_BLANK; continue;
14310 case '#': arg->flags |= F_ALT; continue;
14311 case '0': arg->flags |= F_ZERO; continue;
14312 }
14313 break;
14314 }
14315
14316 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014317 if (arg->ch == '*') {
14318 v = unicode_format_getnextarg(ctx);
14319 if (v == NULL)
14320 return -1;
14321 if (!PyLong_Check(v)) {
14322 PyErr_SetString(PyExc_TypeError,
14323 "* wants int");
14324 return -1;
14325 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014326 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014327 if (arg->width == -1 && PyErr_Occurred())
14328 return -1;
14329 if (arg->width < 0) {
14330 arg->flags |= F_LJUST;
14331 arg->width = -arg->width;
14332 }
14333 if (--ctx->fmtcnt >= 0) {
14334 arg->ch = FORMAT_READ(ctx);
14335 ctx->fmtpos++;
14336 }
14337 }
14338 else if (arg->ch >= '0' && arg->ch <= '9') {
14339 arg->width = arg->ch - '0';
14340 while (--ctx->fmtcnt >= 0) {
14341 arg->ch = FORMAT_READ(ctx);
14342 ctx->fmtpos++;
14343 if (arg->ch < '0' || arg->ch > '9')
14344 break;
14345 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14346 mixing signed and unsigned comparison. Since arg->ch is between
14347 '0' and '9', casting to int is safe. */
14348 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14349 PyErr_SetString(PyExc_ValueError,
14350 "width too big");
14351 return -1;
14352 }
14353 arg->width = arg->width*10 + (arg->ch - '0');
14354 }
14355 }
14356
14357 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014358 if (arg->ch == '.') {
14359 arg->prec = 0;
14360 if (--ctx->fmtcnt >= 0) {
14361 arg->ch = FORMAT_READ(ctx);
14362 ctx->fmtpos++;
14363 }
14364 if (arg->ch == '*') {
14365 v = unicode_format_getnextarg(ctx);
14366 if (v == NULL)
14367 return -1;
14368 if (!PyLong_Check(v)) {
14369 PyErr_SetString(PyExc_TypeError,
14370 "* wants int");
14371 return -1;
14372 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014373 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014374 if (arg->prec == -1 && PyErr_Occurred())
14375 return -1;
14376 if (arg->prec < 0)
14377 arg->prec = 0;
14378 if (--ctx->fmtcnt >= 0) {
14379 arg->ch = FORMAT_READ(ctx);
14380 ctx->fmtpos++;
14381 }
14382 }
14383 else if (arg->ch >= '0' && arg->ch <= '9') {
14384 arg->prec = arg->ch - '0';
14385 while (--ctx->fmtcnt >= 0) {
14386 arg->ch = FORMAT_READ(ctx);
14387 ctx->fmtpos++;
14388 if (arg->ch < '0' || arg->ch > '9')
14389 break;
14390 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14391 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014392 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014393 return -1;
14394 }
14395 arg->prec = arg->prec*10 + (arg->ch - '0');
14396 }
14397 }
14398 }
14399
14400 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14401 if (ctx->fmtcnt >= 0) {
14402 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14403 if (--ctx->fmtcnt >= 0) {
14404 arg->ch = FORMAT_READ(ctx);
14405 ctx->fmtpos++;
14406 }
14407 }
14408 }
14409 if (ctx->fmtcnt < 0) {
14410 PyErr_SetString(PyExc_ValueError,
14411 "incomplete format");
14412 return -1;
14413 }
14414 return 0;
14415
14416#undef FORMAT_READ
14417}
14418
14419/* Format one argument. Supported conversion specifiers:
14420
14421 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014422 - "i", "d", "u": int or float
14423 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014424 - "e", "E", "f", "F", "g", "G": float
14425 - "c": int or str (1 character)
14426
Victor Stinner8dbd4212012-12-04 09:30:24 +010014427 When possible, the output is written directly into the Unicode writer
14428 (ctx->writer). A string is created when padding is required.
14429
Victor Stinnera47082312012-10-04 02:19:54 +020014430 Return 0 if the argument has been formatted into *p_str,
14431 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014432 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014433static int
14434unicode_format_arg_format(struct unicode_formatter_t *ctx,
14435 struct unicode_format_arg_t *arg,
14436 PyObject **p_str)
14437{
14438 PyObject *v;
14439 _PyUnicodeWriter *writer = &ctx->writer;
14440
14441 if (ctx->fmtcnt == 0)
14442 ctx->writer.overallocate = 0;
14443
14444 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014445 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014446 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014447 return 1;
14448 }
14449
14450 v = unicode_format_getnextarg(ctx);
14451 if (v == NULL)
14452 return -1;
14453
Victor Stinnera47082312012-10-04 02:19:54 +020014454
14455 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014456 case 's':
14457 case 'r':
14458 case 'a':
14459 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14460 /* Fast path */
14461 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14462 return -1;
14463 return 1;
14464 }
14465
14466 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14467 *p_str = v;
14468 Py_INCREF(*p_str);
14469 }
14470 else {
14471 if (arg->ch == 's')
14472 *p_str = PyObject_Str(v);
14473 else if (arg->ch == 'r')
14474 *p_str = PyObject_Repr(v);
14475 else
14476 *p_str = PyObject_ASCII(v);
14477 }
14478 break;
14479
14480 case 'i':
14481 case 'd':
14482 case 'u':
14483 case 'o':
14484 case 'x':
14485 case 'X':
14486 {
14487 int ret = mainformatlong(v, arg, p_str, writer);
14488 if (ret != 0)
14489 return ret;
14490 arg->sign = 1;
14491 break;
14492 }
14493
14494 case 'e':
14495 case 'E':
14496 case 'f':
14497 case 'F':
14498 case 'g':
14499 case 'G':
14500 if (arg->width == -1 && arg->prec == -1
14501 && !(arg->flags & (F_SIGN | F_BLANK)))
14502 {
14503 /* Fast path */
14504 if (formatfloat(v, arg, NULL, writer) == -1)
14505 return -1;
14506 return 1;
14507 }
14508
14509 arg->sign = 1;
14510 if (formatfloat(v, arg, p_str, NULL) == -1)
14511 return -1;
14512 break;
14513
14514 case 'c':
14515 {
14516 Py_UCS4 ch = formatchar(v);
14517 if (ch == (Py_UCS4) -1)
14518 return -1;
14519 if (arg->width == -1 && arg->prec == -1) {
14520 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014521 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014522 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014523 return 1;
14524 }
14525 *p_str = PyUnicode_FromOrdinal(ch);
14526 break;
14527 }
14528
14529 default:
14530 PyErr_Format(PyExc_ValueError,
14531 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014532 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014533 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14534 (int)arg->ch,
14535 ctx->fmtpos - 1);
14536 return -1;
14537 }
14538 if (*p_str == NULL)
14539 return -1;
14540 assert (PyUnicode_Check(*p_str));
14541 return 0;
14542}
14543
14544static int
14545unicode_format_arg_output(struct unicode_formatter_t *ctx,
14546 struct unicode_format_arg_t *arg,
14547 PyObject *str)
14548{
14549 Py_ssize_t len;
14550 enum PyUnicode_Kind kind;
14551 void *pbuf;
14552 Py_ssize_t pindex;
14553 Py_UCS4 signchar;
14554 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014555 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014556 Py_ssize_t sublen;
14557 _PyUnicodeWriter *writer = &ctx->writer;
14558 Py_UCS4 fill;
14559
14560 fill = ' ';
14561 if (arg->sign && arg->flags & F_ZERO)
14562 fill = '0';
14563
14564 if (PyUnicode_READY(str) == -1)
14565 return -1;
14566
14567 len = PyUnicode_GET_LENGTH(str);
14568 if ((arg->width == -1 || arg->width <= len)
14569 && (arg->prec == -1 || arg->prec >= len)
14570 && !(arg->flags & (F_SIGN | F_BLANK)))
14571 {
14572 /* Fast path */
14573 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14574 return -1;
14575 return 0;
14576 }
14577
14578 /* Truncate the string for "s", "r" and "a" formats
14579 if the precision is set */
14580 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14581 if (arg->prec >= 0 && len > arg->prec)
14582 len = arg->prec;
14583 }
14584
14585 /* Adjust sign and width */
14586 kind = PyUnicode_KIND(str);
14587 pbuf = PyUnicode_DATA(str);
14588 pindex = 0;
14589 signchar = '\0';
14590 if (arg->sign) {
14591 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14592 if (ch == '-' || ch == '+') {
14593 signchar = ch;
14594 len--;
14595 pindex++;
14596 }
14597 else if (arg->flags & F_SIGN)
14598 signchar = '+';
14599 else if (arg->flags & F_BLANK)
14600 signchar = ' ';
14601 else
14602 arg->sign = 0;
14603 }
14604 if (arg->width < len)
14605 arg->width = len;
14606
14607 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014608 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014609 if (!(arg->flags & F_LJUST)) {
14610 if (arg->sign) {
14611 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014612 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014613 }
14614 else {
14615 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014616 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014617 }
14618 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014619 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14620 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014621 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014622 }
14623
Victor Stinnera47082312012-10-04 02:19:54 +020014624 buflen = arg->width;
14625 if (arg->sign && len == arg->width)
14626 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014627 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014628 return -1;
14629
14630 /* Write the sign if needed */
14631 if (arg->sign) {
14632 if (fill != ' ') {
14633 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14634 writer->pos += 1;
14635 }
14636 if (arg->width > len)
14637 arg->width--;
14638 }
14639
14640 /* Write the numeric prefix for "x", "X" and "o" formats
14641 if the alternate form is used.
14642 For example, write "0x" for the "%#x" format. */
14643 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14644 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14645 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14646 if (fill != ' ') {
14647 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14648 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14649 writer->pos += 2;
14650 pindex += 2;
14651 }
14652 arg->width -= 2;
14653 if (arg->width < 0)
14654 arg->width = 0;
14655 len -= 2;
14656 }
14657
14658 /* Pad left with the fill character if needed */
14659 if (arg->width > len && !(arg->flags & F_LJUST)) {
14660 sublen = arg->width - len;
14661 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14662 writer->pos += sublen;
14663 arg->width = len;
14664 }
14665
14666 /* If padding with spaces: write sign if needed and/or numeric prefix if
14667 the alternate form is used */
14668 if (fill == ' ') {
14669 if (arg->sign) {
14670 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14671 writer->pos += 1;
14672 }
14673 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14674 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14675 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14676 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14677 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14678 writer->pos += 2;
14679 pindex += 2;
14680 }
14681 }
14682
14683 /* Write characters */
14684 if (len) {
14685 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14686 str, pindex, len);
14687 writer->pos += len;
14688 }
14689
14690 /* Pad right with the fill character if needed */
14691 if (arg->width > len) {
14692 sublen = arg->width - len;
14693 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14694 writer->pos += sublen;
14695 }
14696 return 0;
14697}
14698
14699/* Helper of PyUnicode_Format(): format one arg.
14700 Return 0 on success, raise an exception and return -1 on error. */
14701static int
14702unicode_format_arg(struct unicode_formatter_t *ctx)
14703{
14704 struct unicode_format_arg_t arg;
14705 PyObject *str;
14706 int ret;
14707
Victor Stinner8dbd4212012-12-04 09:30:24 +010014708 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14709 arg.flags = 0;
14710 arg.width = -1;
14711 arg.prec = -1;
14712 arg.sign = 0;
14713 str = NULL;
14714
Victor Stinnera47082312012-10-04 02:19:54 +020014715 ret = unicode_format_arg_parse(ctx, &arg);
14716 if (ret == -1)
14717 return -1;
14718
14719 ret = unicode_format_arg_format(ctx, &arg, &str);
14720 if (ret == -1)
14721 return -1;
14722
14723 if (ret != 1) {
14724 ret = unicode_format_arg_output(ctx, &arg, str);
14725 Py_DECREF(str);
14726 if (ret == -1)
14727 return -1;
14728 }
14729
14730 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14731 PyErr_SetString(PyExc_TypeError,
14732 "not all arguments converted during string formatting");
14733 return -1;
14734 }
14735 return 0;
14736}
14737
Alexander Belopolsky40018472011-02-26 01:02:56 +000014738PyObject *
14739PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014740{
Victor Stinnera47082312012-10-04 02:19:54 +020014741 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014742
Guido van Rossumd57fd912000-03-10 22:53:23 +000014743 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014744 PyErr_BadInternalCall();
14745 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014746 }
Victor Stinnera47082312012-10-04 02:19:54 +020014747
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014748 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014749 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014750
14751 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014752 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14753 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14754 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14755 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014756
Victor Stinner8f674cc2013-04-17 23:02:17 +020014757 _PyUnicodeWriter_Init(&ctx.writer);
14758 ctx.writer.min_length = ctx.fmtcnt + 100;
14759 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014760
Guido van Rossumd57fd912000-03-10 22:53:23 +000014761 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014762 ctx.arglen = PyTuple_Size(args);
14763 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014764 }
14765 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014766 ctx.arglen = -1;
14767 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014768 }
Victor Stinnera47082312012-10-04 02:19:54 +020014769 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014770 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014771 ctx.dict = args;
14772 else
14773 ctx.dict = NULL;
14774 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014775
Victor Stinnera47082312012-10-04 02:19:54 +020014776 while (--ctx.fmtcnt >= 0) {
14777 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014778 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014779
14780 nonfmtpos = ctx.fmtpos++;
14781 while (ctx.fmtcnt >= 0 &&
14782 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14783 ctx.fmtpos++;
14784 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014785 }
Victor Stinnera47082312012-10-04 02:19:54 +020014786 if (ctx.fmtcnt < 0) {
14787 ctx.fmtpos--;
14788 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014789 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014790
Victor Stinnercfc4c132013-04-03 01:48:39 +020014791 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14792 nonfmtpos, ctx.fmtpos) < 0)
14793 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014794 }
14795 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014796 ctx.fmtpos++;
14797 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014798 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014799 }
14800 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014801
Victor Stinnera47082312012-10-04 02:19:54 +020014802 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014803 PyErr_SetString(PyExc_TypeError,
14804 "not all arguments converted during string formatting");
14805 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014806 }
14807
Victor Stinnera47082312012-10-04 02:19:54 +020014808 if (ctx.args_owned) {
14809 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014810 }
Victor Stinnera47082312012-10-04 02:19:54 +020014811 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014812
Benjamin Peterson29060642009-01-31 22:14:21 +000014813 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014814 _PyUnicodeWriter_Dealloc(&ctx.writer);
14815 if (ctx.args_owned) {
14816 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014817 }
14818 return NULL;
14819}
14820
Jeremy Hylton938ace62002-07-17 16:30:39 +000014821static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014822unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14823
Tim Peters6d6c1a32001-08-02 04:15:00 +000014824static PyObject *
14825unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14826{
Benjamin Peterson29060642009-01-31 22:14:21 +000014827 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014828 static char *kwlist[] = {"object", "encoding", "errors", 0};
14829 char *encoding = NULL;
14830 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014831
Benjamin Peterson14339b62009-01-31 16:36:08 +000014832 if (type != &PyUnicode_Type)
14833 return unicode_subtype_new(type, args, kwds);
14834 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014835 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014836 return NULL;
14837 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014838 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014839 if (encoding == NULL && errors == NULL)
14840 return PyObject_Str(x);
14841 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014842 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014843}
14844
Guido van Rossume023fe02001-08-30 03:12:59 +000014845static PyObject *
14846unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14847{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014848 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014849 Py_ssize_t length, char_size;
14850 int share_wstr, share_utf8;
14851 unsigned int kind;
14852 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014853
Benjamin Peterson14339b62009-01-31 16:36:08 +000014854 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014855
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014856 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014857 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014858 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014859 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014860 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014861 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014862 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014863 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014864
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014865 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014866 if (self == NULL) {
14867 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014868 return NULL;
14869 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014870 kind = PyUnicode_KIND(unicode);
14871 length = PyUnicode_GET_LENGTH(unicode);
14872
14873 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014874#ifdef Py_DEBUG
14875 _PyUnicode_HASH(self) = -1;
14876#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014877 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014878#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014879 _PyUnicode_STATE(self).interned = 0;
14880 _PyUnicode_STATE(self).kind = kind;
14881 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014882 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014883 _PyUnicode_STATE(self).ready = 1;
14884 _PyUnicode_WSTR(self) = NULL;
14885 _PyUnicode_UTF8_LENGTH(self) = 0;
14886 _PyUnicode_UTF8(self) = NULL;
14887 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014888 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014889
14890 share_utf8 = 0;
14891 share_wstr = 0;
14892 if (kind == PyUnicode_1BYTE_KIND) {
14893 char_size = 1;
14894 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14895 share_utf8 = 1;
14896 }
14897 else if (kind == PyUnicode_2BYTE_KIND) {
14898 char_size = 2;
14899 if (sizeof(wchar_t) == 2)
14900 share_wstr = 1;
14901 }
14902 else {
14903 assert(kind == PyUnicode_4BYTE_KIND);
14904 char_size = 4;
14905 if (sizeof(wchar_t) == 4)
14906 share_wstr = 1;
14907 }
14908
14909 /* Ensure we won't overflow the length. */
14910 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14911 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014912 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014913 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014914 data = PyObject_MALLOC((length + 1) * char_size);
14915 if (data == NULL) {
14916 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014917 goto onError;
14918 }
14919
Victor Stinnerc3c74152011-10-02 20:39:55 +020014920 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014921 if (share_utf8) {
14922 _PyUnicode_UTF8_LENGTH(self) = length;
14923 _PyUnicode_UTF8(self) = data;
14924 }
14925 if (share_wstr) {
14926 _PyUnicode_WSTR_LENGTH(self) = length;
14927 _PyUnicode_WSTR(self) = (wchar_t *)data;
14928 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014929
Christian Heimesf051e432016-09-13 20:22:02 +020014930 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014931 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014932 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014933#ifdef Py_DEBUG
14934 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14935#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014936 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014937 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014938
14939onError:
14940 Py_DECREF(unicode);
14941 Py_DECREF(self);
14942 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014943}
14944
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014945PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014946"str(object='') -> str\n\
14947str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014948\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014949Create a new string object from the given object. If encoding or\n\
14950errors is specified, then the object must expose a data buffer\n\
14951that will be decoded using the given encoding and error handler.\n\
14952Otherwise, returns the result of object.__str__() (if defined)\n\
14953or repr(object).\n\
14954encoding defaults to sys.getdefaultencoding().\n\
14955errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014956
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014957static PyObject *unicode_iter(PyObject *seq);
14958
Guido van Rossumd57fd912000-03-10 22:53:23 +000014959PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014960 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014961 "str", /* tp_name */
14962 sizeof(PyUnicodeObject), /* tp_size */
14963 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014964 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014965 (destructor)unicode_dealloc, /* tp_dealloc */
14966 0, /* tp_print */
14967 0, /* tp_getattr */
14968 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014969 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014970 unicode_repr, /* tp_repr */
14971 &unicode_as_number, /* tp_as_number */
14972 &unicode_as_sequence, /* tp_as_sequence */
14973 &unicode_as_mapping, /* tp_as_mapping */
14974 (hashfunc) unicode_hash, /* tp_hash*/
14975 0, /* tp_call*/
14976 (reprfunc) unicode_str, /* tp_str */
14977 PyObject_GenericGetAttr, /* tp_getattro */
14978 0, /* tp_setattro */
14979 0, /* tp_as_buffer */
14980 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014981 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014982 unicode_doc, /* tp_doc */
14983 0, /* tp_traverse */
14984 0, /* tp_clear */
14985 PyUnicode_RichCompare, /* tp_richcompare */
14986 0, /* tp_weaklistoffset */
14987 unicode_iter, /* tp_iter */
14988 0, /* tp_iternext */
14989 unicode_methods, /* tp_methods */
14990 0, /* tp_members */
14991 0, /* tp_getset */
14992 &PyBaseObject_Type, /* tp_base */
14993 0, /* tp_dict */
14994 0, /* tp_descr_get */
14995 0, /* tp_descr_set */
14996 0, /* tp_dictoffset */
14997 0, /* tp_init */
14998 0, /* tp_alloc */
14999 unicode_new, /* tp_new */
15000 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015001};
15002
15003/* Initialize the Unicode implementation */
15004
Victor Stinner3a50e702011-10-18 21:21:00 +020015005int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015006{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015007 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015008 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015009 0x000A, /* LINE FEED */
15010 0x000D, /* CARRIAGE RETURN */
15011 0x001C, /* FILE SEPARATOR */
15012 0x001D, /* GROUP SEPARATOR */
15013 0x001E, /* RECORD SEPARATOR */
15014 0x0085, /* NEXT LINE */
15015 0x2028, /* LINE SEPARATOR */
15016 0x2029, /* PARAGRAPH SEPARATOR */
15017 };
15018
Fred Drakee4315f52000-05-09 19:53:39 +000015019 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015020 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015021 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015022 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015023 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015024
Guido van Rossumcacfc072002-05-24 19:01:59 +000015025 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015026 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015027
15028 /* initialize the linebreak bloom filter */
15029 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015030 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015031 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015032
Christian Heimes26532f72013-07-20 14:57:16 +020015033 if (PyType_Ready(&EncodingMapType) < 0)
15034 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015035
Benjamin Petersonc4311282012-10-30 23:21:10 -040015036 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15037 Py_FatalError("Can't initialize field name iterator type");
15038
15039 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15040 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015041
Victor Stinner3a50e702011-10-18 21:21:00 +020015042 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015043}
15044
15045/* Finalize the Unicode implementation */
15046
Christian Heimesa156e092008-02-16 07:38:31 +000015047int
15048PyUnicode_ClearFreeList(void)
15049{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015050 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015051}
15052
Guido van Rossumd57fd912000-03-10 22:53:23 +000015053void
Thomas Wouters78890102000-07-22 19:25:51 +000015054_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015055{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015056 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015057
Serhiy Storchaka05997252013-01-26 12:14:02 +020015058 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015059
Serhiy Storchaka05997252013-01-26 12:14:02 +020015060 for (i = 0; i < 256; i++)
15061 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015062 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015063 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015064}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015065
Walter Dörwald16807132007-05-25 13:52:07 +000015066void
15067PyUnicode_InternInPlace(PyObject **p)
15068{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015069 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015070 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015071#ifdef Py_DEBUG
15072 assert(s != NULL);
15073 assert(_PyUnicode_CHECK(s));
15074#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015075 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015076 return;
15077#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015078 /* If it's a subclass, we don't really know what putting
15079 it in the interned dict might do. */
15080 if (!PyUnicode_CheckExact(s))
15081 return;
15082 if (PyUnicode_CHECK_INTERNED(s))
15083 return;
15084 if (interned == NULL) {
15085 interned = PyDict_New();
15086 if (interned == NULL) {
15087 PyErr_Clear(); /* Don't leave an exception */
15088 return;
15089 }
15090 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015091 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015092 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015093 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015094 if (t == NULL) {
15095 PyErr_Clear();
15096 return;
15097 }
15098 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015099 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015100 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015101 return;
15102 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015103 /* The two references in interned are not counted by refcnt.
15104 The deallocator will take care of this */
15105 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015106 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015107}
15108
15109void
15110PyUnicode_InternImmortal(PyObject **p)
15111{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015112 PyUnicode_InternInPlace(p);
15113 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015114 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015115 Py_INCREF(*p);
15116 }
Walter Dörwald16807132007-05-25 13:52:07 +000015117}
15118
15119PyObject *
15120PyUnicode_InternFromString(const char *cp)
15121{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015122 PyObject *s = PyUnicode_FromString(cp);
15123 if (s == NULL)
15124 return NULL;
15125 PyUnicode_InternInPlace(&s);
15126 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015127}
15128
Alexander Belopolsky40018472011-02-26 01:02:56 +000015129void
15130_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015131{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015132 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015133 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015134 Py_ssize_t i, n;
15135 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015136
Benjamin Peterson14339b62009-01-31 16:36:08 +000015137 if (interned == NULL || !PyDict_Check(interned))
15138 return;
15139 keys = PyDict_Keys(interned);
15140 if (keys == NULL || !PyList_Check(keys)) {
15141 PyErr_Clear();
15142 return;
15143 }
Walter Dörwald16807132007-05-25 13:52:07 +000015144
Benjamin Peterson14339b62009-01-31 16:36:08 +000015145 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15146 detector, interned unicode strings are not forcibly deallocated;
15147 rather, we give them their stolen references back, and then clear
15148 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015149
Benjamin Peterson14339b62009-01-31 16:36:08 +000015150 n = PyList_GET_SIZE(keys);
15151 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015152 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015153 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015154 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015155 if (PyUnicode_READY(s) == -1) {
15156 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015157 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015158 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015159 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015160 case SSTATE_NOT_INTERNED:
15161 /* XXX Shouldn't happen */
15162 break;
15163 case SSTATE_INTERNED_IMMORTAL:
15164 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015165 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015166 break;
15167 case SSTATE_INTERNED_MORTAL:
15168 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015169 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015170 break;
15171 default:
15172 Py_FatalError("Inconsistent interned string state.");
15173 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015174 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015175 }
15176 fprintf(stderr, "total size of all interned strings: "
15177 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15178 "mortal/immortal\n", mortal_size, immortal_size);
15179 Py_DECREF(keys);
15180 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015181 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015182}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015183
15184
15185/********************* Unicode Iterator **************************/
15186
15187typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015188 PyObject_HEAD
15189 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015190 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015191} unicodeiterobject;
15192
15193static void
15194unicodeiter_dealloc(unicodeiterobject *it)
15195{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015196 _PyObject_GC_UNTRACK(it);
15197 Py_XDECREF(it->it_seq);
15198 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015199}
15200
15201static int
15202unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15203{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015204 Py_VISIT(it->it_seq);
15205 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015206}
15207
15208static PyObject *
15209unicodeiter_next(unicodeiterobject *it)
15210{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015211 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015212
Benjamin Peterson14339b62009-01-31 16:36:08 +000015213 assert(it != NULL);
15214 seq = it->it_seq;
15215 if (seq == NULL)
15216 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015217 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015219 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15220 int kind = PyUnicode_KIND(seq);
15221 void *data = PyUnicode_DATA(seq);
15222 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15223 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015224 if (item != NULL)
15225 ++it->it_index;
15226 return item;
15227 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015228
Benjamin Peterson14339b62009-01-31 16:36:08 +000015229 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015230 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015231 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015232}
15233
15234static PyObject *
15235unicodeiter_len(unicodeiterobject *it)
15236{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015237 Py_ssize_t len = 0;
15238 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015239 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015240 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015241}
15242
15243PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15244
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015245static PyObject *
15246unicodeiter_reduce(unicodeiterobject *it)
15247{
15248 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015249 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015250 it->it_seq, it->it_index);
15251 } else {
15252 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15253 if (u == NULL)
15254 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015255 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015256 }
15257}
15258
15259PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15260
15261static PyObject *
15262unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15263{
15264 Py_ssize_t index = PyLong_AsSsize_t(state);
15265 if (index == -1 && PyErr_Occurred())
15266 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015267 if (it->it_seq != NULL) {
15268 if (index < 0)
15269 index = 0;
15270 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15271 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15272 it->it_index = index;
15273 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015274 Py_RETURN_NONE;
15275}
15276
15277PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15278
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015279static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015280 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015281 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015282 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15283 reduce_doc},
15284 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15285 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015286 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015287};
15288
15289PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015290 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15291 "str_iterator", /* tp_name */
15292 sizeof(unicodeiterobject), /* tp_basicsize */
15293 0, /* tp_itemsize */
15294 /* methods */
15295 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15296 0, /* tp_print */
15297 0, /* tp_getattr */
15298 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015299 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015300 0, /* tp_repr */
15301 0, /* tp_as_number */
15302 0, /* tp_as_sequence */
15303 0, /* tp_as_mapping */
15304 0, /* tp_hash */
15305 0, /* tp_call */
15306 0, /* tp_str */
15307 PyObject_GenericGetAttr, /* tp_getattro */
15308 0, /* tp_setattro */
15309 0, /* tp_as_buffer */
15310 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15311 0, /* tp_doc */
15312 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15313 0, /* tp_clear */
15314 0, /* tp_richcompare */
15315 0, /* tp_weaklistoffset */
15316 PyObject_SelfIter, /* tp_iter */
15317 (iternextfunc)unicodeiter_next, /* tp_iternext */
15318 unicodeiter_methods, /* tp_methods */
15319 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015320};
15321
15322static PyObject *
15323unicode_iter(PyObject *seq)
15324{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015325 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015326
Benjamin Peterson14339b62009-01-31 16:36:08 +000015327 if (!PyUnicode_Check(seq)) {
15328 PyErr_BadInternalCall();
15329 return NULL;
15330 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015331 if (PyUnicode_READY(seq) == -1)
15332 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015333 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15334 if (it == NULL)
15335 return NULL;
15336 it->it_index = 0;
15337 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015338 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015339 _PyObject_GC_TRACK(it);
15340 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015341}
15342
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015343
15344size_t
15345Py_UNICODE_strlen(const Py_UNICODE *u)
15346{
15347 int res = 0;
15348 while(*u++)
15349 res++;
15350 return res;
15351}
15352
15353Py_UNICODE*
15354Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15355{
15356 Py_UNICODE *u = s1;
15357 while ((*u++ = *s2++));
15358 return s1;
15359}
15360
15361Py_UNICODE*
15362Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15363{
15364 Py_UNICODE *u = s1;
15365 while ((*u++ = *s2++))
15366 if (n-- == 0)
15367 break;
15368 return s1;
15369}
15370
15371Py_UNICODE*
15372Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15373{
15374 Py_UNICODE *u1 = s1;
15375 u1 += Py_UNICODE_strlen(u1);
15376 Py_UNICODE_strcpy(u1, s2);
15377 return s1;
15378}
15379
15380int
15381Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15382{
15383 while (*s1 && *s2 && *s1 == *s2)
15384 s1++, s2++;
15385 if (*s1 && *s2)
15386 return (*s1 < *s2) ? -1 : +1;
15387 if (*s1)
15388 return 1;
15389 if (*s2)
15390 return -1;
15391 return 0;
15392}
15393
15394int
15395Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15396{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015397 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015398 for (; n != 0; n--) {
15399 u1 = *s1;
15400 u2 = *s2;
15401 if (u1 != u2)
15402 return (u1 < u2) ? -1 : +1;
15403 if (u1 == '\0')
15404 return 0;
15405 s1++;
15406 s2++;
15407 }
15408 return 0;
15409}
15410
15411Py_UNICODE*
15412Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15413{
15414 const Py_UNICODE *p;
15415 for (p = s; *p; p++)
15416 if (*p == c)
15417 return (Py_UNICODE*)p;
15418 return NULL;
15419}
15420
15421Py_UNICODE*
15422Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15423{
15424 const Py_UNICODE *p;
15425 p = s + Py_UNICODE_strlen(s);
15426 while (p != s) {
15427 p--;
15428 if (*p == c)
15429 return (Py_UNICODE*)p;
15430 }
15431 return NULL;
15432}
Victor Stinner331ea922010-08-10 16:37:20 +000015433
Victor Stinner71133ff2010-09-01 23:43:53 +000015434Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015435PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015436{
Victor Stinner577db2c2011-10-11 22:12:48 +020015437 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015438 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015439
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015440 if (!PyUnicode_Check(unicode)) {
15441 PyErr_BadArgument();
15442 return NULL;
15443 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015444 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015445 if (u == NULL)
15446 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015447 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015448 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015449 PyErr_NoMemory();
15450 return NULL;
15451 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015452 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015453 size *= sizeof(Py_UNICODE);
15454 copy = PyMem_Malloc(size);
15455 if (copy == NULL) {
15456 PyErr_NoMemory();
15457 return NULL;
15458 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015459 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015460 return copy;
15461}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015462
Georg Brandl66c221e2010-10-14 07:04:07 +000015463/* A _string module, to export formatter_parser and formatter_field_name_split
15464 to the string.Formatter class implemented in Python. */
15465
15466static PyMethodDef _string_methods[] = {
15467 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15468 METH_O, PyDoc_STR("split the argument as a field name")},
15469 {"formatter_parser", (PyCFunction) formatter_parser,
15470 METH_O, PyDoc_STR("parse the argument as a format string")},
15471 {NULL, NULL}
15472};
15473
15474static struct PyModuleDef _string_module = {
15475 PyModuleDef_HEAD_INIT,
15476 "_string",
15477 PyDoc_STR("string helper module"),
15478 0,
15479 _string_methods,
15480 NULL,
15481 NULL,
15482 NULL,
15483 NULL
15484};
15485
15486PyMODINIT_FUNC
15487PyInit__string(void)
15488{
15489 return PyModule_Create(&_string_module);
15490}
15491
15492
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015493#ifdef __cplusplus
15494}
15495#endif