blob: 6e63e009a916393b85b87454b19b3ae06ef5f7aa [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
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001032 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001033
1034 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1035 if (copy == NULL)
1036 return NULL;
1037
1038 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001039 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001040 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001041 }
1042 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001043 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001044
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001045 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046 if (w == NULL)
1047 return NULL;
1048 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1049 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001050 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001051 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001052 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001053 }
1054}
1055
Guido van Rossumd57fd912000-03-10 22:53:23 +00001056/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001057 Ux0000 terminated; some code (e.g. new_identifier)
1058 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001059
1060 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001061 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001062
1063*/
1064
Alexander Belopolsky40018472011-02-26 01:02:56 +00001065static PyUnicodeObject *
1066_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001067{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001068 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001069 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001070
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001072 if (length == 0 && unicode_empty != NULL) {
1073 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001074 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001075 }
1076
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001077 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001078 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001079 return (PyUnicodeObject *)PyErr_NoMemory();
1080 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081 if (length < 0) {
1082 PyErr_SetString(PyExc_SystemError,
1083 "Negative size passed to _PyUnicode_New");
1084 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001085 }
1086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1088 if (unicode == NULL)
1089 return NULL;
1090 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001091
1092 _PyUnicode_WSTR_LENGTH(unicode) = length;
1093 _PyUnicode_HASH(unicode) = -1;
1094 _PyUnicode_STATE(unicode).interned = 0;
1095 _PyUnicode_STATE(unicode).kind = 0;
1096 _PyUnicode_STATE(unicode).compact = 0;
1097 _PyUnicode_STATE(unicode).ready = 0;
1098 _PyUnicode_STATE(unicode).ascii = 0;
1099 _PyUnicode_DATA_ANY(unicode) = NULL;
1100 _PyUnicode_LENGTH(unicode) = 0;
1101 _PyUnicode_UTF8(unicode) = NULL;
1102 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001104 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1105 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001106 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001107 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001108 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001109 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001110
Jeremy Hyltond8082792003-09-16 19:41:39 +00001111 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001112 * the caller fails before initializing str -- unicode_resize()
1113 * reads str[0], and the Keep-Alive optimization can keep memory
1114 * allocated for str alive across a call to unicode_dealloc(unicode).
1115 * We don't want unicode_resize to read uninitialized memory in
1116 * that case.
1117 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001118 _PyUnicode_WSTR(unicode)[0] = 0;
1119 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001120
Victor Stinner7931d9a2011-11-04 00:22:48 +01001121 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001122 return unicode;
1123}
1124
Victor Stinnerf42dc442011-10-02 23:33:16 +02001125static const char*
1126unicode_kind_name(PyObject *unicode)
1127{
Victor Stinner42dfd712011-10-03 14:41:45 +02001128 /* don't check consistency: unicode_kind_name() is called from
1129 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001130 if (!PyUnicode_IS_COMPACT(unicode))
1131 {
1132 if (!PyUnicode_IS_READY(unicode))
1133 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001134 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001135 {
1136 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001137 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001138 return "legacy ascii";
1139 else
1140 return "legacy latin1";
1141 case PyUnicode_2BYTE_KIND:
1142 return "legacy UCS2";
1143 case PyUnicode_4BYTE_KIND:
1144 return "legacy UCS4";
1145 default:
1146 return "<legacy invalid kind>";
1147 }
1148 }
1149 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001150 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001151 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001152 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001153 return "ascii";
1154 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001155 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001156 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001157 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001158 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001159 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001160 default:
1161 return "<invalid compact kind>";
1162 }
1163}
1164
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001165#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001166/* Functions wrapping macros for use in debugger */
1167char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001168 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001169}
1170
1171void *_PyUnicode_compact_data(void *unicode) {
1172 return _PyUnicode_COMPACT_DATA(unicode);
1173}
1174void *_PyUnicode_data(void *unicode){
1175 printf("obj %p\n", unicode);
1176 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1177 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1178 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1179 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1180 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1181 return PyUnicode_DATA(unicode);
1182}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001183
1184void
1185_PyUnicode_Dump(PyObject *op)
1186{
1187 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001188 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1189 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1190 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001191
Victor Stinnera849a4b2011-10-03 12:12:11 +02001192 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001193 {
1194 if (ascii->state.ascii)
1195 data = (ascii + 1);
1196 else
1197 data = (compact + 1);
1198 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001199 else
1200 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001201 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1202 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001203
Victor Stinnera849a4b2011-10-03 12:12:11 +02001204 if (ascii->wstr == data)
1205 printf("shared ");
1206 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001207
Victor Stinnera3b334d2011-10-03 13:53:37 +02001208 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001209 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001210 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1211 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001212 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1213 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001214 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001215 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001216}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001217#endif
1218
1219PyObject *
1220PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1221{
1222 PyObject *obj;
1223 PyCompactUnicodeObject *unicode;
1224 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001225 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001226 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001227 Py_ssize_t char_size;
1228 Py_ssize_t struct_size;
1229
1230 /* Optimization for empty strings */
1231 if (size == 0 && unicode_empty != NULL) {
1232 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001233 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001234 }
1235
Victor Stinner9e9d6892011-10-04 01:02:02 +02001236 is_ascii = 0;
1237 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001238 struct_size = sizeof(PyCompactUnicodeObject);
1239 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001240 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001241 char_size = 1;
1242 is_ascii = 1;
1243 struct_size = sizeof(PyASCIIObject);
1244 }
1245 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001246 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001247 char_size = 1;
1248 }
1249 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001250 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 char_size = 2;
1252 if (sizeof(wchar_t) == 2)
1253 is_sharing = 1;
1254 }
1255 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001256 if (maxchar > MAX_UNICODE) {
1257 PyErr_SetString(PyExc_SystemError,
1258 "invalid maximum character passed to PyUnicode_New");
1259 return NULL;
1260 }
Victor Stinner8f825062012-04-27 13:55:39 +02001261 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001262 char_size = 4;
1263 if (sizeof(wchar_t) == 4)
1264 is_sharing = 1;
1265 }
1266
1267 /* Ensure we won't overflow the size. */
1268 if (size < 0) {
1269 PyErr_SetString(PyExc_SystemError,
1270 "Negative size passed to PyUnicode_New");
1271 return NULL;
1272 }
1273 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1274 return PyErr_NoMemory();
1275
1276 /* Duplicated allocation code from _PyObject_New() instead of a call to
1277 * PyObject_New() so we are able to allocate space for the object and
1278 * it's data buffer.
1279 */
1280 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1281 if (obj == NULL)
1282 return PyErr_NoMemory();
1283 obj = PyObject_INIT(obj, &PyUnicode_Type);
1284 if (obj == NULL)
1285 return NULL;
1286
1287 unicode = (PyCompactUnicodeObject *)obj;
1288 if (is_ascii)
1289 data = ((PyASCIIObject*)obj) + 1;
1290 else
1291 data = unicode + 1;
1292 _PyUnicode_LENGTH(unicode) = size;
1293 _PyUnicode_HASH(unicode) = -1;
1294 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001295 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001296 _PyUnicode_STATE(unicode).compact = 1;
1297 _PyUnicode_STATE(unicode).ready = 1;
1298 _PyUnicode_STATE(unicode).ascii = is_ascii;
1299 if (is_ascii) {
1300 ((char*)data)[size] = 0;
1301 _PyUnicode_WSTR(unicode) = NULL;
1302 }
Victor Stinner8f825062012-04-27 13:55:39 +02001303 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 ((char*)data)[size] = 0;
1305 _PyUnicode_WSTR(unicode) = NULL;
1306 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001308 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310 else {
1311 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001312 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001313 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001315 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 ((Py_UCS4*)data)[size] = 0;
1317 if (is_sharing) {
1318 _PyUnicode_WSTR_LENGTH(unicode) = size;
1319 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1320 }
1321 else {
1322 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1323 _PyUnicode_WSTR(unicode) = NULL;
1324 }
1325 }
Victor Stinner8f825062012-04-27 13:55:39 +02001326#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001327 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001328#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001329 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330 return obj;
1331}
1332
1333#if SIZEOF_WCHAR_T == 2
1334/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1335 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001336 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337
1338 This function assumes that unicode can hold one more code point than wstr
1339 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001340static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001341unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001342 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343{
1344 const wchar_t *iter;
1345 Py_UCS4 *ucs4_out;
1346
Victor Stinner910337b2011-10-03 03:20:16 +02001347 assert(unicode != NULL);
1348 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001349 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1350 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1351
1352 for (iter = begin; iter < end; ) {
1353 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1354 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001355 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1356 && (iter+1) < end
1357 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001358 {
Victor Stinner551ac952011-11-29 22:58:13 +01001359 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001360 iter += 2;
1361 }
1362 else {
1363 *ucs4_out++ = *iter;
1364 iter++;
1365 }
1366 }
1367 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1368 _PyUnicode_GET_LENGTH(unicode)));
1369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001370}
1371#endif
1372
Victor Stinnercd9950f2011-10-02 00:34:53 +02001373static int
Victor Stinner488fa492011-12-12 00:01:39 +01001374unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001375{
Victor Stinner488fa492011-12-12 00:01:39 +01001376 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001377 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001378 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001379 return -1;
1380 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001381 return 0;
1382}
1383
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001384static int
1385_copy_characters(PyObject *to, Py_ssize_t to_start,
1386 PyObject *from, Py_ssize_t from_start,
1387 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001388{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001389 unsigned int from_kind, to_kind;
1390 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001391
Victor Stinneree4544c2012-05-09 22:24:08 +02001392 assert(0 <= how_many);
1393 assert(0 <= from_start);
1394 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001395 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001396 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001397 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001398
Victor Stinnerd3f08822012-05-29 12:57:52 +02001399 assert(PyUnicode_Check(to));
1400 assert(PyUnicode_IS_READY(to));
1401 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1402
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001403 if (how_many == 0)
1404 return 0;
1405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001407 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001409 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410
Victor Stinnerf1852262012-06-16 16:38:26 +02001411#ifdef Py_DEBUG
1412 if (!check_maxchar
1413 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1414 {
1415 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1416 Py_UCS4 ch;
1417 Py_ssize_t i;
1418 for (i=0; i < how_many; i++) {
1419 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1420 assert(ch <= to_maxchar);
1421 }
1422 }
1423#endif
1424
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001425 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001426 if (check_maxchar
1427 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1428 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001429 /* Writing Latin-1 characters into an ASCII string requires to
1430 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001431 Py_UCS4 max_char;
1432 max_char = ucs1lib_find_max_char(from_data,
1433 (Py_UCS1*)from_data + how_many);
1434 if (max_char >= 128)
1435 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001436 }
Christian Heimesf051e432016-09-13 20:22:02 +02001437 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001438 (char*)from_data + from_kind * from_start,
1439 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001441 else if (from_kind == PyUnicode_1BYTE_KIND
1442 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001443 {
1444 _PyUnicode_CONVERT_BYTES(
1445 Py_UCS1, Py_UCS2,
1446 PyUnicode_1BYTE_DATA(from) + from_start,
1447 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1448 PyUnicode_2BYTE_DATA(to) + to_start
1449 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001450 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001451 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001452 && to_kind == PyUnicode_4BYTE_KIND)
1453 {
1454 _PyUnicode_CONVERT_BYTES(
1455 Py_UCS1, Py_UCS4,
1456 PyUnicode_1BYTE_DATA(from) + from_start,
1457 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1458 PyUnicode_4BYTE_DATA(to) + to_start
1459 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001460 }
1461 else if (from_kind == PyUnicode_2BYTE_KIND
1462 && to_kind == PyUnicode_4BYTE_KIND)
1463 {
1464 _PyUnicode_CONVERT_BYTES(
1465 Py_UCS2, Py_UCS4,
1466 PyUnicode_2BYTE_DATA(from) + from_start,
1467 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1468 PyUnicode_4BYTE_DATA(to) + to_start
1469 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001470 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001471 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001472 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1473
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001474 if (!check_maxchar) {
1475 if (from_kind == PyUnicode_2BYTE_KIND
1476 && to_kind == PyUnicode_1BYTE_KIND)
1477 {
1478 _PyUnicode_CONVERT_BYTES(
1479 Py_UCS2, Py_UCS1,
1480 PyUnicode_2BYTE_DATA(from) + from_start,
1481 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1482 PyUnicode_1BYTE_DATA(to) + to_start
1483 );
1484 }
1485 else if (from_kind == PyUnicode_4BYTE_KIND
1486 && to_kind == PyUnicode_1BYTE_KIND)
1487 {
1488 _PyUnicode_CONVERT_BYTES(
1489 Py_UCS4, Py_UCS1,
1490 PyUnicode_4BYTE_DATA(from) + from_start,
1491 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1492 PyUnicode_1BYTE_DATA(to) + to_start
1493 );
1494 }
1495 else if (from_kind == PyUnicode_4BYTE_KIND
1496 && to_kind == PyUnicode_2BYTE_KIND)
1497 {
1498 _PyUnicode_CONVERT_BYTES(
1499 Py_UCS4, Py_UCS2,
1500 PyUnicode_4BYTE_DATA(from) + from_start,
1501 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1502 PyUnicode_2BYTE_DATA(to) + to_start
1503 );
1504 }
1505 else {
1506 assert(0);
1507 return -1;
1508 }
1509 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001510 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001511 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001512 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001513 Py_ssize_t i;
1514
Victor Stinnera0702ab2011-09-29 14:14:38 +02001515 for (i=0; i < how_many; i++) {
1516 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001517 if (ch > to_maxchar)
1518 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001519 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1520 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001521 }
1522 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001523 return 0;
1524}
1525
Victor Stinnerd3f08822012-05-29 12:57:52 +02001526void
1527_PyUnicode_FastCopyCharacters(
1528 PyObject *to, Py_ssize_t to_start,
1529 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001530{
1531 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1532}
1533
1534Py_ssize_t
1535PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1536 PyObject *from, Py_ssize_t from_start,
1537 Py_ssize_t how_many)
1538{
1539 int err;
1540
1541 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1542 PyErr_BadInternalCall();
1543 return -1;
1544 }
1545
Benjamin Petersonbac79492012-01-14 13:34:47 -05001546 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001547 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001548 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001549 return -1;
1550
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001551 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001552 PyErr_SetString(PyExc_IndexError, "string index out of range");
1553 return -1;
1554 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001555 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001556 PyErr_SetString(PyExc_IndexError, "string index out of range");
1557 return -1;
1558 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001559 if (how_many < 0) {
1560 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1561 return -1;
1562 }
1563 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001564 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1565 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001566 "Cannot write %zi characters at %zi "
1567 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001568 how_many, to_start, PyUnicode_GET_LENGTH(to));
1569 return -1;
1570 }
1571
1572 if (how_many == 0)
1573 return 0;
1574
Victor Stinner488fa492011-12-12 00:01:39 +01001575 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001576 return -1;
1577
1578 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1579 if (err) {
1580 PyErr_Format(PyExc_SystemError,
1581 "Cannot copy %s characters "
1582 "into a string of %s characters",
1583 unicode_kind_name(from),
1584 unicode_kind_name(to));
1585 return -1;
1586 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001587 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588}
1589
Victor Stinner17222162011-09-28 22:15:37 +02001590/* Find the maximum code point and count the number of surrogate pairs so a
1591 correct string length can be computed before converting a string to UCS4.
1592 This function counts single surrogates as a character and not as a pair.
1593
1594 Return 0 on success, or -1 on error. */
1595static int
1596find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1597 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598{
1599 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001600 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001601
Victor Stinnerc53be962011-10-02 21:33:54 +02001602 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001603 *num_surrogates = 0;
1604 *maxchar = 0;
1605
1606 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001607#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001608 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1609 && (iter+1) < end
1610 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1611 {
1612 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1613 ++(*num_surrogates);
1614 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 }
1616 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001618 {
1619 ch = *iter;
1620 iter++;
1621 }
1622 if (ch > *maxchar) {
1623 *maxchar = ch;
1624 if (*maxchar > MAX_UNICODE) {
1625 PyErr_Format(PyExc_ValueError,
1626 "character U+%x is not in range [U+0000; U+10ffff]",
1627 ch);
1628 return -1;
1629 }
1630 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001631 }
1632 return 0;
1633}
1634
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001635int
1636_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001637{
1638 wchar_t *end;
1639 Py_UCS4 maxchar = 0;
1640 Py_ssize_t num_surrogates;
1641#if SIZEOF_WCHAR_T == 2
1642 Py_ssize_t length_wo_surrogates;
1643#endif
1644
Georg Brandl7597add2011-10-05 16:36:47 +02001645 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001646 strings were created using _PyObject_New() and where no canonical
1647 representation (the str field) has been set yet aka strings
1648 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001649 assert(_PyUnicode_CHECK(unicode));
1650 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001651 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001652 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001653 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001654 /* Actually, it should neither be interned nor be anything else: */
1655 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001656
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001658 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001659 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001660 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661
1662 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001663 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1664 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001665 PyErr_NoMemory();
1666 return -1;
1667 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001668 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 _PyUnicode_WSTR(unicode), end,
1670 PyUnicode_1BYTE_DATA(unicode));
1671 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1672 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1673 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1674 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001675 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001676 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001677 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001678 }
1679 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001680 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001681 _PyUnicode_UTF8(unicode) = NULL;
1682 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001683 }
1684 PyObject_FREE(_PyUnicode_WSTR(unicode));
1685 _PyUnicode_WSTR(unicode) = NULL;
1686 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1687 }
1688 /* In this case we might have to convert down from 4-byte native
1689 wchar_t to 2-byte unicode. */
1690 else if (maxchar < 65536) {
1691 assert(num_surrogates == 0 &&
1692 "FindMaxCharAndNumSurrogatePairs() messed up");
1693
Victor Stinner506f5922011-09-28 22:34:18 +02001694#if SIZEOF_WCHAR_T == 2
1695 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001696 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001697 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1698 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1699 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001700 _PyUnicode_UTF8(unicode) = NULL;
1701 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001702#else
1703 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001704 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001705 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001706 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001707 PyErr_NoMemory();
1708 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001709 }
Victor Stinner506f5922011-09-28 22:34:18 +02001710 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1711 _PyUnicode_WSTR(unicode), end,
1712 PyUnicode_2BYTE_DATA(unicode));
1713 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1714 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1715 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001716 _PyUnicode_UTF8(unicode) = NULL;
1717 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001718 PyObject_FREE(_PyUnicode_WSTR(unicode));
1719 _PyUnicode_WSTR(unicode) = NULL;
1720 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1721#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001722 }
1723 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1724 else {
1725#if SIZEOF_WCHAR_T == 2
1726 /* in case the native representation is 2-bytes, we need to allocate a
1727 new normalized 4-byte version. */
1728 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001729 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1730 PyErr_NoMemory();
1731 return -1;
1732 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001733 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1734 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001735 PyErr_NoMemory();
1736 return -1;
1737 }
1738 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1739 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001740 _PyUnicode_UTF8(unicode) = NULL;
1741 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001742 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1743 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001744 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001745 PyObject_FREE(_PyUnicode_WSTR(unicode));
1746 _PyUnicode_WSTR(unicode) = NULL;
1747 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1748#else
1749 assert(num_surrogates == 0);
1750
Victor Stinnerc3c74152011-10-02 20:39:55 +02001751 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001753 _PyUnicode_UTF8(unicode) = NULL;
1754 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001755 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1756#endif
1757 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1758 }
1759 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001760 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001761 return 0;
1762}
1763
Alexander Belopolsky40018472011-02-26 01:02:56 +00001764static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001765unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001766{
Walter Dörwald16807132007-05-25 13:52:07 +00001767 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001768 case SSTATE_NOT_INTERNED:
1769 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001770
Benjamin Peterson29060642009-01-31 22:14:21 +00001771 case SSTATE_INTERNED_MORTAL:
1772 /* revive dead object temporarily for DelItem */
1773 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001774 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001775 Py_FatalError(
1776 "deletion of interned string failed");
1777 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001778
Benjamin Peterson29060642009-01-31 22:14:21 +00001779 case SSTATE_INTERNED_IMMORTAL:
1780 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001781
Benjamin Peterson29060642009-01-31 22:14:21 +00001782 default:
1783 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001784 }
1785
Victor Stinner03490912011-10-03 23:45:12 +02001786 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001788 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001789 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001790 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1791 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001792
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001793 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001794}
1795
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001796#ifdef Py_DEBUG
1797static int
1798unicode_is_singleton(PyObject *unicode)
1799{
1800 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1801 if (unicode == unicode_empty)
1802 return 1;
1803 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1804 {
1805 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1806 if (ch < 256 && unicode_latin1[ch] == unicode)
1807 return 1;
1808 }
1809 return 0;
1810}
1811#endif
1812
Alexander Belopolsky40018472011-02-26 01:02:56 +00001813static int
Victor Stinner488fa492011-12-12 00:01:39 +01001814unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001815{
Victor Stinner488fa492011-12-12 00:01:39 +01001816 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001817 if (Py_REFCNT(unicode) != 1)
1818 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001819 if (_PyUnicode_HASH(unicode) != -1)
1820 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001821 if (PyUnicode_CHECK_INTERNED(unicode))
1822 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001823 if (!PyUnicode_CheckExact(unicode))
1824 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001825#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001826 /* singleton refcount is greater than 1 */
1827 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001828#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001829 return 1;
1830}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001831
Victor Stinnerfe226c02011-10-03 03:52:20 +02001832static int
1833unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1834{
1835 PyObject *unicode;
1836 Py_ssize_t old_length;
1837
1838 assert(p_unicode != NULL);
1839 unicode = *p_unicode;
1840
1841 assert(unicode != NULL);
1842 assert(PyUnicode_Check(unicode));
1843 assert(0 <= length);
1844
Victor Stinner910337b2011-10-03 03:20:16 +02001845 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001846 old_length = PyUnicode_WSTR_LENGTH(unicode);
1847 else
1848 old_length = PyUnicode_GET_LENGTH(unicode);
1849 if (old_length == length)
1850 return 0;
1851
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001852 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001853 _Py_INCREF_UNICODE_EMPTY();
1854 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001855 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001856 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001857 return 0;
1858 }
1859
Victor Stinner488fa492011-12-12 00:01:39 +01001860 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001861 PyObject *copy = resize_copy(unicode, length);
1862 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001863 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001864 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001865 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001866 }
1867
Victor Stinnerfe226c02011-10-03 03:52:20 +02001868 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001869 PyObject *new_unicode = resize_compact(unicode, length);
1870 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001871 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001872 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001873 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001874 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001875 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001876}
1877
Alexander Belopolsky40018472011-02-26 01:02:56 +00001878int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001879PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001880{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001881 PyObject *unicode;
1882 if (p_unicode == NULL) {
1883 PyErr_BadInternalCall();
1884 return -1;
1885 }
1886 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001887 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001888 {
1889 PyErr_BadInternalCall();
1890 return -1;
1891 }
1892 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001893}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001894
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001895/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001896
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001897 WARNING: The function doesn't copy the terminating null character and
1898 doesn't check the maximum character (may write a latin1 character in an
1899 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001900static void
1901unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1902 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001903{
1904 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1905 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001906 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001907
1908 switch (kind) {
1909 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001910 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001911#ifdef Py_DEBUG
1912 if (PyUnicode_IS_ASCII(unicode)) {
1913 Py_UCS4 maxchar = ucs1lib_find_max_char(
1914 (const Py_UCS1*)str,
1915 (const Py_UCS1*)str + len);
1916 assert(maxchar < 128);
1917 }
1918#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001919 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001920 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001921 }
1922 case PyUnicode_2BYTE_KIND: {
1923 Py_UCS2 *start = (Py_UCS2 *)data + index;
1924 Py_UCS2 *ucs2 = start;
1925 assert(index <= PyUnicode_GET_LENGTH(unicode));
1926
Victor Stinner184252a2012-06-16 02:57:41 +02001927 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001928 *ucs2 = (Py_UCS2)*str;
1929
1930 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001931 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001932 }
1933 default: {
1934 Py_UCS4 *start = (Py_UCS4 *)data + index;
1935 Py_UCS4 *ucs4 = start;
1936 assert(kind == PyUnicode_4BYTE_KIND);
1937 assert(index <= PyUnicode_GET_LENGTH(unicode));
1938
Victor Stinner184252a2012-06-16 02:57:41 +02001939 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001940 *ucs4 = (Py_UCS4)*str;
1941
1942 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001943 }
1944 }
1945}
1946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001947static PyObject*
1948get_latin1_char(unsigned char ch)
1949{
Victor Stinnera464fc12011-10-02 20:39:30 +02001950 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001951 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001952 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 if (!unicode)
1954 return NULL;
1955 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001956 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001957 unicode_latin1[ch] = unicode;
1958 }
1959 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001960 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001961}
1962
Victor Stinner985a82a2014-01-03 12:53:47 +01001963static PyObject*
1964unicode_char(Py_UCS4 ch)
1965{
1966 PyObject *unicode;
1967
1968 assert(ch <= MAX_UNICODE);
1969
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001970 if (ch < 256)
1971 return get_latin1_char(ch);
1972
Victor Stinner985a82a2014-01-03 12:53:47 +01001973 unicode = PyUnicode_New(1, ch);
1974 if (unicode == NULL)
1975 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001976
1977 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
1978 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01001979 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001980 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01001981 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);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002898 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002899 }
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 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002914 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002915 return _PyUnicodeWriter_Finish(&writer);
2916
2917 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002918 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002919 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002920 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002921}
2922
Walter Dörwaldd2034312007-05-18 16:29:38 +00002923PyObject *
2924PyUnicode_FromFormat(const char *format, ...)
2925{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002926 PyObject* ret;
2927 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002928
2929#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002930 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002931#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002932 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002933#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002934 ret = PyUnicode_FromFormatV(format, vargs);
2935 va_end(vargs);
2936 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002937}
2938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002939#ifdef HAVE_WCHAR_H
2940
Victor Stinner5593d8a2010-10-02 11:11:27 +00002941/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2942 convert a Unicode object to a wide character string.
2943
Victor Stinnerd88d9832011-09-06 02:00:05 +02002944 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002945 character) required to convert the unicode object. Ignore size argument.
2946
Victor Stinnerd88d9832011-09-06 02:00:05 +02002947 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002948 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002949 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002950static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002951unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002952 wchar_t *w,
2953 Py_ssize_t size)
2954{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002955 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002956 const wchar_t *wstr;
2957
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002958 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002959 if (wstr == NULL)
2960 return -1;
2961
Victor Stinner5593d8a2010-10-02 11:11:27 +00002962 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002963 if (size > res)
2964 size = res + 1;
2965 else
2966 res = size;
Christian Heimesf051e432016-09-13 20:22:02 +02002967 memcpy(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002968 return res;
2969 }
2970 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002971 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002972}
2973
2974Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002975PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002976 wchar_t *w,
2977 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002978{
2979 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002980 PyErr_BadInternalCall();
2981 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002982 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002983 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002984}
2985
Victor Stinner137c34c2010-09-29 10:25:54 +00002986wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002987PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002988 Py_ssize_t *size)
2989{
2990 wchar_t* buffer;
2991 Py_ssize_t buflen;
2992
2993 if (unicode == NULL) {
2994 PyErr_BadInternalCall();
2995 return NULL;
2996 }
2997
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002998 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002999 if (buflen == -1)
3000 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003001 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00003002 if (buffer == NULL) {
3003 PyErr_NoMemory();
3004 return NULL;
3005 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003006 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02003007 if (buflen == -1) {
3008 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003009 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02003010 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00003011 if (size != NULL)
3012 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00003013 return buffer;
3014}
3015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003016#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003017
Alexander Belopolsky40018472011-02-26 01:02:56 +00003018PyObject *
3019PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003020{
Victor Stinner8faf8212011-12-08 22:14:11 +01003021 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003022 PyErr_SetString(PyExc_ValueError,
3023 "chr() arg not in range(0x110000)");
3024 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003025 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003026
Victor Stinner985a82a2014-01-03 12:53:47 +01003027 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003028}
3029
Alexander Belopolsky40018472011-02-26 01:02:56 +00003030PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003031PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003032{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003033 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003035 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003036 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003037 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003038 Py_INCREF(obj);
3039 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003040 }
3041 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003042 /* For a Unicode subtype that's not a Unicode object,
3043 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003044 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003045 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003046 PyErr_Format(PyExc_TypeError,
3047 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00003048 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003049 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003050}
3051
Alexander Belopolsky40018472011-02-26 01:02:56 +00003052PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003053PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003054 const char *encoding,
3055 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003056{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003057 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003058 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003059
Guido van Rossumd57fd912000-03-10 22:53:23 +00003060 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003061 PyErr_BadInternalCall();
3062 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003063 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003064
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003065 /* Decoding bytes objects is the most common case and should be fast */
3066 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003067 if (PyBytes_GET_SIZE(obj) == 0)
3068 _Py_RETURN_UNICODE_EMPTY();
3069 v = PyUnicode_Decode(
3070 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3071 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003072 return v;
3073 }
3074
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003075 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003076 PyErr_SetString(PyExc_TypeError,
3077 "decoding str is not supported");
3078 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003079 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003080
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003081 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3082 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3083 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003084 "decoding to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003085 Py_TYPE(obj)->tp_name);
3086 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003087 }
Tim Petersced69f82003-09-16 20:30:58 +00003088
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003089 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003090 PyBuffer_Release(&buffer);
3091 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003092 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003093
Serhiy Storchaka05997252013-01-26 12:14:02 +02003094 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003095 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003096 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003097}
3098
Victor Stinnerebe17e02016-10-12 13:57:45 +02003099/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3100 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3101 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003102int
3103_Py_normalize_encoding(const char *encoding,
3104 char *lower,
3105 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003106{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003107 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003108 char *l;
3109 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003110 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003111
Victor Stinner942889a2016-09-05 15:40:10 -07003112 assert(encoding != NULL);
3113
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003114 e = encoding;
3115 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003116 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003117 punct = 0;
3118 while (1) {
3119 char c = *e;
3120 if (c == 0) {
3121 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003122 }
Victor Stinner942889a2016-09-05 15:40:10 -07003123
3124 if (Py_ISALNUM(c) || c == '.') {
3125 if (punct && l != lower) {
3126 if (l == l_end) {
3127 return 0;
3128 }
3129 *l++ = '_';
3130 }
3131 punct = 0;
3132
3133 if (l == l_end) {
3134 return 0;
3135 }
3136 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003137 }
3138 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003139 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003140 }
Victor Stinner942889a2016-09-05 15:40:10 -07003141
3142 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003143 }
3144 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003145 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003146}
3147
Alexander Belopolsky40018472011-02-26 01:02:56 +00003148PyObject *
3149PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003150 Py_ssize_t size,
3151 const char *encoding,
3152 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003153{
3154 PyObject *buffer = NULL, *unicode;
3155 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003156 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3157
3158 if (encoding == NULL) {
3159 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3160 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003161
Fred Drakee4315f52000-05-09 19:53:39 +00003162 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003163 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3164 char *lower = buflower;
3165
3166 /* Fast paths */
3167 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3168 lower += 3;
3169 if (*lower == '_') {
3170 /* Match "utf8" and "utf_8" */
3171 lower++;
3172 }
3173
3174 if (lower[0] == '8' && lower[1] == 0) {
3175 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3176 }
3177 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3178 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3179 }
3180 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3181 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3182 }
3183 }
3184 else {
3185 if (strcmp(lower, "ascii") == 0
3186 || strcmp(lower, "us_ascii") == 0) {
3187 return PyUnicode_DecodeASCII(s, size, errors);
3188 }
Steve Dowercc16be82016-09-08 10:35:16 -07003189 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003190 else if (strcmp(lower, "mbcs") == 0) {
3191 return PyUnicode_DecodeMBCS(s, size, errors);
3192 }
3193 #endif
3194 else if (strcmp(lower, "latin1") == 0
3195 || strcmp(lower, "latin_1") == 0
3196 || strcmp(lower, "iso_8859_1") == 0
3197 || strcmp(lower, "iso8859_1") == 0) {
3198 return PyUnicode_DecodeLatin1(s, size, errors);
3199 }
3200 }
Victor Stinner37296e82010-06-10 13:36:23 +00003201 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003202
3203 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003204 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003205 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003206 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003207 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003208 if (buffer == NULL)
3209 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003210 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003211 if (unicode == NULL)
3212 goto onError;
3213 if (!PyUnicode_Check(unicode)) {
3214 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003215 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3216 "use codecs.decode() to decode to arbitrary types",
3217 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003218 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003219 Py_DECREF(unicode);
3220 goto onError;
3221 }
3222 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003223 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003224
Benjamin Peterson29060642009-01-31 22:14:21 +00003225 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003226 Py_XDECREF(buffer);
3227 return NULL;
3228}
3229
Alexander Belopolsky40018472011-02-26 01:02:56 +00003230PyObject *
3231PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003232 const char *encoding,
3233 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003234{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003235 if (!PyUnicode_Check(unicode)) {
3236 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003237 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003238 }
3239
Serhiy Storchaka00939072016-10-27 21:05:49 +03003240 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3241 "PyUnicode_AsDecodedObject() is deprecated; "
3242 "use PyCodec_Decode() to decode from str", 1) < 0)
3243 return NULL;
3244
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003245 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003246 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003247
3248 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003249 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003250}
3251
Alexander Belopolsky40018472011-02-26 01:02:56 +00003252PyObject *
3253PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003254 const char *encoding,
3255 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003256{
3257 PyObject *v;
3258
3259 if (!PyUnicode_Check(unicode)) {
3260 PyErr_BadArgument();
3261 goto onError;
3262 }
3263
Serhiy Storchaka00939072016-10-27 21:05:49 +03003264 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3265 "PyUnicode_AsDecodedUnicode() is deprecated; "
3266 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3267 return NULL;
3268
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003269 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003270 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003271
3272 /* Decode via the codec registry */
3273 v = PyCodec_Decode(unicode, encoding, errors);
3274 if (v == NULL)
3275 goto onError;
3276 if (!PyUnicode_Check(v)) {
3277 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003278 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3279 "use codecs.decode() to decode to arbitrary types",
3280 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003281 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003282 Py_DECREF(v);
3283 goto onError;
3284 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003285 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003286
Benjamin Peterson29060642009-01-31 22:14:21 +00003287 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003288 return NULL;
3289}
3290
Alexander Belopolsky40018472011-02-26 01:02:56 +00003291PyObject *
3292PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003293 Py_ssize_t size,
3294 const char *encoding,
3295 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003296{
3297 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003298
Guido van Rossumd57fd912000-03-10 22:53:23 +00003299 unicode = PyUnicode_FromUnicode(s, size);
3300 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003301 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003302 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3303 Py_DECREF(unicode);
3304 return v;
3305}
3306
Alexander Belopolsky40018472011-02-26 01:02:56 +00003307PyObject *
3308PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003309 const char *encoding,
3310 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003311{
3312 PyObject *v;
3313
3314 if (!PyUnicode_Check(unicode)) {
3315 PyErr_BadArgument();
3316 goto onError;
3317 }
3318
Serhiy Storchaka00939072016-10-27 21:05:49 +03003319 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3320 "PyUnicode_AsEncodedObject() is deprecated; "
3321 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3322 "or PyCodec_Encode() for generic encoding", 1) < 0)
3323 return NULL;
3324
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003325 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003326 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003327
3328 /* Encode via the codec registry */
3329 v = PyCodec_Encode(unicode, encoding, errors);
3330 if (v == NULL)
3331 goto onError;
3332 return v;
3333
Benjamin Peterson29060642009-01-31 22:14:21 +00003334 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003335 return NULL;
3336}
3337
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003338static size_t
3339wcstombs_errorpos(const wchar_t *wstr)
3340{
3341 size_t len;
3342#if SIZEOF_WCHAR_T == 2
3343 wchar_t buf[3];
3344#else
3345 wchar_t buf[2];
3346#endif
3347 char outbuf[MB_LEN_MAX];
3348 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003349
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003350#if SIZEOF_WCHAR_T == 2
3351 buf[2] = 0;
3352#else
3353 buf[1] = 0;
3354#endif
3355 start = wstr;
3356 while (*wstr != L'\0')
3357 {
3358 previous = wstr;
3359#if SIZEOF_WCHAR_T == 2
3360 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3361 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3362 {
3363 buf[0] = wstr[0];
3364 buf[1] = wstr[1];
3365 wstr += 2;
3366 }
3367 else {
3368 buf[0] = *wstr;
3369 buf[1] = 0;
3370 wstr++;
3371 }
3372#else
3373 buf[0] = *wstr;
3374 wstr++;
3375#endif
3376 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003377 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003378 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003379 }
3380
3381 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003382 return 0;
3383}
3384
Victor Stinner1b579672011-12-17 05:47:23 +01003385static int
3386locale_error_handler(const char *errors, int *surrogateescape)
3387{
Victor Stinner50149202015-09-22 00:26:54 +02003388 _Py_error_handler error_handler = get_error_handler(errors);
3389 switch (error_handler)
3390 {
3391 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003392 *surrogateescape = 0;
3393 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003394 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003395 *surrogateescape = 1;
3396 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003397 default:
3398 PyErr_Format(PyExc_ValueError,
3399 "only 'strict' and 'surrogateescape' error handlers "
3400 "are supported, not '%s'",
3401 errors);
3402 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003403 }
Victor Stinner1b579672011-12-17 05:47:23 +01003404}
3405
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003406PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003407PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003408{
3409 Py_ssize_t wlen, wlen2;
3410 wchar_t *wstr;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003411 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003412 PyObject *bytes, *reason, *exc;
3413 size_t error_pos, errlen;
Victor Stinner1b579672011-12-17 05:47:23 +01003414 int surrogateescape;
3415
3416 if (locale_error_handler(errors, &surrogateescape) < 0)
3417 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003418
3419 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3420 if (wstr == NULL)
3421 return NULL;
3422
3423 wlen2 = wcslen(wstr);
3424 if (wlen2 != wlen) {
3425 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003426 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003427 return NULL;
3428 }
3429
3430 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003431 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003432 char *str;
3433
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003434 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003435 if (str == NULL) {
3436 if (error_pos == (size_t)-1) {
3437 PyErr_NoMemory();
3438 PyMem_Free(wstr);
3439 return NULL;
3440 }
3441 else {
3442 goto encode_error;
3443 }
3444 }
3445 PyMem_Free(wstr);
3446
3447 bytes = PyBytes_FromString(str);
3448 PyMem_Free(str);
3449 }
3450 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003451 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003452 size_t len, len2;
3453
3454 len = wcstombs(NULL, wstr, 0);
3455 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003456 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003457 goto encode_error;
3458 }
3459
3460 bytes = PyBytes_FromStringAndSize(NULL, len);
3461 if (bytes == NULL) {
3462 PyMem_Free(wstr);
3463 return NULL;
3464 }
3465
3466 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3467 if (len2 == (size_t)-1 || len2 > len) {
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003468 Py_DECREF(bytes);
Victor Stinner2f197072011-12-17 07:08:30 +01003469 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003470 goto encode_error;
3471 }
3472 PyMem_Free(wstr);
3473 }
3474 return bytes;
3475
3476encode_error:
3477 errmsg = strerror(errno);
3478 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003479
3480 if (error_pos == (size_t)-1)
3481 error_pos = wcstombs_errorpos(wstr);
3482
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003483 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003484
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003485 wstr = Py_DecodeLocale(errmsg, &errlen);
3486 if (wstr != NULL) {
3487 reason = PyUnicode_FromWideChar(wstr, errlen);
3488 PyMem_RawFree(wstr);
3489 } else {
3490 errmsg = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003491 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003492
Victor Stinner2f197072011-12-17 07:08:30 +01003493 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003494 reason = PyUnicode_FromString(
3495 "wcstombs() encountered an unencodable "
3496 "wide character");
3497 if (reason == NULL)
3498 return NULL;
3499
3500 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3501 "locale", unicode,
3502 (Py_ssize_t)error_pos,
3503 (Py_ssize_t)(error_pos+1),
3504 reason);
3505 Py_DECREF(reason);
3506 if (exc != NULL) {
3507 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003508 Py_DECREF(exc);
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003509 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003510 return NULL;
3511}
3512
Victor Stinnerad158722010-10-27 00:25:46 +00003513PyObject *
3514PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003515{
Steve Dowercc16be82016-09-08 10:35:16 -07003516#if defined(__APPLE__)
3517 return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerad158722010-10-27 00:25:46 +00003518#else
Victor Stinner793b5312011-04-27 00:24:21 +02003519 PyInterpreterState *interp = PyThreadState_GET()->interp;
3520 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3521 cannot use it to encode and decode filenames before it is loaded. Load
3522 the Python codec requires to encode at least its own filename. Use the C
3523 version of the locale codec until the codec registry is initialized and
3524 the Python codec is loaded.
3525
3526 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3527 cannot only rely on it: check also interp->fscodec_initialized for
3528 subinterpreters. */
3529 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003530 return PyUnicode_AsEncodedString(unicode,
3531 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003532 Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003533 }
3534 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003535 return PyUnicode_EncodeLocale(unicode, Py_FileSystemDefaultEncodeErrors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003536 }
Victor Stinnerad158722010-10-27 00:25:46 +00003537#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003538}
3539
Alexander Belopolsky40018472011-02-26 01:02:56 +00003540PyObject *
3541PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003542 const char *encoding,
3543 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003544{
3545 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003546 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003547
Guido van Rossumd57fd912000-03-10 22:53:23 +00003548 if (!PyUnicode_Check(unicode)) {
3549 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003550 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003551 }
Fred Drakee4315f52000-05-09 19:53:39 +00003552
Victor Stinner942889a2016-09-05 15:40:10 -07003553 if (encoding == NULL) {
3554 return _PyUnicode_AsUTF8String(unicode, errors);
3555 }
3556
Fred Drakee4315f52000-05-09 19:53:39 +00003557 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003558 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3559 char *lower = buflower;
3560
3561 /* Fast paths */
3562 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3563 lower += 3;
3564 if (*lower == '_') {
3565 /* Match "utf8" and "utf_8" */
3566 lower++;
3567 }
3568
3569 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003570 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003571 }
3572 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3573 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3574 }
3575 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3576 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3577 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003578 }
Victor Stinner942889a2016-09-05 15:40:10 -07003579 else {
3580 if (strcmp(lower, "ascii") == 0
3581 || strcmp(lower, "us_ascii") == 0) {
3582 return _PyUnicode_AsASCIIString(unicode, errors);
3583 }
Steve Dowercc16be82016-09-08 10:35:16 -07003584#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003585 else if (strcmp(lower, "mbcs") == 0) {
3586 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3587 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003588#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003589 else if (strcmp(lower, "latin1") == 0 ||
3590 strcmp(lower, "latin_1") == 0 ||
3591 strcmp(lower, "iso_8859_1") == 0 ||
3592 strcmp(lower, "iso8859_1") == 0) {
3593 return _PyUnicode_AsLatin1String(unicode, errors);
3594 }
3595 }
Victor Stinner37296e82010-06-10 13:36:23 +00003596 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003597
3598 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003599 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003600 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003601 return NULL;
3602
3603 /* The normal path */
3604 if (PyBytes_Check(v))
3605 return v;
3606
3607 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003608 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003609 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003610 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003611
3612 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003613 "encoder %s returned bytearray instead of bytes; "
3614 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003615 encoding);
3616 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003617 Py_DECREF(v);
3618 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003619 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003620
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003621 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3622 Py_DECREF(v);
3623 return b;
3624 }
3625
3626 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003627 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3628 "use codecs.encode() to encode to arbitrary types",
3629 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003630 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003631 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003632 return NULL;
3633}
3634
Alexander Belopolsky40018472011-02-26 01:02:56 +00003635PyObject *
3636PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003637 const char *encoding,
3638 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003639{
3640 PyObject *v;
3641
3642 if (!PyUnicode_Check(unicode)) {
3643 PyErr_BadArgument();
3644 goto onError;
3645 }
3646
Serhiy Storchaka00939072016-10-27 21:05:49 +03003647 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3648 "PyUnicode_AsEncodedUnicode() is deprecated; "
3649 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3650 return NULL;
3651
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003652 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003654
3655 /* Encode via the codec registry */
3656 v = PyCodec_Encode(unicode, encoding, errors);
3657 if (v == NULL)
3658 goto onError;
3659 if (!PyUnicode_Check(v)) {
3660 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003661 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3662 "use codecs.encode() to encode to arbitrary types",
3663 encoding,
Benjamin Peterson8d761ff2016-10-16 15:41:46 -07003664 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003665 Py_DECREF(v);
3666 goto onError;
3667 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003668 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003669
Benjamin Peterson29060642009-01-31 22:14:21 +00003670 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003671 return NULL;
3672}
3673
Victor Stinner2f197072011-12-17 07:08:30 +01003674static size_t
3675mbstowcs_errorpos(const char *str, size_t len)
3676{
3677#ifdef HAVE_MBRTOWC
3678 const char *start = str;
3679 mbstate_t mbs;
3680 size_t converted;
3681 wchar_t ch;
3682
3683 memset(&mbs, 0, sizeof mbs);
3684 while (len)
3685 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003686 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003687 if (converted == 0)
3688 /* Reached end of string */
3689 break;
3690 if (converted == (size_t)-1 || converted == (size_t)-2) {
3691 /* Conversion error or incomplete character */
3692 return str - start;
3693 }
3694 else {
3695 str += converted;
3696 len -= converted;
3697 }
3698 }
3699 /* failed to find the undecodable byte sequence */
3700 return 0;
3701#endif
3702 return 0;
3703}
3704
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003705PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003706PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003707 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003708{
3709 wchar_t smallbuf[256];
3710 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3711 wchar_t *wstr;
3712 size_t wlen, wlen2;
3713 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003714 int surrogateescape;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003715 size_t error_pos, errlen;
Victor Stinner2f197072011-12-17 07:08:30 +01003716 char *errmsg;
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003717 PyObject *exc, *reason = NULL; /* initialize to prevent gcc warning */
Victor Stinner1b579672011-12-17 05:47:23 +01003718
3719 if (locale_error_handler(errors, &surrogateescape) < 0)
3720 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003721
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003722 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3723 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003724 return NULL;
3725 }
3726
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003727 if (surrogateescape) {
3728 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003729 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003730 if (wstr == NULL) {
3731 if (wlen == (size_t)-1)
3732 PyErr_NoMemory();
3733 else
3734 PyErr_SetFromErrno(PyExc_OSError);
3735 return NULL;
3736 }
3737
3738 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003739 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003740 }
3741 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003742 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003743#ifndef HAVE_BROKEN_MBSTOWCS
3744 wlen = mbstowcs(NULL, str, 0);
3745#else
3746 wlen = len;
3747#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003748 if (wlen == (size_t)-1)
3749 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003750 if (wlen+1 <= smallbuf_len) {
3751 wstr = smallbuf;
3752 }
3753 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003754 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003755 if (!wstr)
3756 return PyErr_NoMemory();
3757 }
3758
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003759 wlen2 = mbstowcs(wstr, str, wlen+1);
3760 if (wlen2 == (size_t)-1) {
3761 if (wstr != smallbuf)
3762 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003763 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003764 }
3765#ifdef HAVE_BROKEN_MBSTOWCS
3766 assert(wlen2 == wlen);
3767#endif
3768 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3769 if (wstr != smallbuf)
3770 PyMem_Free(wstr);
3771 }
3772 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003773
3774decode_error:
3775 errmsg = strerror(errno);
3776 assert(errmsg != NULL);
3777
3778 error_pos = mbstowcs_errorpos(str, len);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003779 wstr = Py_DecodeLocale(errmsg, &errlen);
3780 if (wstr != NULL) {
3781 reason = PyUnicode_FromWideChar(wstr, errlen);
3782 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003783 }
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003784
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003785 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003786 reason = PyUnicode_FromString(
3787 "mbstowcs() encountered an invalid multibyte sequence");
3788 if (reason == NULL)
3789 return NULL;
3790
3791 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3792 "locale", str, len,
3793 (Py_ssize_t)error_pos,
3794 (Py_ssize_t)(error_pos+1),
3795 reason);
3796 Py_DECREF(reason);
3797 if (exc != NULL) {
3798 PyCodec_StrictErrors(exc);
Serhiy Storchaka2fbc0192016-10-23 15:41:36 +03003799 Py_DECREF(exc);
Victor Stinner2f197072011-12-17 07:08:30 +01003800 }
3801 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003802}
3803
3804PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003805PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003806{
3807 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003808 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003809}
3810
3811
3812PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003813PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003814 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003815 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3816}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003817
Christian Heimes5894ba72007-11-04 11:43:14 +00003818PyObject*
3819PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3820{
Steve Dowercc16be82016-09-08 10:35:16 -07003821#if defined(__APPLE__)
3822 return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003823#else
Victor Stinner793b5312011-04-27 00:24:21 +02003824 PyInterpreterState *interp = PyThreadState_GET()->interp;
3825 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3826 cannot use it to encode and decode filenames before it is loaded. Load
3827 the Python codec requires to encode at least its own filename. Use the C
3828 version of the locale codec until the codec registry is initialized and
3829 the Python codec is loaded.
3830
3831 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3832 cannot only rely on it: check also interp->fscodec_initialized for
3833 subinterpreters. */
3834 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Steve Dowercc16be82016-09-08 10:35:16 -07003835 PyObject *res = PyUnicode_Decode(s, size,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003836 Py_FileSystemDefaultEncoding,
Steve Dowercc16be82016-09-08 10:35:16 -07003837 Py_FileSystemDefaultEncodeErrors);
3838#ifdef MS_WINDOWS
3839 if (!res && PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
Serhiy Storchaka467ab192016-10-21 17:09:17 +03003840 _PyErr_FormatFromCause(PyExc_RuntimeError,
3841 "filesystem path bytes were not correctly encoded with '%s'. "
Steve Dowercc16be82016-09-08 10:35:16 -07003842 "Please report this at http://bugs.python.org/issue27781",
3843 Py_FileSystemDefaultEncoding);
Steve Dowercc16be82016-09-08 10:35:16 -07003844 }
3845#endif
3846 return res;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003847 }
3848 else {
Steve Dowercc16be82016-09-08 10:35:16 -07003849 return PyUnicode_DecodeLocaleAndSize(s, size, Py_FileSystemDefaultEncodeErrors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003850 }
Victor Stinnerad158722010-10-27 00:25:46 +00003851#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003852}
3853
Martin v. Löwis011e8422009-05-05 04:43:17 +00003854
3855int
3856PyUnicode_FSConverter(PyObject* arg, void* addr)
3857{
Brett Cannonec6ce872016-09-06 15:50:29 -07003858 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003859 PyObject *output = NULL;
3860 Py_ssize_t size;
3861 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003862 if (arg == NULL) {
3863 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003864 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003865 return 1;
3866 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003867 path = PyOS_FSPath(arg);
3868 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003869 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003870 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003871 if (PyBytes_Check(path)) {
3872 output = path;
3873 }
3874 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3875 output = PyUnicode_EncodeFSDefault(path);
3876 Py_DECREF(path);
3877 if (!output) {
3878 return 0;
3879 }
3880 assert(PyBytes_Check(output));
3881 }
3882
Victor Stinner0ea2a462010-04-30 00:22:08 +00003883 size = PyBytes_GET_SIZE(output);
3884 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003885 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003886 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003887 Py_DECREF(output);
3888 return 0;
3889 }
3890 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003891 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003892}
3893
3894
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003895int
3896PyUnicode_FSDecoder(PyObject* arg, void* addr)
3897{
Brett Cannona5711202016-09-06 19:36:01 -07003898 int is_buffer = 0;
3899 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003900 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003901 if (arg == NULL) {
3902 Py_DECREF(*(PyObject**)addr);
3903 return 1;
3904 }
Brett Cannona5711202016-09-06 19:36:01 -07003905
3906 is_buffer = PyObject_CheckBuffer(arg);
3907 if (!is_buffer) {
3908 path = PyOS_FSPath(arg);
3909 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003910 return 0;
3911 }
Brett Cannona5711202016-09-06 19:36:01 -07003912 }
3913 else {
3914 path = arg;
3915 Py_INCREF(arg);
3916 }
3917
3918 if (PyUnicode_Check(path)) {
3919 if (PyUnicode_READY(path) == -1) {
3920 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003921 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003922 }
3923 output = path;
3924 }
3925 else if (PyBytes_Check(path) || is_buffer) {
3926 PyObject *path_bytes = NULL;
3927
3928 if (!PyBytes_Check(path) &&
3929 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3930 "path should be string, bytes, or os.PathLike, not %.200s",
3931 Py_TYPE(arg)->tp_name)) {
3932 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003933 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003934 }
3935 path_bytes = PyBytes_FromObject(path);
3936 Py_DECREF(path);
3937 if (!path_bytes) {
3938 return 0;
3939 }
3940 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3941 PyBytes_GET_SIZE(path_bytes));
3942 Py_DECREF(path_bytes);
3943 if (!output) {
3944 return 0;
3945 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003946 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003947 else {
3948 PyErr_Format(PyExc_TypeError,
Brett Cannona5711202016-09-06 19:36:01 -07003949 "path should be string, bytes, or os.PathLike, not %.200s",
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003950 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003951 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003952 return 0;
3953 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003954 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003955 Py_DECREF(output);
3956 return 0;
3957 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003958 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003959 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003960 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003961 Py_DECREF(output);
3962 return 0;
3963 }
3964 *(PyObject**)addr = output;
3965 return Py_CLEANUP_SUPPORTED;
3966}
3967
3968
Martin v. Löwis5b222132007-06-10 09:51:05 +00003969char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003970PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003971{
Christian Heimesf3863112007-11-22 07:46:41 +00003972 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003973
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003974 if (!PyUnicode_Check(unicode)) {
3975 PyErr_BadArgument();
3976 return NULL;
3977 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003978 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003979 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003980
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003981 if (PyUnicode_UTF8(unicode) == NULL) {
3982 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003983 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003984 if (bytes == NULL)
3985 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003986 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3987 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003988 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003989 Py_DECREF(bytes);
3990 return NULL;
3991 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003992 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003993 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003994 PyBytes_AS_STRING(bytes),
3995 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003996 Py_DECREF(bytes);
3997 }
3998
3999 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004000 *psize = PyUnicode_UTF8_LENGTH(unicode);
4001 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004002}
4003
4004char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004005PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004006{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004007 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4008}
4009
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004010Py_UNICODE *
4011PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4012{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004013 const unsigned char *one_byte;
4014#if SIZEOF_WCHAR_T == 4
4015 const Py_UCS2 *two_bytes;
4016#else
4017 const Py_UCS4 *four_bytes;
4018 const Py_UCS4 *ucs4_end;
4019 Py_ssize_t num_surrogates;
4020#endif
4021 wchar_t *w;
4022 wchar_t *wchar_end;
4023
4024 if (!PyUnicode_Check(unicode)) {
4025 PyErr_BadArgument();
4026 return NULL;
4027 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004028 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004029 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004030 assert(_PyUnicode_KIND(unicode) != 0);
4031 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004032
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004033 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004034#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004035 four_bytes = PyUnicode_4BYTE_DATA(unicode);
4036 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004037 num_surrogates = 0;
4038
4039 for (; four_bytes < ucs4_end; ++four_bytes) {
4040 if (*four_bytes > 0xFFFF)
4041 ++num_surrogates;
4042 }
4043
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004044 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
4045 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
4046 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004047 PyErr_NoMemory();
4048 return NULL;
4049 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004050 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004051
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004052 w = _PyUnicode_WSTR(unicode);
4053 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
4054 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004055 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
4056 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004057 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004058 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01004059 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
4060 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004061 }
4062 else
4063 *w = *four_bytes;
4064
4065 if (w > wchar_end) {
4066 assert(0 && "Miscalculated string end");
4067 }
4068 }
4069 *w = 0;
4070#else
4071 /* sizeof(wchar_t) == 4 */
4072 Py_FatalError("Impossible unicode object state, wstr and str "
4073 "should share memory already.");
4074 return NULL;
4075#endif
4076 }
4077 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02004078 if ((size_t)_PyUnicode_LENGTH(unicode) >
4079 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4080 PyErr_NoMemory();
4081 return NULL;
4082 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004083 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
4084 (_PyUnicode_LENGTH(unicode) + 1));
4085 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004086 PyErr_NoMemory();
4087 return NULL;
4088 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004089 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
4090 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
4091 w = _PyUnicode_WSTR(unicode);
4092 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004093
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004094 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
4095 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004096 for (; w < wchar_end; ++one_byte, ++w)
4097 *w = *one_byte;
4098 /* null-terminate the wstr */
4099 *w = 0;
4100 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004101 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004102#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004103 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004104 for (; w < wchar_end; ++two_bytes, ++w)
4105 *w = *two_bytes;
4106 /* null-terminate the wstr */
4107 *w = 0;
4108#else
4109 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004110 PyObject_FREE(_PyUnicode_WSTR(unicode));
4111 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004112 Py_FatalError("Impossible unicode object state, wstr "
4113 "and str should share memory already.");
4114 return NULL;
4115#endif
4116 }
4117 else {
4118 assert(0 && "This should never happen.");
4119 }
4120 }
4121 }
4122 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004123 *size = PyUnicode_WSTR_LENGTH(unicode);
4124 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00004125}
4126
Alexander Belopolsky40018472011-02-26 01:02:56 +00004127Py_UNICODE *
4128PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004129{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004130 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004131}
4132
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004133
Alexander Belopolsky40018472011-02-26 01:02:56 +00004134Py_ssize_t
4135PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004136{
4137 if (!PyUnicode_Check(unicode)) {
4138 PyErr_BadArgument();
4139 goto onError;
4140 }
4141 return PyUnicode_GET_SIZE(unicode);
4142
Benjamin Peterson29060642009-01-31 22:14:21 +00004143 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004144 return -1;
4145}
4146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004147Py_ssize_t
4148PyUnicode_GetLength(PyObject *unicode)
4149{
Victor Stinner07621332012-06-16 04:53:46 +02004150 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004151 PyErr_BadArgument();
4152 return -1;
4153 }
Victor Stinner07621332012-06-16 04:53:46 +02004154 if (PyUnicode_READY(unicode) == -1)
4155 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004156 return PyUnicode_GET_LENGTH(unicode);
4157}
4158
4159Py_UCS4
4160PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4161{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004162 void *data;
4163 int kind;
4164
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004165 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
4166 PyErr_BadArgument();
4167 return (Py_UCS4)-1;
4168 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004169 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004170 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004171 return (Py_UCS4)-1;
4172 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004173 data = PyUnicode_DATA(unicode);
4174 kind = PyUnicode_KIND(unicode);
4175 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004176}
4177
4178int
4179PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4180{
4181 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004182 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004183 return -1;
4184 }
Victor Stinner488fa492011-12-12 00:01:39 +01004185 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004186 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004187 PyErr_SetString(PyExc_IndexError, "string index out of range");
4188 return -1;
4189 }
Victor Stinner488fa492011-12-12 00:01:39 +01004190 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004191 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004192 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4193 PyErr_SetString(PyExc_ValueError, "character out of range");
4194 return -1;
4195 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004196 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4197 index, ch);
4198 return 0;
4199}
4200
Alexander Belopolsky40018472011-02-26 01:02:56 +00004201const char *
4202PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004203{
Victor Stinner42cb4622010-09-01 19:39:01 +00004204 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004205}
4206
Victor Stinner554f3f02010-06-16 23:33:54 +00004207/* create or adjust a UnicodeDecodeError */
4208static void
4209make_decode_exception(PyObject **exceptionObject,
4210 const char *encoding,
4211 const char *input, Py_ssize_t length,
4212 Py_ssize_t startpos, Py_ssize_t endpos,
4213 const char *reason)
4214{
4215 if (*exceptionObject == NULL) {
4216 *exceptionObject = PyUnicodeDecodeError_Create(
4217 encoding, input, length, startpos, endpos, reason);
4218 }
4219 else {
4220 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4221 goto onError;
4222 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4223 goto onError;
4224 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4225 goto onError;
4226 }
4227 return;
4228
4229onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004230 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004231}
4232
Steve Dowercc16be82016-09-08 10:35:16 -07004233#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004234/* error handling callback helper:
4235 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004236 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004237 and adjust various state variables.
4238 return 0 on success, -1 on error
4239*/
4240
Alexander Belopolsky40018472011-02-26 01:02:56 +00004241static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004242unicode_decode_call_errorhandler_wchar(
4243 const char *errors, PyObject **errorHandler,
4244 const char *encoding, const char *reason,
4245 const char **input, const char **inend, Py_ssize_t *startinpos,
4246 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4247 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004248{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004249 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004250
4251 PyObject *restuple = NULL;
4252 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004253 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004254 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004255 Py_ssize_t requiredsize;
4256 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004257 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004258 wchar_t *repwstr;
4259 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004260
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004261 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4262 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004263
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004264 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004265 *errorHandler = PyCodec_LookupError(errors);
4266 if (*errorHandler == NULL)
4267 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004268 }
4269
Victor Stinner554f3f02010-06-16 23:33:54 +00004270 make_decode_exception(exceptionObject,
4271 encoding,
4272 *input, *inend - *input,
4273 *startinpos, *endinpos,
4274 reason);
4275 if (*exceptionObject == NULL)
4276 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004277
4278 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4279 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004280 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004281 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004282 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004283 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004284 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004285 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004286 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004287
4288 /* Copy back the bytes variables, which might have been modified by the
4289 callback */
4290 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4291 if (!inputobj)
4292 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004293 *input = PyBytes_AS_STRING(inputobj);
4294 insize = PyBytes_GET_SIZE(inputobj);
4295 *inend = *input + insize;
4296 /* we can DECREF safely, as the exception has another reference,
4297 so the object won't go away. */
4298 Py_DECREF(inputobj);
4299
4300 if (newpos<0)
4301 newpos = insize+newpos;
4302 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004303 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004304 goto onError;
4305 }
4306
4307 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4308 if (repwstr == NULL)
4309 goto onError;
4310 /* need more space? (at least enough for what we
4311 have+the replacement+the rest of the string (starting
4312 at the new input position), so we won't have to check space
4313 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004314 requiredsize = *outpos;
4315 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4316 goto overflow;
4317 requiredsize += repwlen;
4318 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4319 goto overflow;
4320 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004321 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004322 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004323 requiredsize = 2*outsize;
4324 if (unicode_resize(output, requiredsize) < 0)
4325 goto onError;
4326 }
4327 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4328 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004329 *endinpos = newpos;
4330 *inptr = *input + newpos;
4331
4332 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004333 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004334 return 0;
4335
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004336 overflow:
4337 PyErr_SetString(PyExc_OverflowError,
4338 "decoded result is too long for a Python string");
4339
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004340 onError:
4341 Py_XDECREF(restuple);
4342 return -1;
4343}
Steve Dowercc16be82016-09-08 10:35:16 -07004344#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004345
4346static int
4347unicode_decode_call_errorhandler_writer(
4348 const char *errors, PyObject **errorHandler,
4349 const char *encoding, const char *reason,
4350 const char **input, const char **inend, Py_ssize_t *startinpos,
4351 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4352 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4353{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004354 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004355
4356 PyObject *restuple = NULL;
4357 PyObject *repunicode = NULL;
4358 Py_ssize_t insize;
4359 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004360 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004361 PyObject *inputobj = NULL;
4362
4363 if (*errorHandler == NULL) {
4364 *errorHandler = PyCodec_LookupError(errors);
4365 if (*errorHandler == NULL)
4366 goto onError;
4367 }
4368
4369 make_decode_exception(exceptionObject,
4370 encoding,
4371 *input, *inend - *input,
4372 *startinpos, *endinpos,
4373 reason);
4374 if (*exceptionObject == NULL)
4375 goto onError;
4376
4377 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4378 if (restuple == NULL)
4379 goto onError;
4380 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004381 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004382 goto onError;
4383 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004384 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004385 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004386
4387 /* Copy back the bytes variables, which might have been modified by the
4388 callback */
4389 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4390 if (!inputobj)
4391 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004392 *input = PyBytes_AS_STRING(inputobj);
4393 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004394 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004395 /* we can DECREF safely, as the exception has another reference,
4396 so the object won't go away. */
4397 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004398
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004399 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004400 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004401 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004402 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004403 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004404 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004405
Victor Stinner170ca6f2013-04-18 00:25:28 +02004406 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004407 if (replen > 1) {
4408 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004409 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004410 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4411 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4412 goto onError;
4413 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004414 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004415 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004416
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004417 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004418 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004419
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004420 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004421 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004422 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004423
Benjamin Peterson29060642009-01-31 22:14:21 +00004424 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004425 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004426 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004427}
4428
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429/* --- UTF-7 Codec -------------------------------------------------------- */
4430
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431/* See RFC2152 for details. We encode conservatively and decode liberally. */
4432
4433/* Three simple macros defining base-64. */
4434
4435/* Is c a base-64 character? */
4436
4437#define IS_BASE64(c) \
4438 (((c) >= 'A' && (c) <= 'Z') || \
4439 ((c) >= 'a' && (c) <= 'z') || \
4440 ((c) >= '0' && (c) <= '9') || \
4441 (c) == '+' || (c) == '/')
4442
4443/* given that c is a base-64 character, what is its base-64 value? */
4444
4445#define FROM_BASE64(c) \
4446 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4447 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4448 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4449 (c) == '+' ? 62 : 63)
4450
4451/* What is the base-64 character of the bottom 6 bits of n? */
4452
4453#define TO_BASE64(n) \
4454 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4455
4456/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4457 * decoded as itself. We are permissive on decoding; the only ASCII
4458 * byte not decoding to itself is the + which begins a base64
4459 * string. */
4460
4461#define DECODE_DIRECT(c) \
4462 ((c) <= 127 && (c) != '+')
4463
4464/* The UTF-7 encoder treats ASCII characters differently according to
4465 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4466 * the above). See RFC2152. This array identifies these different
4467 * sets:
4468 * 0 : "Set D"
4469 * alphanumeric and '(),-./:?
4470 * 1 : "Set O"
4471 * !"#$%&*;<=>@[]^_`{|}
4472 * 2 : "whitespace"
4473 * ht nl cr sp
4474 * 3 : special (must be base64 encoded)
4475 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4476 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477
Tim Petersced69f82003-09-16 20:30:58 +00004478static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479char utf7_category[128] = {
4480/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4481 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4482/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4483 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4484/* sp ! " # $ % & ' ( ) * + , - . / */
4485 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4486/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4487 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4488/* @ A B C D E F G H I J K L M N O */
4489 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4490/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4491 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4492/* ` a b c d e f g h i j k l m n o */
4493 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4494/* p q r s t u v w x y z { | } ~ del */
4495 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004496};
4497
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498/* ENCODE_DIRECT: this character should be encoded as itself. The
4499 * answer depends on whether we are encoding set O as itself, and also
4500 * on whether we are encoding whitespace as itself. RFC2152 makes it
4501 * clear that the answers to these questions vary between
4502 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004503
Antoine Pitrou244651a2009-05-04 18:56:13 +00004504#define ENCODE_DIRECT(c, directO, directWS) \
4505 ((c) < 128 && (c) > 0 && \
4506 ((utf7_category[(c)] == 0) || \
4507 (directWS && (utf7_category[(c)] == 2)) || \
4508 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004509
Alexander Belopolsky40018472011-02-26 01:02:56 +00004510PyObject *
4511PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004512 Py_ssize_t size,
4513 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004514{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004515 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4516}
4517
Antoine Pitrou244651a2009-05-04 18:56:13 +00004518/* The decoder. The only state we preserve is our read position,
4519 * i.e. how many characters we have consumed. So if we end in the
4520 * middle of a shift sequence we have to back off the read position
4521 * and the output to the beginning of the sequence, otherwise we lose
4522 * all the shift state (seen bits, number of bits seen, high
4523 * surrogate). */
4524
Alexander Belopolsky40018472011-02-26 01:02:56 +00004525PyObject *
4526PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004527 Py_ssize_t size,
4528 const char *errors,
4529 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004530{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004531 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004532 Py_ssize_t startinpos;
4533 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004534 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004535 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004536 const char *errmsg = "";
4537 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004538 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539 unsigned int base64bits = 0;
4540 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004541 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004542 PyObject *errorHandler = NULL;
4543 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004545 if (size == 0) {
4546 if (consumed)
4547 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004548 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004549 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004551 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004552 _PyUnicodeWriter_Init(&writer);
4553 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004554
4555 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004556 e = s + size;
4557
4558 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004559 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004560 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004561 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004562
Antoine Pitrou244651a2009-05-04 18:56:13 +00004563 if (inShift) { /* in a base-64 section */
4564 if (IS_BASE64(ch)) { /* consume a base-64 character */
4565 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4566 base64bits += 6;
4567 s++;
4568 if (base64bits >= 16) {
4569 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004570 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004571 base64bits -= 16;
4572 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004573 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 if (surrogate) {
4575 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004576 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4577 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004578 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004579 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004581 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004582 }
4583 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004584 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004585 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004586 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004587 }
4588 }
Victor Stinner551ac952011-11-29 22:58:13 +01004589 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004590 /* first surrogate */
4591 surrogate = outCh;
4592 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004594 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004595 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 }
4597 }
4598 }
4599 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004600 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004601 if (base64bits > 0) { /* left-over bits */
4602 if (base64bits >= 6) {
4603 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004604 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004605 errmsg = "partial character in shift sequence";
4606 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004607 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004608 else {
4609 /* Some bits remain; they should be zero */
4610 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004611 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004612 errmsg = "non-zero padding bits in shift sequence";
4613 goto utf7Error;
4614 }
4615 }
4616 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004617 if (surrogate && DECODE_DIRECT(ch)) {
4618 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4619 goto onError;
4620 }
4621 surrogate = 0;
4622 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004623 /* '-' is absorbed; other terminating
4624 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004625 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004626 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004627 }
4628 }
4629 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004630 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004631 s++; /* consume '+' */
4632 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004633 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004634 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004635 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004636 }
4637 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004638 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004639 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004640 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004641 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004642 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004643 }
4644 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004645 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004646 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004647 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004648 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004649 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004650 else {
4651 startinpos = s-starts;
4652 s++;
4653 errmsg = "unexpected special character";
4654 goto utf7Error;
4655 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004656 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004657utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004658 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004659 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004660 errors, &errorHandler,
4661 "utf7", errmsg,
4662 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004663 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004664 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004665 }
4666
Antoine Pitrou244651a2009-05-04 18:56:13 +00004667 /* end of string */
4668
4669 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4670 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004671 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004672 if (surrogate ||
4673 (base64bits >= 6) ||
4674 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004675 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004676 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004677 errors, &errorHandler,
4678 "utf7", "unterminated shift sequence",
4679 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004680 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004681 goto onError;
4682 if (s < e)
4683 goto restart;
4684 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004685 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004686
4687 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004688 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004689 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004690 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004691 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004692 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004693 writer.kind, writer.data, shiftOutStart);
4694 Py_XDECREF(errorHandler);
4695 Py_XDECREF(exc);
4696 _PyUnicodeWriter_Dealloc(&writer);
4697 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004698 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004699 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004700 }
4701 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004702 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004703 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004704 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004705
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004706 Py_XDECREF(errorHandler);
4707 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004708 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004709
Benjamin Peterson29060642009-01-31 22:14:21 +00004710 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004711 Py_XDECREF(errorHandler);
4712 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004713 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004714 return NULL;
4715}
4716
4717
Alexander Belopolsky40018472011-02-26 01:02:56 +00004718PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004719_PyUnicode_EncodeUTF7(PyObject *str,
4720 int base64SetO,
4721 int base64WhiteSpace,
4722 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004723{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004724 int kind;
4725 void *data;
4726 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004727 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004728 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004729 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004730 unsigned int base64bits = 0;
4731 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004732 char * out;
4733 char * start;
4734
Benjamin Petersonbac79492012-01-14 13:34:47 -05004735 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004736 return NULL;
4737 kind = PyUnicode_KIND(str);
4738 data = PyUnicode_DATA(str);
4739 len = PyUnicode_GET_LENGTH(str);
4740
4741 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004742 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004743
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004744 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004745 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004746 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004747 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004748 if (v == NULL)
4749 return NULL;
4750
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004751 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004752 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004753 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004754
Antoine Pitrou244651a2009-05-04 18:56:13 +00004755 if (inShift) {
4756 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4757 /* shifting out */
4758 if (base64bits) { /* output remaining bits */
4759 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4760 base64buffer = 0;
4761 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004762 }
4763 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004764 /* Characters not in the BASE64 set implicitly unshift the sequence
4765 so no '-' is required, except if the character is itself a '-' */
4766 if (IS_BASE64(ch) || ch == '-') {
4767 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004768 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004769 *out++ = (char) ch;
4770 }
4771 else {
4772 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004773 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004774 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004775 else { /* not in a shift sequence */
4776 if (ch == '+') {
4777 *out++ = '+';
4778 *out++ = '-';
4779 }
4780 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4781 *out++ = (char) ch;
4782 }
4783 else {
4784 *out++ = '+';
4785 inShift = 1;
4786 goto encode_char;
4787 }
4788 }
4789 continue;
4790encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004791 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004792 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004793
Antoine Pitrou244651a2009-05-04 18:56:13 +00004794 /* code first surrogate */
4795 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004796 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004797 while (base64bits >= 6) {
4798 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4799 base64bits -= 6;
4800 }
4801 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004802 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004803 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004804 base64bits += 16;
4805 base64buffer = (base64buffer << 16) | ch;
4806 while (base64bits >= 6) {
4807 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4808 base64bits -= 6;
4809 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004810 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004811 if (base64bits)
4812 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4813 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004814 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004815 if (_PyBytes_Resize(&v, out - start) < 0)
4816 return NULL;
4817 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004818}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004819PyObject *
4820PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4821 Py_ssize_t size,
4822 int base64SetO,
4823 int base64WhiteSpace,
4824 const char *errors)
4825{
4826 PyObject *result;
4827 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4828 if (tmp == NULL)
4829 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004830 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004831 base64WhiteSpace, errors);
4832 Py_DECREF(tmp);
4833 return result;
4834}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004835
Antoine Pitrou244651a2009-05-04 18:56:13 +00004836#undef IS_BASE64
4837#undef FROM_BASE64
4838#undef TO_BASE64
4839#undef DECODE_DIRECT
4840#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004841
Guido van Rossumd57fd912000-03-10 22:53:23 +00004842/* --- UTF-8 Codec -------------------------------------------------------- */
4843
Alexander Belopolsky40018472011-02-26 01:02:56 +00004844PyObject *
4845PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004846 Py_ssize_t size,
4847 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004848{
Walter Dörwald69652032004-09-07 20:24:22 +00004849 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4850}
4851
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004852#include "stringlib/asciilib.h"
4853#include "stringlib/codecs.h"
4854#include "stringlib/undef.h"
4855
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004856#include "stringlib/ucs1lib.h"
4857#include "stringlib/codecs.h"
4858#include "stringlib/undef.h"
4859
4860#include "stringlib/ucs2lib.h"
4861#include "stringlib/codecs.h"
4862#include "stringlib/undef.h"
4863
4864#include "stringlib/ucs4lib.h"
4865#include "stringlib/codecs.h"
4866#include "stringlib/undef.h"
4867
Antoine Pitrouab868312009-01-10 15:40:25 +00004868/* Mask to quickly check whether a C 'long' contains a
4869 non-ASCII, UTF8-encoded char. */
4870#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004871# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004872#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004873# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004874#else
4875# error C 'long' size should be either 4 or 8!
4876#endif
4877
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004878static Py_ssize_t
4879ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004880{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004881 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004882 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004883
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004884 /*
4885 * Issue #17237: m68k is a bit different from most architectures in
4886 * that objects do not use "natural alignment" - for example, int and
4887 * long are only aligned at 2-byte boundaries. Therefore the assert()
4888 * won't work; also, tests have shown that skipping the "optimised
4889 * version" will even speed up m68k.
4890 */
4891#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004892#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004893 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4894 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004895 /* Fast path, see in STRINGLIB(utf8_decode) for
4896 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004897 /* Help allocation */
4898 const char *_p = p;
4899 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004900 while (_p < aligned_end) {
4901 unsigned long value = *(const unsigned long *) _p;
4902 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004903 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004904 *((unsigned long *)q) = value;
4905 _p += SIZEOF_LONG;
4906 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004907 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004908 p = _p;
4909 while (p < end) {
4910 if ((unsigned char)*p & 0x80)
4911 break;
4912 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004913 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004914 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004915 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004916#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004917#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004918 while (p < end) {
4919 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4920 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004921 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004922 /* Help allocation */
4923 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004924 while (_p < aligned_end) {
4925 unsigned long value = *(unsigned long *) _p;
4926 if (value & ASCII_CHAR_MASK)
4927 break;
4928 _p += SIZEOF_LONG;
4929 }
4930 p = _p;
4931 if (_p == end)
4932 break;
4933 }
4934 if ((unsigned char)*p & 0x80)
4935 break;
4936 ++p;
4937 }
4938 memcpy(dest, start, p - start);
4939 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004940}
Antoine Pitrouab868312009-01-10 15:40:25 +00004941
Victor Stinner785938e2011-12-11 20:09:03 +01004942PyObject *
4943PyUnicode_DecodeUTF8Stateful(const char *s,
4944 Py_ssize_t size,
4945 const char *errors,
4946 Py_ssize_t *consumed)
4947{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004948 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004949 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004950 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004951
4952 Py_ssize_t startinpos;
4953 Py_ssize_t endinpos;
4954 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004955 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004956 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004957 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004958
4959 if (size == 0) {
4960 if (consumed)
4961 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004962 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004963 }
4964
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004965 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4966 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004967 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004968 *consumed = 1;
4969 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004970 }
4971
Victor Stinner8f674cc2013-04-17 23:02:17 +02004972 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004973 writer.min_length = size;
4974 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004975 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004976
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004977 writer.pos = ascii_decode(s, end, writer.data);
4978 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004979 while (s < end) {
4980 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004981 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004982
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004983 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004984 if (PyUnicode_IS_ASCII(writer.buffer))
4985 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004986 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004987 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004988 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004989 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004990 } else {
4991 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004992 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004993 }
4994
4995 switch (ch) {
4996 case 0:
4997 if (s == end || consumed)
4998 goto End;
4999 errmsg = "unexpected end of data";
5000 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005001 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005002 break;
5003 case 1:
5004 errmsg = "invalid start byte";
5005 startinpos = s - starts;
5006 endinpos = startinpos + 1;
5007 break;
5008 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005009 case 3:
5010 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005011 errmsg = "invalid continuation byte";
5012 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005013 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005014 break;
5015 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005016 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005017 goto onError;
5018 continue;
5019 }
5020
Victor Stinner1d65d912015-10-05 13:43:50 +02005021 if (error_handler == _Py_ERROR_UNKNOWN)
5022 error_handler = get_error_handler(errors);
5023
5024 switch (error_handler) {
5025 case _Py_ERROR_IGNORE:
5026 s += (endinpos - startinpos);
5027 break;
5028
5029 case _Py_ERROR_REPLACE:
5030 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5031 goto onError;
5032 s += (endinpos - startinpos);
5033 break;
5034
5035 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005036 {
5037 Py_ssize_t i;
5038
Victor Stinner1d65d912015-10-05 13:43:50 +02005039 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5040 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005041 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005042 ch = (Py_UCS4)(unsigned char)(starts[i]);
5043 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5044 ch + 0xdc00);
5045 writer.pos++;
5046 }
5047 s += (endinpos - startinpos);
5048 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005049 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005050
5051 default:
5052 if (unicode_decode_call_errorhandler_writer(
5053 errors, &error_handler_obj,
5054 "utf-8", errmsg,
5055 &starts, &end, &startinpos, &endinpos, &exc, &s,
5056 &writer))
5057 goto onError;
5058 }
Victor Stinner785938e2011-12-11 20:09:03 +01005059 }
5060
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005061End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005062 if (consumed)
5063 *consumed = s - starts;
5064
Victor Stinner1d65d912015-10-05 13:43:50 +02005065 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005066 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005067 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005068
5069onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005070 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005071 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005072 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005073 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005074}
5075
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005076#ifdef __APPLE__
5077
5078/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005079 used to decode the command line arguments on Mac OS X.
5080
5081 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005082 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005083
5084wchar_t*
5085_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
5086{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005087 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005088 wchar_t *unicode;
5089 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005090
5091 /* Note: size will always be longer than the resulting Unicode
5092 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01005093 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005094 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005095 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005096 if (!unicode)
5097 return NULL;
5098
5099 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005100 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005101 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005102 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005103 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005104#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005105 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005106#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005107 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005108#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005109 if (ch > 0xFF) {
5110#if SIZEOF_WCHAR_T == 4
5111 assert(0);
5112#else
5113 assert(Py_UNICODE_IS_SURROGATE(ch));
5114 /* compute and append the two surrogates: */
5115 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5116 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5117#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005118 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005119 else {
5120 if (!ch && s == e)
5121 break;
5122 /* surrogateescape */
5123 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5124 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005125 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005126 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005127 return unicode;
5128}
5129
5130#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005131
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005132/* Primary internal function which creates utf8 encoded bytes objects.
5133
5134 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005135 and allocate exactly as much space needed at the end. Else allocate the
5136 maximum possible needed (4 result bytes per Unicode character), and return
5137 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005138*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005139PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005140_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005141{
Victor Stinner6099a032011-12-18 14:22:26 +01005142 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005143 void *data;
5144 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005145
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005146 if (!PyUnicode_Check(unicode)) {
5147 PyErr_BadArgument();
5148 return NULL;
5149 }
5150
5151 if (PyUnicode_READY(unicode) == -1)
5152 return NULL;
5153
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005154 if (PyUnicode_UTF8(unicode))
5155 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5156 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005157
5158 kind = PyUnicode_KIND(unicode);
5159 data = PyUnicode_DATA(unicode);
5160 size = PyUnicode_GET_LENGTH(unicode);
5161
Benjamin Petersonead6b532011-12-20 17:23:42 -06005162 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005163 default:
5164 assert(0);
5165 case PyUnicode_1BYTE_KIND:
5166 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5167 assert(!PyUnicode_IS_ASCII(unicode));
5168 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5169 case PyUnicode_2BYTE_KIND:
5170 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5171 case PyUnicode_4BYTE_KIND:
5172 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005173 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005174}
5175
Alexander Belopolsky40018472011-02-26 01:02:56 +00005176PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005177PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5178 Py_ssize_t size,
5179 const char *errors)
5180{
5181 PyObject *v, *unicode;
5182
5183 unicode = PyUnicode_FromUnicode(s, size);
5184 if (unicode == NULL)
5185 return NULL;
5186 v = _PyUnicode_AsUTF8String(unicode, errors);
5187 Py_DECREF(unicode);
5188 return v;
5189}
5190
5191PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005192PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005193{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005194 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005195}
5196
Walter Dörwald41980ca2007-08-16 21:55:45 +00005197/* --- UTF-32 Codec ------------------------------------------------------- */
5198
5199PyObject *
5200PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005201 Py_ssize_t size,
5202 const char *errors,
5203 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005204{
5205 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5206}
5207
5208PyObject *
5209PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005210 Py_ssize_t size,
5211 const char *errors,
5212 int *byteorder,
5213 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005214{
5215 const char *starts = s;
5216 Py_ssize_t startinpos;
5217 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005218 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005219 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005220 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005221 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005222 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005223 PyObject *errorHandler = NULL;
5224 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005225
Walter Dörwald41980ca2007-08-16 21:55:45 +00005226 q = (unsigned char *)s;
5227 e = q + size;
5228
5229 if (byteorder)
5230 bo = *byteorder;
5231
5232 /* Check for BOM marks (U+FEFF) in the input and adjust current
5233 byte order setting accordingly. In native mode, the leading BOM
5234 mark is skipped, in all other modes, it is copied to the output
5235 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005236 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005237 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005238 if (bom == 0x0000FEFF) {
5239 bo = -1;
5240 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005241 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005242 else if (bom == 0xFFFE0000) {
5243 bo = 1;
5244 q += 4;
5245 }
5246 if (byteorder)
5247 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005248 }
5249
Victor Stinnere64322e2012-10-30 23:12:47 +01005250 if (q == e) {
5251 if (consumed)
5252 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005253 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005254 }
5255
Victor Stinnere64322e2012-10-30 23:12:47 +01005256#ifdef WORDS_BIGENDIAN
5257 le = bo < 0;
5258#else
5259 le = bo <= 0;
5260#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005261 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005262
Victor Stinner8f674cc2013-04-17 23:02:17 +02005263 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005264 writer.min_length = (e - q + 3) / 4;
5265 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005266 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005267
Victor Stinnere64322e2012-10-30 23:12:47 +01005268 while (1) {
5269 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005270 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005271
Victor Stinnere64322e2012-10-30 23:12:47 +01005272 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005273 enum PyUnicode_Kind kind = writer.kind;
5274 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005275 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005276 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005277 if (le) {
5278 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005279 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005280 if (ch > maxch)
5281 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005282 if (kind != PyUnicode_1BYTE_KIND &&
5283 Py_UNICODE_IS_SURROGATE(ch))
5284 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005285 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005286 q += 4;
5287 } while (q <= last);
5288 }
5289 else {
5290 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005291 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005292 if (ch > maxch)
5293 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005294 if (kind != PyUnicode_1BYTE_KIND &&
5295 Py_UNICODE_IS_SURROGATE(ch))
5296 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005297 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005298 q += 4;
5299 } while (q <= last);
5300 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005301 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005302 }
5303
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005304 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005305 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005306 startinpos = ((const char *)q) - starts;
5307 endinpos = startinpos + 4;
5308 }
5309 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005310 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005311 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005312 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005313 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005314 startinpos = ((const char *)q) - starts;
5315 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005316 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005317 else {
5318 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005319 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005320 goto onError;
5321 q += 4;
5322 continue;
5323 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005324 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005325 startinpos = ((const char *)q) - starts;
5326 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005328
5329 /* The remaining input chars are ignored if the callback
5330 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005331 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005332 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005333 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005334 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005335 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005337 }
5338
Walter Dörwald41980ca2007-08-16 21:55:45 +00005339 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005341
Walter Dörwald41980ca2007-08-16 21:55:45 +00005342 Py_XDECREF(errorHandler);
5343 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005344 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005345
Benjamin Peterson29060642009-01-31 22:14:21 +00005346 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005347 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005348 Py_XDECREF(errorHandler);
5349 Py_XDECREF(exc);
5350 return NULL;
5351}
5352
5353PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005354_PyUnicode_EncodeUTF32(PyObject *str,
5355 const char *errors,
5356 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005357{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005358 enum PyUnicode_Kind kind;
5359 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005360 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005361 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005362 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005363#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005364 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005365#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005366 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005367#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005368 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005369 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005370 PyObject *errorHandler = NULL;
5371 PyObject *exc = NULL;
5372 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005373
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005374 if (!PyUnicode_Check(str)) {
5375 PyErr_BadArgument();
5376 return NULL;
5377 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005378 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005379 return NULL;
5380 kind = PyUnicode_KIND(str);
5381 data = PyUnicode_DATA(str);
5382 len = PyUnicode_GET_LENGTH(str);
5383
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005384 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005385 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005386 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005387 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005388 if (v == NULL)
5389 return NULL;
5390
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005391 /* output buffer is 4-bytes aligned */
5392 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005393 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005394 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005395 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005396 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005397 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005398
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005399 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005400 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005401 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005402 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005403 else
5404 encoding = "utf-32";
5405
5406 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005407 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5408 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005409 }
5410
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005411 pos = 0;
5412 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005413 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005414
5415 if (kind == PyUnicode_2BYTE_KIND) {
5416 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5417 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005418 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005419 else {
5420 assert(kind == PyUnicode_4BYTE_KIND);
5421 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5422 &out, native_ordering);
5423 }
5424 if (pos == len)
5425 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005426
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005427 rep = unicode_encode_call_errorhandler(
5428 errors, &errorHandler,
5429 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005430 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005431 if (!rep)
5432 goto error;
5433
5434 if (PyBytes_Check(rep)) {
5435 repsize = PyBytes_GET_SIZE(rep);
5436 if (repsize & 3) {
5437 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005438 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005439 "surrogates not allowed");
5440 goto error;
5441 }
5442 moreunits = repsize / 4;
5443 }
5444 else {
5445 assert(PyUnicode_Check(rep));
5446 if (PyUnicode_READY(rep) < 0)
5447 goto error;
5448 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5449 if (!PyUnicode_IS_ASCII(rep)) {
5450 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005451 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005452 "surrogates not allowed");
5453 goto error;
5454 }
5455 }
5456
5457 /* four bytes are reserved for each surrogate */
5458 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005459 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005460 Py_ssize_t morebytes = 4 * (moreunits - 1);
5461 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5462 /* integer overflow */
5463 PyErr_NoMemory();
5464 goto error;
5465 }
5466 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5467 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005468 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 }
5470
5471 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005472 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005473 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005474 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005475 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005476 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5477 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005478 }
5479
5480 Py_CLEAR(rep);
5481 }
5482
5483 /* Cut back to size actually needed. This is necessary for, for example,
5484 encoding of a string containing isolated surrogates and the 'ignore'
5485 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005486 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005487 if (nsize != PyBytes_GET_SIZE(v))
5488 _PyBytes_Resize(&v, nsize);
5489 Py_XDECREF(errorHandler);
5490 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005491 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005492 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005493 error:
5494 Py_XDECREF(rep);
5495 Py_XDECREF(errorHandler);
5496 Py_XDECREF(exc);
5497 Py_XDECREF(v);
5498 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005499}
5500
Alexander Belopolsky40018472011-02-26 01:02:56 +00005501PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005502PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5503 Py_ssize_t size,
5504 const char *errors,
5505 int byteorder)
5506{
5507 PyObject *result;
5508 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5509 if (tmp == NULL)
5510 return NULL;
5511 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5512 Py_DECREF(tmp);
5513 return result;
5514}
5515
5516PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005517PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005518{
Victor Stinnerb960b342011-11-20 19:12:52 +01005519 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005520}
5521
Guido van Rossumd57fd912000-03-10 22:53:23 +00005522/* --- UTF-16 Codec ------------------------------------------------------- */
5523
Tim Peters772747b2001-08-09 22:21:55 +00005524PyObject *
5525PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005526 Py_ssize_t size,
5527 const char *errors,
5528 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005529{
Walter Dörwald69652032004-09-07 20:24:22 +00005530 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5531}
5532
5533PyObject *
5534PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005535 Py_ssize_t size,
5536 const char *errors,
5537 int *byteorder,
5538 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005539{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005540 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005541 Py_ssize_t startinpos;
5542 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005543 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005544 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005545 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005546 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005547 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005548 PyObject *errorHandler = NULL;
5549 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005550 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005551
Tim Peters772747b2001-08-09 22:21:55 +00005552 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005553 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005554
5555 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005556 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005557
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005558 /* Check for BOM marks (U+FEFF) in the input and adjust current
5559 byte order setting accordingly. In native mode, the leading BOM
5560 mark is skipped, in all other modes, it is copied to the output
5561 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005562 if (bo == 0 && size >= 2) {
5563 const Py_UCS4 bom = (q[1] << 8) | q[0];
5564 if (bom == 0xFEFF) {
5565 q += 2;
5566 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005567 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005568 else if (bom == 0xFFFE) {
5569 q += 2;
5570 bo = 1;
5571 }
5572 if (byteorder)
5573 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005574 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005575
Antoine Pitrou63065d72012-05-15 23:48:04 +02005576 if (q == e) {
5577 if (consumed)
5578 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005579 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005580 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005581
Christian Heimes743e0cd2012-10-17 23:52:17 +02005582#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005583 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005584 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005585#else
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-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005588#endif
Tim Peters772747b2001-08-09 22:21:55 +00005589
Antoine Pitrou63065d72012-05-15 23:48:04 +02005590 /* Note: size will always be longer than the resulting Unicode
5591 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005592 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005593 writer.min_length = (e - q + 1) / 2;
5594 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005595 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005596
Antoine Pitrou63065d72012-05-15 23:48:04 +02005597 while (1) {
5598 Py_UCS4 ch = 0;
5599 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005600 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005601 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005602 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005603 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005604 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005605 native_ordering);
5606 else
5607 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005608 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005609 native_ordering);
5610 } else if (kind == PyUnicode_2BYTE_KIND) {
5611 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005612 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005613 native_ordering);
5614 } else {
5615 assert(kind == PyUnicode_4BYTE_KIND);
5616 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005617 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005618 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005619 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005620 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005621
Antoine Pitrou63065d72012-05-15 23:48:04 +02005622 switch (ch)
5623 {
5624 case 0:
5625 /* remaining byte at the end? (size should be even) */
5626 if (q == e || consumed)
5627 goto End;
5628 errmsg = "truncated data";
5629 startinpos = ((const char *)q) - starts;
5630 endinpos = ((const char *)e) - starts;
5631 break;
5632 /* The remaining input chars are ignored if the callback
5633 chooses to skip the input */
5634 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005635 q -= 2;
5636 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005637 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005638 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005639 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005640 endinpos = ((const char *)e) - starts;
5641 break;
5642 case 2:
5643 errmsg = "illegal encoding";
5644 startinpos = ((const char *)q) - 2 - starts;
5645 endinpos = startinpos + 2;
5646 break;
5647 case 3:
5648 errmsg = "illegal UTF-16 surrogate";
5649 startinpos = ((const char *)q) - 4 - starts;
5650 endinpos = startinpos + 2;
5651 break;
5652 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005653 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005654 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005655 continue;
5656 }
5657
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005658 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005659 errors,
5660 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005661 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005662 &starts,
5663 (const char **)&e,
5664 &startinpos,
5665 &endinpos,
5666 &exc,
5667 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005668 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005669 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005670 }
5671
Antoine Pitrou63065d72012-05-15 23:48:04 +02005672End:
Walter Dörwald69652032004-09-07 20:24:22 +00005673 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005674 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005675
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005676 Py_XDECREF(errorHandler);
5677 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005678 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005679
Benjamin Peterson29060642009-01-31 22:14:21 +00005680 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005681 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005682 Py_XDECREF(errorHandler);
5683 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684 return NULL;
5685}
5686
Tim Peters772747b2001-08-09 22:21:55 +00005687PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005688_PyUnicode_EncodeUTF16(PyObject *str,
5689 const char *errors,
5690 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005691{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005692 enum PyUnicode_Kind kind;
5693 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005694 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005695 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005696 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005697 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005698#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005699 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005700#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005701 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005702#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005703 const char *encoding;
5704 Py_ssize_t nsize, pos;
5705 PyObject *errorHandler = NULL;
5706 PyObject *exc = NULL;
5707 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005708
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005709 if (!PyUnicode_Check(str)) {
5710 PyErr_BadArgument();
5711 return NULL;
5712 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005713 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005714 return NULL;
5715 kind = PyUnicode_KIND(str);
5716 data = PyUnicode_DATA(str);
5717 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005718
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005719 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005720 if (kind == PyUnicode_4BYTE_KIND) {
5721 const Py_UCS4 *in = (const Py_UCS4 *)data;
5722 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005723 while (in < end) {
5724 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005725 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005726 }
5727 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005728 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005729 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005730 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005731 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005732 nsize = len + pairs + (byteorder == 0);
5733 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005734 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005735 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005736 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005738 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005739 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005740 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005741 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005742 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005743 }
5744 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005745 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005746 }
Tim Peters772747b2001-08-09 22:21:55 +00005747
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005748 if (kind == PyUnicode_1BYTE_KIND) {
5749 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5750 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005751 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005752
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005753 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005754 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005755 }
5756 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005757 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005758 }
5759 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005760 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005761 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005762
5763 pos = 0;
5764 while (pos < len) {
5765 Py_ssize_t repsize, moreunits;
5766
5767 if (kind == PyUnicode_2BYTE_KIND) {
5768 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5769 &out, native_ordering);
5770 }
5771 else {
5772 assert(kind == PyUnicode_4BYTE_KIND);
5773 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5774 &out, native_ordering);
5775 }
5776 if (pos == len)
5777 break;
5778
5779 rep = unicode_encode_call_errorhandler(
5780 errors, &errorHandler,
5781 encoding, "surrogates not allowed",
5782 str, &exc, pos, pos + 1, &pos);
5783 if (!rep)
5784 goto error;
5785
5786 if (PyBytes_Check(rep)) {
5787 repsize = PyBytes_GET_SIZE(rep);
5788 if (repsize & 1) {
5789 raise_encode_exception(&exc, encoding,
5790 str, pos - 1, pos,
5791 "surrogates not allowed");
5792 goto error;
5793 }
5794 moreunits = repsize / 2;
5795 }
5796 else {
5797 assert(PyUnicode_Check(rep));
5798 if (PyUnicode_READY(rep) < 0)
5799 goto error;
5800 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5801 if (!PyUnicode_IS_ASCII(rep)) {
5802 raise_encode_exception(&exc, encoding,
5803 str, pos - 1, pos,
5804 "surrogates not allowed");
5805 goto error;
5806 }
5807 }
5808
5809 /* two bytes are reserved for each surrogate */
5810 if (moreunits > 1) {
5811 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5812 Py_ssize_t morebytes = 2 * (moreunits - 1);
5813 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5814 /* integer overflow */
5815 PyErr_NoMemory();
5816 goto error;
5817 }
5818 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5819 goto error;
5820 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5821 }
5822
5823 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005824 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005825 out += moreunits;
5826 } else /* rep is unicode */ {
5827 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5828 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5829 &out, native_ordering);
5830 }
5831
5832 Py_CLEAR(rep);
5833 }
5834
5835 /* Cut back to size actually needed. This is necessary for, for example,
5836 encoding of a string containing isolated surrogates and the 'ignore' handler
5837 is used. */
5838 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5839 if (nsize != PyBytes_GET_SIZE(v))
5840 _PyBytes_Resize(&v, nsize);
5841 Py_XDECREF(errorHandler);
5842 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005843 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005844 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005845 error:
5846 Py_XDECREF(rep);
5847 Py_XDECREF(errorHandler);
5848 Py_XDECREF(exc);
5849 Py_XDECREF(v);
5850 return NULL;
5851#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005852}
5853
Alexander Belopolsky40018472011-02-26 01:02:56 +00005854PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005855PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5856 Py_ssize_t size,
5857 const char *errors,
5858 int byteorder)
5859{
5860 PyObject *result;
5861 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5862 if (tmp == NULL)
5863 return NULL;
5864 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5865 Py_DECREF(tmp);
5866 return result;
5867}
5868
5869PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005870PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005871{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005872 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005873}
5874
5875/* --- Unicode Escape Codec ----------------------------------------------- */
5876
Fredrik Lundh06d12682001-01-24 07:59:11 +00005877static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005878
Alexander Belopolsky40018472011-02-26 01:02:56 +00005879PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005880_PyUnicode_DecodeUnicodeEscape(const char *s,
5881 Py_ssize_t size,
5882 const char *errors,
5883 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005885 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005886 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005887 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005888 PyObject *errorHandler = NULL;
5889 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005890
Eric V. Smith42454af2016-10-31 09:22:08 -04005891 // so we can remember if we've seen an invalid escape char or not
5892 *first_invalid_escape = NULL;
5893
Victor Stinner62ec3312016-09-06 17:04:34 -07005894 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005895 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005896 }
5897 /* Escaped strings will always be longer than the resulting
5898 Unicode string, so we start with size here and then reduce the
5899 length after conversion to the true value.
5900 (but if the error callback returns a long replacement string
5901 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005902 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005903 writer.min_length = size;
5904 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5905 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005906 }
5907
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908 end = s + size;
5909 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005910 unsigned char c = (unsigned char) *s++;
5911 Py_UCS4 ch;
5912 int count;
5913 Py_ssize_t startinpos;
5914 Py_ssize_t endinpos;
5915 const char *message;
5916
5917#define WRITE_ASCII_CHAR(ch) \
5918 do { \
5919 assert(ch <= 127); \
5920 assert(writer.pos < writer.size); \
5921 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5922 } while(0)
5923
5924#define WRITE_CHAR(ch) \
5925 do { \
5926 if (ch <= writer.maxchar) { \
5927 assert(writer.pos < writer.size); \
5928 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5929 } \
5930 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5931 goto onError; \
5932 } \
5933 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005934
5935 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005936 if (c != '\\') {
5937 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938 continue;
5939 }
5940
Victor Stinner62ec3312016-09-06 17:04:34 -07005941 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005942 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005943 if (s >= end) {
5944 message = "\\ at end of string";
5945 goto error;
5946 }
5947 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005948
Victor Stinner62ec3312016-09-06 17:04:34 -07005949 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005950 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005951
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07005953 case '\n': continue;
5954 case '\\': WRITE_ASCII_CHAR('\\'); continue;
5955 case '\'': WRITE_ASCII_CHAR('\''); continue;
5956 case '\"': WRITE_ASCII_CHAR('\"'); continue;
5957 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005958 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07005959 case 'f': WRITE_ASCII_CHAR('\014'); continue;
5960 case 't': WRITE_ASCII_CHAR('\t'); continue;
5961 case 'n': WRITE_ASCII_CHAR('\n'); continue;
5962 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005963 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07005964 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005965 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07005966 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969 case '0': case '1': case '2': case '3':
5970 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07005971 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005972 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07005973 ch = (ch<<3) + *s++ - '0';
5974 if (s < end && '0' <= *s && *s <= '7') {
5975 ch = (ch<<3) + *s++ - '0';
5976 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977 }
Victor Stinner62ec3312016-09-06 17:04:34 -07005978 WRITE_CHAR(ch);
5979 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980
Benjamin Peterson29060642009-01-31 22:14:21 +00005981 /* hex escapes */
5982 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07005984 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005985 message = "truncated \\xXX escape";
5986 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987
Benjamin Peterson29060642009-01-31 22:14:21 +00005988 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005989 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07005990 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005991 message = "truncated \\uXXXX escape";
5992 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993
Benjamin Peterson29060642009-01-31 22:14:21 +00005994 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005995 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07005996 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005997 message = "truncated \\UXXXXXXXX escape";
5998 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07005999 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006000 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006001 ch <<= 4;
6002 if (c >= '0' && c <= '9') {
6003 ch += c - '0';
6004 }
6005 else if (c >= 'a' && c <= 'f') {
6006 ch += c - ('a' - 10);
6007 }
6008 else if (c >= 'A' && c <= 'F') {
6009 ch += c - ('A' - 10);
6010 }
6011 else {
6012 break;
6013 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006014 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006015 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006016 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006017 }
6018
6019 /* when we get here, ch is a 32-bit unicode character */
6020 if (ch > MAX_UNICODE) {
6021 message = "illegal Unicode character";
6022 goto error;
6023 }
6024
6025 WRITE_CHAR(ch);
6026 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006027
Benjamin Peterson29060642009-01-31 22:14:21 +00006028 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006029 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006030 if (ucnhash_CAPI == NULL) {
6031 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006032 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6033 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006034 if (ucnhash_CAPI == NULL) {
6035 PyErr_SetString(
6036 PyExc_UnicodeError,
6037 "\\N escapes not supported (can't load unicodedata module)"
6038 );
6039 goto onError;
6040 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006041 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006042
6043 message = "malformed \\N character escape";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006044 if (*s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006045 const char *start = ++s;
6046 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006047 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006048 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006049 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006050 namelen = s - start;
6051 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006052 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006053 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006054 ch = 0xffffffff; /* in case 'getcode' messes up */
6055 if (namelen <= INT_MAX &&
6056 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6057 &ch, 0)) {
6058 assert(ch <= MAX_UNICODE);
6059 WRITE_CHAR(ch);
6060 continue;
6061 }
6062 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006063 }
6064 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006065 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006066
6067 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006068 if (*first_invalid_escape == NULL) {
6069 *first_invalid_escape = s-1; /* Back up one char, since we've
6070 already incremented s. */
6071 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006072 WRITE_ASCII_CHAR('\\');
6073 WRITE_CHAR(c);
6074 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006075 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006076
6077 error:
6078 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006079 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006080 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006081 errors, &errorHandler,
6082 "unicodeescape", message,
6083 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006084 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006085 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006086 }
6087 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6088 goto onError;
6089 }
6090
6091#undef WRITE_ASCII_CHAR
6092#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006093 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006094
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006095 Py_XDECREF(errorHandler);
6096 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006097 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006098
Benjamin Peterson29060642009-01-31 22:14:21 +00006099 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006100 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006101 Py_XDECREF(errorHandler);
6102 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006103 return NULL;
6104}
6105
Eric V. Smith42454af2016-10-31 09:22:08 -04006106PyObject *
6107PyUnicode_DecodeUnicodeEscape(const char *s,
6108 Py_ssize_t size,
6109 const char *errors)
6110{
6111 const char *first_invalid_escape;
6112 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6113 &first_invalid_escape);
6114 if (result == NULL)
6115 return NULL;
6116 if (first_invalid_escape != NULL) {
6117 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6118 "invalid escape sequence '\\%c'",
6119 *first_invalid_escape) < 0) {
6120 Py_DECREF(result);
6121 return NULL;
6122 }
6123 }
6124 return result;
6125}
6126
Guido van Rossumd57fd912000-03-10 22:53:23 +00006127/* Return a Unicode-Escape string version of the Unicode object.
6128
6129 If quotes is true, the string is enclosed in u"" or u'' quotes as
6130 appropriate.
6131
6132*/
6133
Alexander Belopolsky40018472011-02-26 01:02:56 +00006134PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006135PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006136{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006137 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006138 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006139 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006140 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006141 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006142 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006143
Ezio Melottie7f90372012-10-05 03:33:31 +03006144 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006145 escape.
6146
Ezio Melottie7f90372012-10-05 03:33:31 +03006147 For UCS1 strings it's '\xxx', 4 bytes per source character.
6148 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6149 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006150 */
6151
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006152 if (!PyUnicode_Check(unicode)) {
6153 PyErr_BadArgument();
6154 return NULL;
6155 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006156 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006157 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006158 }
Victor Stinner358af132015-10-12 22:36:57 +02006159
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006160 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006161 if (len == 0) {
6162 return PyBytes_FromStringAndSize(NULL, 0);
6163 }
6164
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006165 kind = PyUnicode_KIND(unicode);
6166 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006167 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6168 bytes, and 1 byte characters 4. */
6169 expandsize = kind * 2 + 2;
6170 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize) {
6171 return PyErr_NoMemory();
6172 }
6173 repr = PyBytes_FromStringAndSize(NULL, 2 + expandsize * len + 1);
6174 if (repr == NULL) {
6175 return NULL;
6176 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006177
Victor Stinner62ec3312016-09-06 17:04:34 -07006178 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006180 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006181
Victor Stinner62ec3312016-09-06 17:04:34 -07006182 /* U+0000-U+00ff range */
6183 if (ch < 0x100) {
6184 if (ch >= ' ' && ch < 127) {
6185 if (ch != '\\') {
6186 /* Copy printable US ASCII as-is */
6187 *p++ = (char) ch;
6188 }
6189 /* Escape backslashes */
6190 else {
6191 *p++ = '\\';
6192 *p++ = '\\';
6193 }
6194 }
Victor Stinner358af132015-10-12 22:36:57 +02006195
Victor Stinner62ec3312016-09-06 17:04:34 -07006196 /* Map special whitespace to '\t', \n', '\r' */
6197 else if (ch == '\t') {
6198 *p++ = '\\';
6199 *p++ = 't';
6200 }
6201 else if (ch == '\n') {
6202 *p++ = '\\';
6203 *p++ = 'n';
6204 }
6205 else if (ch == '\r') {
6206 *p++ = '\\';
6207 *p++ = 'r';
6208 }
6209
6210 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6211 else {
6212 *p++ = '\\';
6213 *p++ = 'x';
6214 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6215 *p++ = Py_hexdigits[ch & 0x000F];
6216 }
Tim Petersced69f82003-09-16 20:30:58 +00006217 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006218 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6219 else if (ch < 0x10000) {
6220 /* U+0100-U+ffff */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221 *p++ = '\\';
6222 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006223 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6224 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6225 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6226 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006228 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6229 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006230
Victor Stinner62ec3312016-09-06 17:04:34 -07006231 /* Make sure that the first two digits are zero */
6232 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006233 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006234 *p++ = 'U';
6235 *p++ = '0';
6236 *p++ = '0';
6237 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6238 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6239 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6240 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6241 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6242 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006243 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006245
Victor Stinner62ec3312016-09-06 17:04:34 -07006246 assert(p - PyBytes_AS_STRING(repr) > 0);
6247 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6248 return NULL;
6249 }
6250 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006251}
6252
Alexander Belopolsky40018472011-02-26 01:02:56 +00006253PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006254PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6255 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006256{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006257 PyObject *result;
6258 PyObject *tmp = PyUnicode_FromUnicode(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006259 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006260 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006261 }
6262
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006263 result = PyUnicode_AsUnicodeEscapeString(tmp);
6264 Py_DECREF(tmp);
6265 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006266}
6267
6268/* --- Raw Unicode Escape Codec ------------------------------------------- */
6269
Alexander Belopolsky40018472011-02-26 01:02:56 +00006270PyObject *
6271PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006272 Py_ssize_t size,
6273 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006274{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006275 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006276 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006277 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006278 PyObject *errorHandler = NULL;
6279 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006280
Victor Stinner62ec3312016-09-06 17:04:34 -07006281 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006282 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006283 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006284
Guido van Rossumd57fd912000-03-10 22:53:23 +00006285 /* Escaped strings will always be longer than the resulting
6286 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006287 length after conversion to the true value. (But decoding error
6288 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006289 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006290 writer.min_length = size;
6291 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6292 goto onError;
6293 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006294
Guido van Rossumd57fd912000-03-10 22:53:23 +00006295 end = s + size;
6296 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006297 unsigned char c = (unsigned char) *s++;
6298 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006299 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006300 Py_ssize_t startinpos;
6301 Py_ssize_t endinpos;
6302 const char *message;
6303
6304#define WRITE_CHAR(ch) \
6305 do { \
6306 if (ch <= writer.maxchar) { \
6307 assert(writer.pos < writer.size); \
6308 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6309 } \
6310 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6311 goto onError; \
6312 } \
6313 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314
Benjamin Peterson29060642009-01-31 22:14:21 +00006315 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006316 if (c != '\\' || s >= end) {
6317 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006318 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006319 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006320
Victor Stinner62ec3312016-09-06 17:04:34 -07006321 c = (unsigned char) *s++;
6322 if (c == 'u') {
6323 count = 4;
6324 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006325 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006326 else if (c == 'U') {
6327 count = 8;
6328 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006329 }
6330 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006331 assert(writer.pos < writer.size);
6332 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6333 WRITE_CHAR(c);
6334 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006335 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006336 startinpos = s - starts - 2;
6337
6338 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6339 for (ch = 0; count && s < end; ++s, --count) {
6340 c = (unsigned char)*s;
6341 ch <<= 4;
6342 if (c >= '0' && c <= '9') {
6343 ch += c - '0';
6344 }
6345 else if (c >= 'a' && c <= 'f') {
6346 ch += c - ('a' - 10);
6347 }
6348 else if (c >= 'A' && c <= 'F') {
6349 ch += c - ('A' - 10);
6350 }
6351 else {
6352 break;
6353 }
6354 }
6355 if (!count) {
6356 if (ch <= MAX_UNICODE) {
6357 WRITE_CHAR(ch);
6358 continue;
6359 }
6360 message = "\\Uxxxxxxxx out of range";
6361 }
6362
6363 endinpos = s-starts;
6364 writer.min_length = end - s + writer.pos;
6365 if (unicode_decode_call_errorhandler_writer(
6366 errors, &errorHandler,
6367 "rawunicodeescape", message,
6368 &starts, &end, &startinpos, &endinpos, &exc, &s,
6369 &writer)) {
6370 goto onError;
6371 }
6372 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) {
6373 goto onError;
6374 }
6375
6376#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006377 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006378 Py_XDECREF(errorHandler);
6379 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006380 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006381
Benjamin Peterson29060642009-01-31 22:14:21 +00006382 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006383 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006384 Py_XDECREF(errorHandler);
6385 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006387
Guido van Rossumd57fd912000-03-10 22:53:23 +00006388}
6389
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006390
Alexander Belopolsky40018472011-02-26 01:02:56 +00006391PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006392PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006393{
Victor Stinner62ec3312016-09-06 17:04:34 -07006394 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006395 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006396 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006397 int kind;
6398 void *data;
6399 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006400
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006401 if (!PyUnicode_Check(unicode)) {
6402 PyErr_BadArgument();
6403 return NULL;
6404 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006405 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006406 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006407 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006408 kind = PyUnicode_KIND(unicode);
6409 data = PyUnicode_DATA(unicode);
6410 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006411 if (kind == PyUnicode_1BYTE_KIND) {
6412 return PyBytes_FromStringAndSize(data, len);
6413 }
Victor Stinner0e368262011-11-10 20:12:49 +01006414
Victor Stinner62ec3312016-09-06 17:04:34 -07006415 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6416 bytes, and 1 byte characters 4. */
6417 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006418
Victor Stinner62ec3312016-09-06 17:04:34 -07006419 if (len > PY_SSIZE_T_MAX / expandsize) {
6420 return PyErr_NoMemory();
6421 }
6422 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6423 if (repr == NULL) {
6424 return NULL;
6425 }
6426 if (len == 0) {
6427 return repr;
6428 }
6429
6430 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006431 for (pos = 0; pos < len; pos++) {
6432 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006433
Victor Stinner62ec3312016-09-06 17:04:34 -07006434 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6435 if (ch < 0x100) {
6436 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006437 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006438 /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */
6439 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006440 *p++ = '\\';
6441 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006442 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6443 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6444 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6445 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006446 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006447 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6448 else {
6449 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6450 *p++ = '\\';
6451 *p++ = 'U';
6452 *p++ = '0';
6453 *p++ = '0';
6454 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6455 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6456 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6457 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6458 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6459 *p++ = Py_hexdigits[ch & 15];
6460 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006461 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006462
Victor Stinner62ec3312016-09-06 17:04:34 -07006463 assert(p > PyBytes_AS_STRING(repr));
6464 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6465 return NULL;
6466 }
6467 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006468}
6469
Alexander Belopolsky40018472011-02-26 01:02:56 +00006470PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006471PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6472 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006473{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006474 PyObject *result;
6475 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6476 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006477 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006478 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6479 Py_DECREF(tmp);
6480 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006481}
6482
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006483/* --- Unicode Internal Codec ------------------------------------------- */
6484
Alexander Belopolsky40018472011-02-26 01:02:56 +00006485PyObject *
6486_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006487 Py_ssize_t size,
6488 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006489{
6490 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006491 Py_ssize_t startinpos;
6492 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006493 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006494 const char *end;
6495 const char *reason;
6496 PyObject *errorHandler = NULL;
6497 PyObject *exc = NULL;
6498
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006499 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006500 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006501 1))
6502 return NULL;
6503
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006504 if (size == 0)
6505 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006506
Victor Stinner8f674cc2013-04-17 23:02:17 +02006507 _PyUnicodeWriter_Init(&writer);
6508 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6509 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006510 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006511 }
6512 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006513
Victor Stinner8f674cc2013-04-17 23:02:17 +02006514 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006515 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006516 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006517 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006518 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006519 endinpos = end-starts;
6520 reason = "truncated input";
6521 goto error;
6522 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006523 /* We copy the raw representation one byte at a time because the
6524 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006525 ((char *) &uch)[0] = s[0];
6526 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006527#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006528 ((char *) &uch)[2] = s[2];
6529 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006530#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006531 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006532#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006533 /* We have to sanity check the raw data, otherwise doom looms for
6534 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006535 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006536 endinpos = s - starts + Py_UNICODE_SIZE;
6537 reason = "illegal code point (> 0x10FFFF)";
6538 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006539 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006540#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006541 s += Py_UNICODE_SIZE;
6542#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006543 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006544 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006545 Py_UNICODE uch2;
6546 ((char *) &uch2)[0] = s[0];
6547 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006548 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006549 {
Victor Stinner551ac952011-11-29 22:58:13 +01006550 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006551 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006552 }
6553 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006554#endif
6555
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006556 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006557 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006558 continue;
6559
6560 error:
6561 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006562 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006563 errors, &errorHandler,
6564 "unicode_internal", reason,
6565 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006566 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006567 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006568 }
6569
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006570 Py_XDECREF(errorHandler);
6571 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006572 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006573
Benjamin Peterson29060642009-01-31 22:14:21 +00006574 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006575 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006576 Py_XDECREF(errorHandler);
6577 Py_XDECREF(exc);
6578 return NULL;
6579}
6580
Guido van Rossumd57fd912000-03-10 22:53:23 +00006581/* --- Latin-1 Codec ------------------------------------------------------ */
6582
Alexander Belopolsky40018472011-02-26 01:02:56 +00006583PyObject *
6584PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006585 Py_ssize_t size,
6586 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006587{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006588 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006589 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006590}
6591
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006592/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006593static void
6594make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006595 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006596 PyObject *unicode,
6597 Py_ssize_t startpos, Py_ssize_t endpos,
6598 const char *reason)
6599{
6600 if (*exceptionObject == NULL) {
6601 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006602 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006603 encoding, unicode, startpos, endpos, reason);
6604 }
6605 else {
6606 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6607 goto onError;
6608 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6609 goto onError;
6610 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6611 goto onError;
6612 return;
6613 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006614 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006615 }
6616}
6617
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006618/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006619static void
6620raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006621 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006622 PyObject *unicode,
6623 Py_ssize_t startpos, Py_ssize_t endpos,
6624 const char *reason)
6625{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006626 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006627 encoding, unicode, startpos, endpos, reason);
6628 if (*exceptionObject != NULL)
6629 PyCodec_StrictErrors(*exceptionObject);
6630}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006631
6632/* error handling callback helper:
6633 build arguments, call the callback and check the arguments,
6634 put the result into newpos and return the replacement string, which
6635 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006636static PyObject *
6637unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006638 PyObject **errorHandler,
6639 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006640 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006641 Py_ssize_t startpos, Py_ssize_t endpos,
6642 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006643{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006644 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006645 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006646 PyObject *restuple;
6647 PyObject *resunicode;
6648
6649 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006650 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006651 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006652 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653 }
6654
Benjamin Petersonbac79492012-01-14 13:34:47 -05006655 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006656 return NULL;
6657 len = PyUnicode_GET_LENGTH(unicode);
6658
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006659 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006660 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006661 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006662 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006663
6664 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006666 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006667 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006669 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006670 Py_DECREF(restuple);
6671 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006672 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006673 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006674 &resunicode, newpos)) {
6675 Py_DECREF(restuple);
6676 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006677 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006678 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6679 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6680 Py_DECREF(restuple);
6681 return NULL;
6682 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006683 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006684 *newpos = len + *newpos;
6685 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006686 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006687 Py_DECREF(restuple);
6688 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006689 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006690 Py_INCREF(resunicode);
6691 Py_DECREF(restuple);
6692 return resunicode;
6693}
6694
Alexander Belopolsky40018472011-02-26 01:02:56 +00006695static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006696unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006697 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006698 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006699{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006700 /* input state */
6701 Py_ssize_t pos=0, size;
6702 int kind;
6703 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006704 /* pointer into the output */
6705 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006706 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6707 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006708 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006709 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006710 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006711 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006712 /* output object */
6713 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006714
Benjamin Petersonbac79492012-01-14 13:34:47 -05006715 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006716 return NULL;
6717 size = PyUnicode_GET_LENGTH(unicode);
6718 kind = PyUnicode_KIND(unicode);
6719 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006720 /* allocate enough for a simple encoding without
6721 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006722 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006723 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006724
6725 _PyBytesWriter_Init(&writer);
6726 str = _PyBytesWriter_Alloc(&writer, size);
6727 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006728 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006729
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006730 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006731 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006732
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006734 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006736 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006737 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006738 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006740 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006741 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006742 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006743 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006744 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006745
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006746 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006747 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006748
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006749 /* Only overallocate the buffer if it's not the last write */
6750 writer.overallocate = (collend < size);
6751
Benjamin Peterson29060642009-01-31 22:14:21 +00006752 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006753 if (error_handler == _Py_ERROR_UNKNOWN)
6754 error_handler = get_error_handler(errors);
6755
6756 switch (error_handler) {
6757 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006758 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006759 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006760
6761 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006762 memset(str, '?', collend - collstart);
6763 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006764 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006765 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006766 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006767 break;
Victor Stinner50149202015-09-22 00:26:54 +02006768
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006769 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006770 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006771 writer.min_size -= (collend - collstart);
6772 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006773 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006774 if (str == NULL)
6775 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006776 pos = collend;
6777 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006778
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006779 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006780 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006781 writer.min_size -= (collend - collstart);
6782 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006783 unicode, collstart, collend);
6784 if (str == NULL)
6785 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006786 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006787 break;
Victor Stinner50149202015-09-22 00:26:54 +02006788
Victor Stinnerc3713e92015-09-29 12:32:13 +02006789 case _Py_ERROR_SURROGATEESCAPE:
6790 for (i = collstart; i < collend; ++i) {
6791 ch = PyUnicode_READ(kind, data, i);
6792 if (ch < 0xdc80 || 0xdcff < ch) {
6793 /* Not a UTF-8b surrogate */
6794 break;
6795 }
6796 *str++ = (char)(ch - 0xdc00);
6797 ++pos;
6798 }
6799 if (i >= collend)
6800 break;
6801 collstart = pos;
6802 assert(collstart != collend);
6803 /* fallback to general error handling */
6804
Benjamin Peterson29060642009-01-31 22:14:21 +00006805 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006806 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6807 encoding, reason, unicode, &exc,
6808 collstart, collend, &newpos);
6809 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006810 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006811
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006812 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006813 writer.min_size -= 1;
6814
Victor Stinner6bd525b2015-10-09 13:10:05 +02006815 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006816 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006817 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006818 PyBytes_AS_STRING(rep),
6819 PyBytes_GET_SIZE(rep));
Victor Stinnerad771582015-10-09 12:38:53 +02006820 if (str == NULL)
6821 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006822 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006823 else {
6824 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006825
Victor Stinner6bd525b2015-10-09 13:10:05 +02006826 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006827 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006828
6829 if (PyUnicode_IS_ASCII(rep)) {
6830 /* Fast path: all characters are smaller than limit */
6831 assert(limit >= 128);
6832 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6833 str = _PyBytesWriter_WriteBytes(&writer, str,
6834 PyUnicode_DATA(rep),
6835 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006836 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006837 else {
6838 Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep);
6839
6840 str = _PyBytesWriter_Prepare(&writer, str, repsize);
6841 if (str == NULL)
6842 goto onError;
6843
6844 /* check if there is anything unencodable in the
6845 replacement and copy it to the output */
6846 for (i = 0; repsize-->0; ++i, ++str) {
6847 ch = PyUnicode_READ_CHAR(rep, i);
6848 if (ch >= limit) {
6849 raise_encode_exception(&exc, encoding, unicode,
6850 pos, pos+1, reason);
6851 goto onError;
6852 }
6853 *str = (char)ch;
6854 }
6855 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006856 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006857 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006858 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006859 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006860
6861 /* If overallocation was disabled, ensure that it was the last
6862 write. Otherwise, we missed an optimization */
6863 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006864 }
6865 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006866
Victor Stinner50149202015-09-22 00:26:54 +02006867 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006868 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006869 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006870
6871 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006872 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006873 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006874 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006875 Py_XDECREF(exc);
6876 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006877}
6878
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006879/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006880PyObject *
6881PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006882 Py_ssize_t size,
6883 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006884{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006885 PyObject *result;
6886 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6887 if (unicode == NULL)
6888 return NULL;
6889 result = unicode_encode_ucs1(unicode, errors, 256);
6890 Py_DECREF(unicode);
6891 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006892}
6893
Alexander Belopolsky40018472011-02-26 01:02:56 +00006894PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006895_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006896{
6897 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006898 PyErr_BadArgument();
6899 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006900 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006901 if (PyUnicode_READY(unicode) == -1)
6902 return NULL;
6903 /* Fast path: if it is a one-byte string, construct
6904 bytes object directly. */
6905 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6906 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6907 PyUnicode_GET_LENGTH(unicode));
6908 /* Non-Latin-1 characters present. Defer to above function to
6909 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006910 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006911}
6912
6913PyObject*
6914PyUnicode_AsLatin1String(PyObject *unicode)
6915{
6916 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006917}
6918
6919/* --- 7-bit ASCII Codec -------------------------------------------------- */
6920
Alexander Belopolsky40018472011-02-26 01:02:56 +00006921PyObject *
6922PyUnicode_DecodeASCII(const char *s,
6923 Py_ssize_t size,
6924 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006925{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006926 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006927 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006928 int kind;
6929 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006930 Py_ssize_t startinpos;
6931 Py_ssize_t endinpos;
6932 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006933 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006934 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006935 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006936 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006937
Guido van Rossumd57fd912000-03-10 22:53:23 +00006938 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006939 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006940
Guido van Rossumd57fd912000-03-10 22:53:23 +00006941 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006942 if (size == 1 && (unsigned char)s[0] < 128)
6943 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006944
Victor Stinner8f674cc2013-04-17 23:02:17 +02006945 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006946 writer.min_length = size;
6947 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006948 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006949
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006950 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006951 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006952 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006953 writer.pos = outpos;
6954 if (writer.pos == size)
6955 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006956
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006957 s += writer.pos;
6958 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006959 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006960 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006961 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006962 PyUnicode_WRITE(kind, data, writer.pos, c);
6963 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006964 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006965 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006966 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006967
6968 /* byte outsize range 0x00..0x7f: call the error handler */
6969
6970 if (error_handler == _Py_ERROR_UNKNOWN)
6971 error_handler = get_error_handler(errors);
6972
6973 switch (error_handler)
6974 {
6975 case _Py_ERROR_REPLACE:
6976 case _Py_ERROR_SURROGATEESCAPE:
6977 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006978 but we may switch to UCS2 at the first write */
6979 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6980 goto onError;
6981 kind = writer.kind;
6982 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006983
6984 if (error_handler == _Py_ERROR_REPLACE)
6985 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6986 else
6987 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6988 writer.pos++;
6989 ++s;
6990 break;
6991
6992 case _Py_ERROR_IGNORE:
6993 ++s;
6994 break;
6995
6996 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006997 startinpos = s-starts;
6998 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006999 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007000 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007001 "ascii", "ordinal not in range(128)",
7002 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007003 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007004 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007005 kind = writer.kind;
7006 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007007 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007008 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007009 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007010 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007011 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007012
Benjamin Peterson29060642009-01-31 22:14:21 +00007013 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007014 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007015 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007016 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007017 return NULL;
7018}
7019
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007020/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007021PyObject *
7022PyUnicode_EncodeASCII(const Py_UNICODE *p,
7023 Py_ssize_t size,
7024 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007025{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007026 PyObject *result;
7027 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7028 if (unicode == NULL)
7029 return NULL;
7030 result = unicode_encode_ucs1(unicode, errors, 128);
7031 Py_DECREF(unicode);
7032 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007033}
7034
Alexander Belopolsky40018472011-02-26 01:02:56 +00007035PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007036_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007037{
7038 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007039 PyErr_BadArgument();
7040 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007041 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007042 if (PyUnicode_READY(unicode) == -1)
7043 return NULL;
7044 /* Fast path: if it is an ASCII-only string, construct bytes object
7045 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007046 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007047 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7048 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007049 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007050}
7051
7052PyObject *
7053PyUnicode_AsASCIIString(PyObject *unicode)
7054{
7055 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007056}
7057
Steve Dowercc16be82016-09-08 10:35:16 -07007058#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007059
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007060/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007061
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007062#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063#define NEED_RETRY
7064#endif
7065
Victor Stinner3a50e702011-10-18 21:21:00 +02007066#ifndef WC_ERR_INVALID_CHARS
7067# define WC_ERR_INVALID_CHARS 0x0080
7068#endif
7069
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007070static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007071code_page_name(UINT code_page, PyObject **obj)
7072{
7073 *obj = NULL;
7074 if (code_page == CP_ACP)
7075 return "mbcs";
7076 if (code_page == CP_UTF7)
7077 return "CP_UTF7";
7078 if (code_page == CP_UTF8)
7079 return "CP_UTF8";
7080
7081 *obj = PyBytes_FromFormat("cp%u", code_page);
7082 if (*obj == NULL)
7083 return NULL;
7084 return PyBytes_AS_STRING(*obj);
7085}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007086
Victor Stinner3a50e702011-10-18 21:21:00 +02007087static DWORD
7088decode_code_page_flags(UINT code_page)
7089{
7090 if (code_page == CP_UTF7) {
7091 /* The CP_UTF7 decoder only supports flags=0 */
7092 return 0;
7093 }
7094 else
7095 return MB_ERR_INVALID_CHARS;
7096}
7097
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007098/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 * Decode a byte string from a Windows code page into unicode object in strict
7100 * mode.
7101 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007102 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7103 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007104 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007105static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007106decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007107 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007108 const char *in,
7109 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110{
Victor Stinner3a50e702011-10-18 21:21:00 +02007111 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007112 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114
7115 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007116 assert(insize > 0);
7117 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7118 if (outsize <= 0)
7119 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007120
7121 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007122 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007123 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007124 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007125 if (*v == NULL)
7126 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007127 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007128 }
7129 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007130 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007131 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007132 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007133 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007134 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007135 }
7136
7137 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007138 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7139 if (outsize <= 0)
7140 goto error;
7141 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007142
Victor Stinner3a50e702011-10-18 21:21:00 +02007143error:
7144 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7145 return -2;
7146 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007147 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007148}
7149
Victor Stinner3a50e702011-10-18 21:21:00 +02007150/*
7151 * Decode a byte string from a code page into unicode object with an error
7152 * handler.
7153 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007154 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007155 * UnicodeDecodeError exception and returns -1 on error.
7156 */
7157static int
7158decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007159 PyObject **v,
7160 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007161 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007162{
7163 const char *startin = in;
7164 const char *endin = in + size;
7165 const DWORD flags = decode_code_page_flags(code_page);
7166 /* Ideally, we should get reason from FormatMessage. This is the Windows
7167 2000 English version of the message. */
7168 const char *reason = "No mapping for the Unicode character exists "
7169 "in the target code page.";
7170 /* each step cannot decode more than 1 character, but a character can be
7171 represented as a surrogate pair */
7172 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007173 int insize;
7174 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007175 PyObject *errorHandler = NULL;
7176 PyObject *exc = NULL;
7177 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007178 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 DWORD err;
7180 int ret = -1;
7181
7182 assert(size > 0);
7183
7184 encoding = code_page_name(code_page, &encoding_obj);
7185 if (encoding == NULL)
7186 return -1;
7187
Victor Stinner7d00cc12014-03-17 23:08:06 +01007188 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007189 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7190 UnicodeDecodeError. */
7191 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7192 if (exc != NULL) {
7193 PyCodec_StrictErrors(exc);
7194 Py_CLEAR(exc);
7195 }
7196 goto error;
7197 }
7198
7199 if (*v == NULL) {
7200 /* Create unicode object */
7201 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7202 PyErr_NoMemory();
7203 goto error;
7204 }
Victor Stinnerab595942011-12-17 04:59:06 +01007205 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007206 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 if (*v == NULL)
7208 goto error;
7209 startout = PyUnicode_AS_UNICODE(*v);
7210 }
7211 else {
7212 /* Extend unicode object */
7213 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7214 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7215 PyErr_NoMemory();
7216 goto error;
7217 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007218 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 goto error;
7220 startout = PyUnicode_AS_UNICODE(*v) + n;
7221 }
7222
7223 /* Decode the byte string character per character */
7224 out = startout;
7225 while (in < endin)
7226 {
7227 /* Decode a character */
7228 insize = 1;
7229 do
7230 {
7231 outsize = MultiByteToWideChar(code_page, flags,
7232 in, insize,
7233 buffer, Py_ARRAY_LENGTH(buffer));
7234 if (outsize > 0)
7235 break;
7236 err = GetLastError();
7237 if (err != ERROR_NO_UNICODE_TRANSLATION
7238 && err != ERROR_INSUFFICIENT_BUFFER)
7239 {
7240 PyErr_SetFromWindowsErr(0);
7241 goto error;
7242 }
7243 insize++;
7244 }
7245 /* 4=maximum length of a UTF-8 sequence */
7246 while (insize <= 4 && (in + insize) <= endin);
7247
7248 if (outsize <= 0) {
7249 Py_ssize_t startinpos, endinpos, outpos;
7250
Victor Stinner7d00cc12014-03-17 23:08:06 +01007251 /* last character in partial decode? */
7252 if (in + insize >= endin && !final)
7253 break;
7254
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 startinpos = in - startin;
7256 endinpos = startinpos + 1;
7257 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007258 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 errors, &errorHandler,
7260 encoding, reason,
7261 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007262 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007263 {
7264 goto error;
7265 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007266 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007267 }
7268 else {
7269 in += insize;
7270 memcpy(out, buffer, outsize * sizeof(wchar_t));
7271 out += outsize;
7272 }
7273 }
7274
7275 /* write a NUL character at the end */
7276 *out = 0;
7277
7278 /* Extend unicode object */
7279 outsize = out - startout;
7280 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007281 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007282 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007283 /* (in - startin) <= size and size is an int */
7284 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007285
7286error:
7287 Py_XDECREF(encoding_obj);
7288 Py_XDECREF(errorHandler);
7289 Py_XDECREF(exc);
7290 return ret;
7291}
7292
Victor Stinner3a50e702011-10-18 21:21:00 +02007293static PyObject *
7294decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007295 const char *s, Py_ssize_t size,
7296 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007297{
Victor Stinner76a31a62011-11-04 00:05:13 +01007298 PyObject *v = NULL;
7299 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007300
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 if (code_page < 0) {
7302 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7303 return NULL;
7304 }
7305
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007306 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007307 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007308
Victor Stinner76a31a62011-11-04 00:05:13 +01007309 do
7310 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007311#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007312 if (size > INT_MAX) {
7313 chunk_size = INT_MAX;
7314 final = 0;
7315 done = 0;
7316 }
7317 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007318#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007319 {
7320 chunk_size = (int)size;
7321 final = (consumed == NULL);
7322 done = 1;
7323 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007324
Victor Stinner76a31a62011-11-04 00:05:13 +01007325 if (chunk_size == 0 && done) {
7326 if (v != NULL)
7327 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007328 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007329 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007330
Victor Stinner76a31a62011-11-04 00:05:13 +01007331 converted = decode_code_page_strict(code_page, &v,
7332 s, chunk_size);
7333 if (converted == -2)
7334 converted = decode_code_page_errors(code_page, &v,
7335 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007336 errors, final);
7337 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007338
7339 if (converted < 0) {
7340 Py_XDECREF(v);
7341 return NULL;
7342 }
7343
7344 if (consumed)
7345 *consumed += converted;
7346
7347 s += converted;
7348 size -= converted;
7349 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007350
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007351 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007352}
7353
Alexander Belopolsky40018472011-02-26 01:02:56 +00007354PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007355PyUnicode_DecodeCodePageStateful(int code_page,
7356 const char *s,
7357 Py_ssize_t size,
7358 const char *errors,
7359 Py_ssize_t *consumed)
7360{
7361 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7362}
7363
7364PyObject *
7365PyUnicode_DecodeMBCSStateful(const char *s,
7366 Py_ssize_t size,
7367 const char *errors,
7368 Py_ssize_t *consumed)
7369{
7370 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7371}
7372
7373PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007374PyUnicode_DecodeMBCS(const char *s,
7375 Py_ssize_t size,
7376 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007377{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007378 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7379}
7380
Victor Stinner3a50e702011-10-18 21:21:00 +02007381static DWORD
7382encode_code_page_flags(UINT code_page, const char *errors)
7383{
7384 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007385 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007386 }
7387 else if (code_page == CP_UTF7) {
7388 /* CP_UTF7 only supports flags=0 */
7389 return 0;
7390 }
7391 else {
7392 if (errors != NULL && strcmp(errors, "replace") == 0)
7393 return 0;
7394 else
7395 return WC_NO_BEST_FIT_CHARS;
7396 }
7397}
7398
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007399/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007400 * Encode a Unicode string to a Windows code page into a byte string in strict
7401 * mode.
7402 *
7403 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007404 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007405 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007406static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007407encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007408 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007410{
Victor Stinner554f3f02010-06-16 23:33:54 +00007411 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007412 BOOL *pusedDefaultChar = &usedDefaultChar;
7413 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007414 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007415 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 const DWORD flags = encode_code_page_flags(code_page, NULL);
7417 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007418 /* Create a substring so that we can get the UTF-16 representation
7419 of just the slice under consideration. */
7420 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007421
Martin v. Löwis3d325192011-11-04 18:23:06 +01007422 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007423
Victor Stinner3a50e702011-10-18 21:21:00 +02007424 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007425 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007427 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007428
Victor Stinner2fc507f2011-11-04 20:06:39 +01007429 substring = PyUnicode_Substring(unicode, offset, offset+len);
7430 if (substring == NULL)
7431 return -1;
7432 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7433 if (p == NULL) {
7434 Py_DECREF(substring);
7435 return -1;
7436 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007437 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007438
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007439 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007441 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007442 NULL, 0,
7443 NULL, pusedDefaultChar);
7444 if (outsize <= 0)
7445 goto error;
7446 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 if (pusedDefaultChar && *pusedDefaultChar) {
7448 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007450 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007451
Victor Stinner3a50e702011-10-18 21:21:00 +02007452 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007453 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007455 if (*outbytes == NULL) {
7456 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007457 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007458 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007460 }
7461 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007462 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007463 const Py_ssize_t n = PyBytes_Size(*outbytes);
7464 if (outsize > PY_SSIZE_T_MAX - n) {
7465 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007466 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007467 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007468 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007469 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7470 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007471 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007472 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007473 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007474 }
7475
7476 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007477 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007478 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007479 out, outsize,
7480 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007481 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007482 if (outsize <= 0)
7483 goto error;
7484 if (pusedDefaultChar && *pusedDefaultChar)
7485 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007486 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007487
Victor Stinner3a50e702011-10-18 21:21:00 +02007488error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007489 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007490 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7491 return -2;
7492 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007493 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007494}
7495
Victor Stinner3a50e702011-10-18 21:21:00 +02007496/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007497 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007498 * error handler.
7499 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007500 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007501 * -1 on other error.
7502 */
7503static int
7504encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007505 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007506 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007507{
Victor Stinner3a50e702011-10-18 21:21:00 +02007508 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007509 Py_ssize_t pos = unicode_offset;
7510 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007511 /* Ideally, we should get reason from FormatMessage. This is the Windows
7512 2000 English version of the message. */
7513 const char *reason = "invalid character";
7514 /* 4=maximum length of a UTF-8 sequence */
7515 char buffer[4];
7516 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7517 Py_ssize_t outsize;
7518 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007519 PyObject *errorHandler = NULL;
7520 PyObject *exc = NULL;
7521 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007522 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007523 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007524 PyObject *rep;
7525 int ret = -1;
7526
7527 assert(insize > 0);
7528
7529 encoding = code_page_name(code_page, &encoding_obj);
7530 if (encoding == NULL)
7531 return -1;
7532
7533 if (errors == NULL || strcmp(errors, "strict") == 0) {
7534 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7535 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007536 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007537 if (exc != NULL) {
7538 PyCodec_StrictErrors(exc);
7539 Py_DECREF(exc);
7540 }
7541 Py_XDECREF(encoding_obj);
7542 return -1;
7543 }
7544
7545 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7546 pusedDefaultChar = &usedDefaultChar;
7547 else
7548 pusedDefaultChar = NULL;
7549
7550 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7551 PyErr_NoMemory();
7552 goto error;
7553 }
7554 outsize = insize * Py_ARRAY_LENGTH(buffer);
7555
7556 if (*outbytes == NULL) {
7557 /* Create string object */
7558 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7559 if (*outbytes == NULL)
7560 goto error;
7561 out = PyBytes_AS_STRING(*outbytes);
7562 }
7563 else {
7564 /* Extend string object */
7565 Py_ssize_t n = PyBytes_Size(*outbytes);
7566 if (n > PY_SSIZE_T_MAX - outsize) {
7567 PyErr_NoMemory();
7568 goto error;
7569 }
7570 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7571 goto error;
7572 out = PyBytes_AS_STRING(*outbytes) + n;
7573 }
7574
7575 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007576 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007577 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007578 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7579 wchar_t chars[2];
7580 int charsize;
7581 if (ch < 0x10000) {
7582 chars[0] = (wchar_t)ch;
7583 charsize = 1;
7584 }
7585 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007586 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7587 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007588 charsize = 2;
7589 }
7590
Victor Stinner3a50e702011-10-18 21:21:00 +02007591 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007592 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007593 buffer, Py_ARRAY_LENGTH(buffer),
7594 NULL, pusedDefaultChar);
7595 if (outsize > 0) {
7596 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7597 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007598 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007599 memcpy(out, buffer, outsize);
7600 out += outsize;
7601 continue;
7602 }
7603 }
7604 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7605 PyErr_SetFromWindowsErr(0);
7606 goto error;
7607 }
7608
Victor Stinner3a50e702011-10-18 21:21:00 +02007609 rep = unicode_encode_call_errorhandler(
7610 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007611 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007612 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007613 if (rep == NULL)
7614 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007615 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007616
7617 if (PyBytes_Check(rep)) {
7618 outsize = PyBytes_GET_SIZE(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 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7629 out += outsize;
7630 }
7631 else {
7632 Py_ssize_t i;
7633 enum PyUnicode_Kind kind;
7634 void *data;
7635
Benjamin Petersonbac79492012-01-14 13:34:47 -05007636 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007637 Py_DECREF(rep);
7638 goto error;
7639 }
7640
7641 outsize = PyUnicode_GET_LENGTH(rep);
7642 if (outsize != 1) {
7643 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7644 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7645 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7646 Py_DECREF(rep);
7647 goto error;
7648 }
7649 out = PyBytes_AS_STRING(*outbytes) + offset;
7650 }
7651 kind = PyUnicode_KIND(rep);
7652 data = PyUnicode_DATA(rep);
7653 for (i=0; i < outsize; i++) {
7654 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7655 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007656 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007657 encoding, unicode,
7658 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007659 "unable to encode error handler result to ASCII");
7660 Py_DECREF(rep);
7661 goto error;
7662 }
7663 *out = (unsigned char)ch;
7664 out++;
7665 }
7666 }
7667 Py_DECREF(rep);
7668 }
7669 /* write a NUL byte */
7670 *out = 0;
7671 outsize = out - PyBytes_AS_STRING(*outbytes);
7672 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7673 if (_PyBytes_Resize(outbytes, outsize) < 0)
7674 goto error;
7675 ret = 0;
7676
7677error:
7678 Py_XDECREF(encoding_obj);
7679 Py_XDECREF(errorHandler);
7680 Py_XDECREF(exc);
7681 return ret;
7682}
7683
Victor Stinner3a50e702011-10-18 21:21:00 +02007684static PyObject *
7685encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007686 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007687 const char *errors)
7688{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007689 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007690 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007691 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007692 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007693
Victor Stinner29dacf22015-01-26 16:41:32 +01007694 if (!PyUnicode_Check(unicode)) {
7695 PyErr_BadArgument();
7696 return NULL;
7697 }
7698
Benjamin Petersonbac79492012-01-14 13:34:47 -05007699 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007700 return NULL;
7701 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007702
Victor Stinner3a50e702011-10-18 21:21:00 +02007703 if (code_page < 0) {
7704 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7705 return NULL;
7706 }
7707
Martin v. Löwis3d325192011-11-04 18:23:06 +01007708 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007709 return PyBytes_FromStringAndSize(NULL, 0);
7710
Victor Stinner7581cef2011-11-03 22:32:33 +01007711 offset = 0;
7712 do
7713 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007714#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007715 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007716 chunks. */
7717 if (len > INT_MAX/2) {
7718 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007719 done = 0;
7720 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007721 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007722#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007723 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007724 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007725 done = 1;
7726 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007727
Victor Stinner76a31a62011-11-04 00:05:13 +01007728 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007729 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007730 errors);
7731 if (ret == -2)
7732 ret = encode_code_page_errors(code_page, &outbytes,
7733 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007734 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007735 if (ret < 0) {
7736 Py_XDECREF(outbytes);
7737 return NULL;
7738 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007739
Victor Stinner7581cef2011-11-03 22:32:33 +01007740 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007741 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007742 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007743
Victor Stinner3a50e702011-10-18 21:21:00 +02007744 return outbytes;
7745}
7746
7747PyObject *
7748PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7749 Py_ssize_t size,
7750 const char *errors)
7751{
Victor Stinner7581cef2011-11-03 22:32:33 +01007752 PyObject *unicode, *res;
7753 unicode = PyUnicode_FromUnicode(p, size);
7754 if (unicode == NULL)
7755 return NULL;
7756 res = encode_code_page(CP_ACP, unicode, errors);
7757 Py_DECREF(unicode);
7758 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007759}
7760
7761PyObject *
7762PyUnicode_EncodeCodePage(int code_page,
7763 PyObject *unicode,
7764 const char *errors)
7765{
Victor Stinner7581cef2011-11-03 22:32:33 +01007766 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007767}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007768
Alexander Belopolsky40018472011-02-26 01:02:56 +00007769PyObject *
7770PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007771{
Victor Stinner7581cef2011-11-03 22:32:33 +01007772 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007773}
7774
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007775#undef NEED_RETRY
7776
Steve Dowercc16be82016-09-08 10:35:16 -07007777#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007778
Guido van Rossumd57fd912000-03-10 22:53:23 +00007779/* --- Character Mapping Codec -------------------------------------------- */
7780
Victor Stinnerfb161b12013-04-18 01:44:27 +02007781static int
7782charmap_decode_string(const char *s,
7783 Py_ssize_t size,
7784 PyObject *mapping,
7785 const char *errors,
7786 _PyUnicodeWriter *writer)
7787{
7788 const char *starts = s;
7789 const char *e;
7790 Py_ssize_t startinpos, endinpos;
7791 PyObject *errorHandler = NULL, *exc = NULL;
7792 Py_ssize_t maplen;
7793 enum PyUnicode_Kind mapkind;
7794 void *mapdata;
7795 Py_UCS4 x;
7796 unsigned char ch;
7797
7798 if (PyUnicode_READY(mapping) == -1)
7799 return -1;
7800
7801 maplen = PyUnicode_GET_LENGTH(mapping);
7802 mapdata = PyUnicode_DATA(mapping);
7803 mapkind = PyUnicode_KIND(mapping);
7804
7805 e = s + size;
7806
7807 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7808 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7809 * is disabled in encoding aliases, latin1 is preferred because
7810 * its implementation is faster. */
7811 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7812 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7813 Py_UCS4 maxchar = writer->maxchar;
7814
7815 assert (writer->kind == PyUnicode_1BYTE_KIND);
7816 while (s < e) {
7817 ch = *s;
7818 x = mapdata_ucs1[ch];
7819 if (x > maxchar) {
7820 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7821 goto onError;
7822 maxchar = writer->maxchar;
7823 outdata = (Py_UCS1 *)writer->data;
7824 }
7825 outdata[writer->pos] = x;
7826 writer->pos++;
7827 ++s;
7828 }
7829 return 0;
7830 }
7831
7832 while (s < e) {
7833 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7834 enum PyUnicode_Kind outkind = writer->kind;
7835 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7836 if (outkind == PyUnicode_1BYTE_KIND) {
7837 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7838 Py_UCS4 maxchar = writer->maxchar;
7839 while (s < e) {
7840 ch = *s;
7841 x = mapdata_ucs2[ch];
7842 if (x > maxchar)
7843 goto Error;
7844 outdata[writer->pos] = x;
7845 writer->pos++;
7846 ++s;
7847 }
7848 break;
7849 }
7850 else if (outkind == PyUnicode_2BYTE_KIND) {
7851 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7852 while (s < e) {
7853 ch = *s;
7854 x = mapdata_ucs2[ch];
7855 if (x == 0xFFFE)
7856 goto Error;
7857 outdata[writer->pos] = x;
7858 writer->pos++;
7859 ++s;
7860 }
7861 break;
7862 }
7863 }
7864 ch = *s;
7865
7866 if (ch < maplen)
7867 x = PyUnicode_READ(mapkind, mapdata, ch);
7868 else
7869 x = 0xfffe; /* invalid value */
7870Error:
7871 if (x == 0xfffe)
7872 {
7873 /* undefined mapping */
7874 startinpos = s-starts;
7875 endinpos = startinpos+1;
7876 if (unicode_decode_call_errorhandler_writer(
7877 errors, &errorHandler,
7878 "charmap", "character maps to <undefined>",
7879 &starts, &e, &startinpos, &endinpos, &exc, &s,
7880 writer)) {
7881 goto onError;
7882 }
7883 continue;
7884 }
7885
7886 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7887 goto onError;
7888 ++s;
7889 }
7890 Py_XDECREF(errorHandler);
7891 Py_XDECREF(exc);
7892 return 0;
7893
7894onError:
7895 Py_XDECREF(errorHandler);
7896 Py_XDECREF(exc);
7897 return -1;
7898}
7899
7900static int
7901charmap_decode_mapping(const char *s,
7902 Py_ssize_t size,
7903 PyObject *mapping,
7904 const char *errors,
7905 _PyUnicodeWriter *writer)
7906{
7907 const char *starts = s;
7908 const char *e;
7909 Py_ssize_t startinpos, endinpos;
7910 PyObject *errorHandler = NULL, *exc = NULL;
7911 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007912 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007913
7914 e = s + size;
7915
7916 while (s < e) {
7917 ch = *s;
7918
7919 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7920 key = PyLong_FromLong((long)ch);
7921 if (key == NULL)
7922 goto onError;
7923
7924 item = PyObject_GetItem(mapping, key);
7925 Py_DECREF(key);
7926 if (item == NULL) {
7927 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7928 /* No mapping found means: mapping is undefined. */
7929 PyErr_Clear();
7930 goto Undefined;
7931 } else
7932 goto onError;
7933 }
7934
7935 /* Apply mapping */
7936 if (item == Py_None)
7937 goto Undefined;
7938 if (PyLong_Check(item)) {
7939 long value = PyLong_AS_LONG(item);
7940 if (value == 0xFFFE)
7941 goto Undefined;
7942 if (value < 0 || value > MAX_UNICODE) {
7943 PyErr_Format(PyExc_TypeError,
7944 "character mapping must be in range(0x%lx)",
7945 (unsigned long)MAX_UNICODE + 1);
7946 goto onError;
7947 }
7948
7949 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7950 goto onError;
7951 }
7952 else if (PyUnicode_Check(item)) {
7953 if (PyUnicode_READY(item) == -1)
7954 goto onError;
7955 if (PyUnicode_GET_LENGTH(item) == 1) {
7956 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7957 if (value == 0xFFFE)
7958 goto Undefined;
7959 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7960 goto onError;
7961 }
7962 else {
7963 writer->overallocate = 1;
7964 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7965 goto onError;
7966 }
7967 }
7968 else {
7969 /* wrong return value */
7970 PyErr_SetString(PyExc_TypeError,
7971 "character mapping must return integer, None or str");
7972 goto onError;
7973 }
7974 Py_CLEAR(item);
7975 ++s;
7976 continue;
7977
7978Undefined:
7979 /* undefined mapping */
7980 Py_CLEAR(item);
7981 startinpos = s-starts;
7982 endinpos = startinpos+1;
7983 if (unicode_decode_call_errorhandler_writer(
7984 errors, &errorHandler,
7985 "charmap", "character maps to <undefined>",
7986 &starts, &e, &startinpos, &endinpos, &exc, &s,
7987 writer)) {
7988 goto onError;
7989 }
7990 }
7991 Py_XDECREF(errorHandler);
7992 Py_XDECREF(exc);
7993 return 0;
7994
7995onError:
7996 Py_XDECREF(item);
7997 Py_XDECREF(errorHandler);
7998 Py_XDECREF(exc);
7999 return -1;
8000}
8001
Alexander Belopolsky40018472011-02-26 01:02:56 +00008002PyObject *
8003PyUnicode_DecodeCharmap(const char *s,
8004 Py_ssize_t size,
8005 PyObject *mapping,
8006 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008007{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008008 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008009
Guido van Rossumd57fd912000-03-10 22:53:23 +00008010 /* Default to Latin-1 */
8011 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008012 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008013
Guido van Rossumd57fd912000-03-10 22:53:23 +00008014 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008015 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008016 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008017 writer.min_length = size;
8018 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008019 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008020
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008021 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008022 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8023 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008024 }
8025 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008026 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8027 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008028 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008029 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008030
Benjamin Peterson29060642009-01-31 22:14:21 +00008031 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008032 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008033 return NULL;
8034}
8035
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008036/* Charmap encoding: the lookup table */
8037
Alexander Belopolsky40018472011-02-26 01:02:56 +00008038struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008039 PyObject_HEAD
8040 unsigned char level1[32];
8041 int count2, count3;
8042 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008043};
8044
8045static PyObject*
8046encoding_map_size(PyObject *obj, PyObject* args)
8047{
8048 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008049 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008051}
8052
8053static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008054 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008055 PyDoc_STR("Return the size (in bytes) of this object") },
8056 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008057};
8058
8059static void
8060encoding_map_dealloc(PyObject* o)
8061{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008062 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008063}
8064
8065static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008066 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008067 "EncodingMap", /*tp_name*/
8068 sizeof(struct encoding_map), /*tp_basicsize*/
8069 0, /*tp_itemsize*/
8070 /* methods */
8071 encoding_map_dealloc, /*tp_dealloc*/
8072 0, /*tp_print*/
8073 0, /*tp_getattr*/
8074 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008075 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 0, /*tp_repr*/
8077 0, /*tp_as_number*/
8078 0, /*tp_as_sequence*/
8079 0, /*tp_as_mapping*/
8080 0, /*tp_hash*/
8081 0, /*tp_call*/
8082 0, /*tp_str*/
8083 0, /*tp_getattro*/
8084 0, /*tp_setattro*/
8085 0, /*tp_as_buffer*/
8086 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8087 0, /*tp_doc*/
8088 0, /*tp_traverse*/
8089 0, /*tp_clear*/
8090 0, /*tp_richcompare*/
8091 0, /*tp_weaklistoffset*/
8092 0, /*tp_iter*/
8093 0, /*tp_iternext*/
8094 encoding_map_methods, /*tp_methods*/
8095 0, /*tp_members*/
8096 0, /*tp_getset*/
8097 0, /*tp_base*/
8098 0, /*tp_dict*/
8099 0, /*tp_descr_get*/
8100 0, /*tp_descr_set*/
8101 0, /*tp_dictoffset*/
8102 0, /*tp_init*/
8103 0, /*tp_alloc*/
8104 0, /*tp_new*/
8105 0, /*tp_free*/
8106 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008107};
8108
8109PyObject*
8110PyUnicode_BuildEncodingMap(PyObject* string)
8111{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008112 PyObject *result;
8113 struct encoding_map *mresult;
8114 int i;
8115 int need_dict = 0;
8116 unsigned char level1[32];
8117 unsigned char level2[512];
8118 unsigned char *mlevel1, *mlevel2, *mlevel3;
8119 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008120 int kind;
8121 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008122 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008123 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008124
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008125 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008126 PyErr_BadArgument();
8127 return NULL;
8128 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008129 kind = PyUnicode_KIND(string);
8130 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008131 length = PyUnicode_GET_LENGTH(string);
8132 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008133 memset(level1, 0xFF, sizeof level1);
8134 memset(level2, 0xFF, sizeof level2);
8135
8136 /* If there isn't a one-to-one mapping of NULL to \0,
8137 or if there are non-BMP characters, we need to use
8138 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008139 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008140 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008141 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008142 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008143 ch = PyUnicode_READ(kind, data, i);
8144 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008145 need_dict = 1;
8146 break;
8147 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008148 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008149 /* unmapped character */
8150 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008151 l1 = ch >> 11;
8152 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008153 if (level1[l1] == 0xFF)
8154 level1[l1] = count2++;
8155 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008156 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008157 }
8158
8159 if (count2 >= 0xFF || count3 >= 0xFF)
8160 need_dict = 1;
8161
8162 if (need_dict) {
8163 PyObject *result = PyDict_New();
8164 PyObject *key, *value;
8165 if (!result)
8166 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008167 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008168 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008169 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008170 if (!key || !value)
8171 goto failed1;
8172 if (PyDict_SetItem(result, key, value) == -1)
8173 goto failed1;
8174 Py_DECREF(key);
8175 Py_DECREF(value);
8176 }
8177 return result;
8178 failed1:
8179 Py_XDECREF(key);
8180 Py_XDECREF(value);
8181 Py_DECREF(result);
8182 return NULL;
8183 }
8184
8185 /* Create a three-level trie */
8186 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8187 16*count2 + 128*count3 - 1);
8188 if (!result)
8189 return PyErr_NoMemory();
8190 PyObject_Init(result, &EncodingMapType);
8191 mresult = (struct encoding_map*)result;
8192 mresult->count2 = count2;
8193 mresult->count3 = count3;
8194 mlevel1 = mresult->level1;
8195 mlevel2 = mresult->level23;
8196 mlevel3 = mresult->level23 + 16*count2;
8197 memcpy(mlevel1, level1, 32);
8198 memset(mlevel2, 0xFF, 16*count2);
8199 memset(mlevel3, 0, 128*count3);
8200 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008201 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008202 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008203 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8204 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008205 /* unmapped character */
8206 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008207 o1 = ch>>11;
8208 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008209 i2 = 16*mlevel1[o1] + o2;
8210 if (mlevel2[i2] == 0xFF)
8211 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008212 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008213 i3 = 128*mlevel2[i2] + o3;
8214 mlevel3[i3] = i;
8215 }
8216 return result;
8217}
8218
8219static int
Victor Stinner22168992011-11-20 17:09:18 +01008220encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008221{
8222 struct encoding_map *map = (struct encoding_map*)mapping;
8223 int l1 = c>>11;
8224 int l2 = (c>>7) & 0xF;
8225 int l3 = c & 0x7F;
8226 int i;
8227
Victor Stinner22168992011-11-20 17:09:18 +01008228 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008230 if (c == 0)
8231 return 0;
8232 /* level 1*/
8233 i = map->level1[l1];
8234 if (i == 0xFF) {
8235 return -1;
8236 }
8237 /* level 2*/
8238 i = map->level23[16*i+l2];
8239 if (i == 0xFF) {
8240 return -1;
8241 }
8242 /* level 3 */
8243 i = map->level23[16*map->count2 + 128*i + l3];
8244 if (i == 0) {
8245 return -1;
8246 }
8247 return i;
8248}
8249
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008250/* Lookup the character ch in the mapping. If the character
8251 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008252 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008253static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008254charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008255{
Christian Heimes217cfd12007-12-02 14:31:20 +00008256 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008257 PyObject *x;
8258
8259 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 x = PyObject_GetItem(mapping, w);
8262 Py_DECREF(w);
8263 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8265 /* No mapping found means: mapping is undefined. */
8266 PyErr_Clear();
8267 x = Py_None;
8268 Py_INCREF(x);
8269 return x;
8270 } else
8271 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008272 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008273 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008275 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 long value = PyLong_AS_LONG(x);
8277 if (value < 0 || value > 255) {
8278 PyErr_SetString(PyExc_TypeError,
8279 "character mapping must be in range(256)");
8280 Py_DECREF(x);
8281 return NULL;
8282 }
8283 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008284 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008285 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008286 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008287 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 /* wrong return value */
8289 PyErr_Format(PyExc_TypeError,
8290 "character mapping must return integer, bytes or None, not %.400s",
8291 x->ob_type->tp_name);
8292 Py_DECREF(x);
8293 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008294 }
8295}
8296
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008297static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008298charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008299{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008300 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8301 /* exponentially overallocate to minimize reallocations */
8302 if (requiredsize < 2*outsize)
8303 requiredsize = 2*outsize;
8304 if (_PyBytes_Resize(outobj, requiredsize))
8305 return -1;
8306 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008307}
8308
Benjamin Peterson14339b62009-01-31 16:36:08 +00008309typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008311} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008312/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008313 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314 space is available. Return a new reference to the object that
8315 was put in the output buffer, or Py_None, if the mapping was undefined
8316 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008317 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008318static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008319charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008320 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008321{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008322 PyObject *rep;
8323 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008324 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325
Christian Heimes90aa7642007-12-19 02:45:37 +00008326 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008327 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008328 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008329 if (res == -1)
8330 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008331 if (outsize<requiredsize)
8332 if (charmapencode_resize(outobj, outpos, requiredsize))
8333 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008334 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 outstart[(*outpos)++] = (char)res;
8336 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008337 }
8338
8339 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008340 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008341 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008342 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008343 Py_DECREF(rep);
8344 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008345 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008346 if (PyLong_Check(rep)) {
8347 Py_ssize_t requiredsize = *outpos+1;
8348 if (outsize<requiredsize)
8349 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8350 Py_DECREF(rep);
8351 return enc_EXCEPTION;
8352 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008353 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008355 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 else {
8357 const char *repchars = PyBytes_AS_STRING(rep);
8358 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8359 Py_ssize_t requiredsize = *outpos+repsize;
8360 if (outsize<requiredsize)
8361 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8362 Py_DECREF(rep);
8363 return enc_EXCEPTION;
8364 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008365 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 memcpy(outstart + *outpos, repchars, repsize);
8367 *outpos += repsize;
8368 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008370 Py_DECREF(rep);
8371 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008372}
8373
8374/* handle an error in PyUnicode_EncodeCharmap
8375 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008376static int
8377charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008378 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008379 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008380 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008381 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382{
8383 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008384 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008385 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008386 enum PyUnicode_Kind kind;
8387 void *data;
8388 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008390 Py_ssize_t collstartpos = *inpos;
8391 Py_ssize_t collendpos = *inpos+1;
8392 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008393 char *encoding = "charmap";
8394 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008395 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008396 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008397 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398
Benjamin Petersonbac79492012-01-14 13:34:47 -05008399 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008400 return -1;
8401 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402 /* find all unencodable characters */
8403 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008404 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008405 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008406 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008407 val = encoding_map_lookup(ch, mapping);
8408 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 break;
8410 ++collendpos;
8411 continue;
8412 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008413
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008414 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8415 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 if (rep==NULL)
8417 return -1;
8418 else if (rep!=Py_None) {
8419 Py_DECREF(rep);
8420 break;
8421 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008422 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008423 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008424 }
8425 /* cache callback name lookup
8426 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008427 if (*error_handler == _Py_ERROR_UNKNOWN)
8428 *error_handler = get_error_handler(errors);
8429
8430 switch (*error_handler) {
8431 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008432 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008433 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008434
8435 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008436 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 x = charmapencode_output('?', mapping, res, respos);
8438 if (x==enc_EXCEPTION) {
8439 return -1;
8440 }
8441 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008442 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 return -1;
8444 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008445 }
8446 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008447 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008448 *inpos = collendpos;
8449 break;
Victor Stinner50149202015-09-22 00:26:54 +02008450
8451 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008452 /* generate replacement (temporarily (mis)uses p) */
8453 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 char buffer[2+29+1+1];
8455 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008456 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008457 for (cp = buffer; *cp; ++cp) {
8458 x = charmapencode_output(*cp, mapping, res, respos);
8459 if (x==enc_EXCEPTION)
8460 return -1;
8461 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008462 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 return -1;
8464 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008465 }
8466 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008467 *inpos = collendpos;
8468 break;
Victor Stinner50149202015-09-22 00:26:54 +02008469
Benjamin Peterson14339b62009-01-31 16:36:08 +00008470 default:
Victor Stinner50149202015-09-22 00:26:54 +02008471 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008472 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008474 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008476 if (PyBytes_Check(repunicode)) {
8477 /* Directly copy bytes result to output. */
8478 Py_ssize_t outsize = PyBytes_Size(*res);
8479 Py_ssize_t requiredsize;
8480 repsize = PyBytes_Size(repunicode);
8481 requiredsize = *respos + repsize;
8482 if (requiredsize > outsize)
8483 /* Make room for all additional bytes. */
8484 if (charmapencode_resize(res, respos, requiredsize)) {
8485 Py_DECREF(repunicode);
8486 return -1;
8487 }
8488 memcpy(PyBytes_AsString(*res) + *respos,
8489 PyBytes_AsString(repunicode), repsize);
8490 *respos += repsize;
8491 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008492 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008493 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008494 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008495 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008496 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008497 Py_DECREF(repunicode);
8498 return -1;
8499 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008500 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008501 data = PyUnicode_DATA(repunicode);
8502 kind = PyUnicode_KIND(repunicode);
8503 for (index = 0; index < repsize; index++) {
8504 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8505 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008507 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008508 return -1;
8509 }
8510 else if (x==enc_FAILED) {
8511 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008512 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 return -1;
8514 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008515 }
8516 *inpos = newpos;
8517 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518 }
8519 return 0;
8520}
8521
Alexander Belopolsky40018472011-02-26 01:02:56 +00008522PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008523_PyUnicode_EncodeCharmap(PyObject *unicode,
8524 PyObject *mapping,
8525 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008526{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 /* output object */
8528 PyObject *res = NULL;
8529 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008530 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008531 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008532 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008533 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008534 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008535 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008536 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008537 void *data;
8538 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539
Benjamin Petersonbac79492012-01-14 13:34:47 -05008540 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008541 return NULL;
8542 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008543 data = PyUnicode_DATA(unicode);
8544 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008545
Guido van Rossumd57fd912000-03-10 22:53:23 +00008546 /* Default to Latin-1 */
8547 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008548 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008549
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008550 /* allocate enough for a simple encoding without
8551 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008552 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008553 if (res == NULL)
8554 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008555 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008556 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008557
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008559 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008561 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 if (x==enc_EXCEPTION) /* error */
8563 goto onError;
8564 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008565 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008566 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008567 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008568 &res, &respos)) {
8569 goto onError;
8570 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008571 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 else
8573 /* done with this character => adjust input position */
8574 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008575 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008576
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008578 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008579 if (_PyBytes_Resize(&res, respos) < 0)
8580 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008581
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008582 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008583 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008584 return res;
8585
Benjamin Peterson29060642009-01-31 22:14:21 +00008586 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587 Py_XDECREF(res);
8588 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008589 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008590 return NULL;
8591}
8592
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008593/* Deprecated */
8594PyObject *
8595PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8596 Py_ssize_t size,
8597 PyObject *mapping,
8598 const char *errors)
8599{
8600 PyObject *result;
8601 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8602 if (unicode == NULL)
8603 return NULL;
8604 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8605 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008606 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008607}
8608
Alexander Belopolsky40018472011-02-26 01:02:56 +00008609PyObject *
8610PyUnicode_AsCharmapString(PyObject *unicode,
8611 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008612{
8613 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 PyErr_BadArgument();
8615 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008616 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008617 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008618}
8619
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008620/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008621static void
8622make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008623 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008624 Py_ssize_t startpos, Py_ssize_t endpos,
8625 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008626{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008628 *exceptionObject = _PyUnicodeTranslateError_Create(
8629 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008630 }
8631 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8633 goto onError;
8634 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8635 goto onError;
8636 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8637 goto onError;
8638 return;
8639 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008640 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008641 }
8642}
8643
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644/* error handling callback helper:
8645 build arguments, call the callback and check the arguments,
8646 put the result into newpos and return the replacement string, which
8647 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008648static PyObject *
8649unicode_translate_call_errorhandler(const char *errors,
8650 PyObject **errorHandler,
8651 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008653 Py_ssize_t startpos, Py_ssize_t endpos,
8654 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008655{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008656 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008657
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008658 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659 PyObject *restuple;
8660 PyObject *resunicode;
8661
8662 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008665 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008666 }
8667
8668 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008670 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008672
8673 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008674 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008675 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008677 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008678 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008679 Py_DECREF(restuple);
8680 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008681 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008682 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008683 &resunicode, &i_newpos)) {
8684 Py_DECREF(restuple);
8685 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008686 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008687 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008689 else
8690 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008691 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008692 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008693 Py_DECREF(restuple);
8694 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008695 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696 Py_INCREF(resunicode);
8697 Py_DECREF(restuple);
8698 return resunicode;
8699}
8700
8701/* Lookup the character ch in the mapping and put the result in result,
8702 which must be decrefed by the caller.
8703 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008704static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008705charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008706{
Christian Heimes217cfd12007-12-02 14:31:20 +00008707 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008708 PyObject *x;
8709
8710 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008712 x = PyObject_GetItem(mapping, w);
8713 Py_DECREF(w);
8714 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8716 /* No mapping found means: use 1:1 mapping. */
8717 PyErr_Clear();
8718 *result = NULL;
8719 return 0;
8720 } else
8721 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008722 }
8723 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008724 *result = x;
8725 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008726 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008727 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008729 if (value < 0 || value > MAX_UNICODE) {
8730 PyErr_Format(PyExc_ValueError,
8731 "character mapping must be in range(0x%x)",
8732 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008733 Py_DECREF(x);
8734 return -1;
8735 }
8736 *result = x;
8737 return 0;
8738 }
8739 else if (PyUnicode_Check(x)) {
8740 *result = x;
8741 return 0;
8742 }
8743 else {
8744 /* wrong return value */
8745 PyErr_SetString(PyExc_TypeError,
8746 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008747 Py_DECREF(x);
8748 return -1;
8749 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008750}
Victor Stinner1194ea02014-04-04 19:37:40 +02008751
8752/* lookup the character, write the result into the writer.
8753 Return 1 if the result was written into the writer, return 0 if the mapping
8754 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008755static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008756charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8757 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008758{
Victor Stinner1194ea02014-04-04 19:37:40 +02008759 PyObject *item;
8760
8761 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008762 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008763
8764 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008765 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008766 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008767 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008769 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008770 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008771
8772 if (item == Py_None) {
8773 Py_DECREF(item);
8774 return 0;
8775 }
8776
8777 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008778 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8779 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8780 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008781 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8782 Py_DECREF(item);
8783 return -1;
8784 }
8785 Py_DECREF(item);
8786 return 1;
8787 }
8788
8789 if (!PyUnicode_Check(item)) {
8790 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008791 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008792 }
8793
8794 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8795 Py_DECREF(item);
8796 return -1;
8797 }
8798
8799 Py_DECREF(item);
8800 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008801}
8802
Victor Stinner89a76ab2014-04-05 11:44:04 +02008803static int
8804unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8805 Py_UCS1 *translate)
8806{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008807 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008808 int ret = 0;
8809
Victor Stinner89a76ab2014-04-05 11:44:04 +02008810 if (charmaptranslate_lookup(ch, mapping, &item)) {
8811 return -1;
8812 }
8813
8814 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008815 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008816 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008817 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008818 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008819 /* not found => default to 1:1 mapping */
8820 translate[ch] = ch;
8821 return 1;
8822 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008823 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008824 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008825 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8826 used it */
8827 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008828 /* invalid character or character outside ASCII:
8829 skip the fast translate */
8830 goto exit;
8831 }
8832 translate[ch] = (Py_UCS1)replace;
8833 }
8834 else if (PyUnicode_Check(item)) {
8835 Py_UCS4 replace;
8836
8837 if (PyUnicode_READY(item) == -1) {
8838 Py_DECREF(item);
8839 return -1;
8840 }
8841 if (PyUnicode_GET_LENGTH(item) != 1)
8842 goto exit;
8843
8844 replace = PyUnicode_READ_CHAR(item, 0);
8845 if (replace > 127)
8846 goto exit;
8847 translate[ch] = (Py_UCS1)replace;
8848 }
8849 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008850 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008851 goto exit;
8852 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008853 ret = 1;
8854
Benjamin Peterson1365de72014-04-07 20:15:41 -04008855 exit:
8856 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008857 return ret;
8858}
8859
8860/* Fast path for ascii => ascii translation. Return 1 if the whole string
8861 was translated into writer, return 0 if the input string was partially
8862 translated into writer, raise an exception and return -1 on error. */
8863static int
8864unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008865 _PyUnicodeWriter *writer, int ignore,
8866 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008867{
Victor Stinner872b2912014-04-05 14:27:07 +02008868 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008869 Py_ssize_t len;
8870 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008871 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008872
Victor Stinner89a76ab2014-04-05 11:44:04 +02008873 len = PyUnicode_GET_LENGTH(input);
8874
Victor Stinner872b2912014-04-05 14:27:07 +02008875 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008876
8877 in = PyUnicode_1BYTE_DATA(input);
8878 end = in + len;
8879
8880 assert(PyUnicode_IS_ASCII(writer->buffer));
8881 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8882 out = PyUnicode_1BYTE_DATA(writer->buffer);
8883
Victor Stinner872b2912014-04-05 14:27:07 +02008884 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008885 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008886 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008887 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008888 int translate = unicode_fast_translate_lookup(mapping, ch,
8889 ascii_table);
8890 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008891 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008892 if (translate == 0)
8893 goto exit;
8894 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008895 }
Victor Stinner872b2912014-04-05 14:27:07 +02008896 if (ch2 == 0xfe) {
8897 if (ignore)
8898 continue;
8899 goto exit;
8900 }
8901 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008902 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008903 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008904 }
Victor Stinner872b2912014-04-05 14:27:07 +02008905 res = 1;
8906
8907exit:
8908 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008909 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008910 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008911}
8912
Victor Stinner3222da22015-10-01 22:07:32 +02008913static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008914_PyUnicode_TranslateCharmap(PyObject *input,
8915 PyObject *mapping,
8916 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008917{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008918 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008919 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008920 Py_ssize_t size, i;
8921 int kind;
8922 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008923 _PyUnicodeWriter writer;
8924 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008925 char *reason = "character maps to <undefined>";
8926 PyObject *errorHandler = NULL;
8927 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008928 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008929 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008930
Guido van Rossumd57fd912000-03-10 22:53:23 +00008931 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008932 PyErr_BadArgument();
8933 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008934 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008936 if (PyUnicode_READY(input) == -1)
8937 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008938 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008939 kind = PyUnicode_KIND(input);
8940 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008941
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008942 if (size == 0)
8943 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008944
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008945 /* allocate enough for a simple 1:1 translation without
8946 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008947 _PyUnicodeWriter_Init(&writer);
8948 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008949 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008950
Victor Stinner872b2912014-04-05 14:27:07 +02008951 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8952
Victor Stinner33798672016-03-01 21:59:58 +01008953 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008954 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008955 if (PyUnicode_IS_ASCII(input)) {
8956 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8957 if (res < 0) {
8958 _PyUnicodeWriter_Dealloc(&writer);
8959 return NULL;
8960 }
8961 if (res == 1)
8962 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008963 }
Victor Stinner33798672016-03-01 21:59:58 +01008964 else {
8965 i = 0;
8966 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008968 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008969 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008970 int translate;
8971 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8972 Py_ssize_t newpos;
8973 /* startpos for collecting untranslatable chars */
8974 Py_ssize_t collstart;
8975 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008976 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008977
Victor Stinner1194ea02014-04-04 19:37:40 +02008978 ch = PyUnicode_READ(kind, data, i);
8979 translate = charmaptranslate_output(ch, mapping, &writer);
8980 if (translate < 0)
8981 goto onError;
8982
8983 if (translate != 0) {
8984 /* it worked => adjust input pointer */
8985 ++i;
8986 continue;
8987 }
8988
8989 /* untranslatable character */
8990 collstart = i;
8991 collend = i+1;
8992
8993 /* find all untranslatable characters */
8994 while (collend < size) {
8995 PyObject *x;
8996 ch = PyUnicode_READ(kind, data, collend);
8997 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008998 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008999 Py_XDECREF(x);
9000 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009001 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009002 ++collend;
9003 }
9004
9005 if (ignore) {
9006 i = collend;
9007 }
9008 else {
9009 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9010 reason, input, &exc,
9011 collstart, collend, &newpos);
9012 if (repunicode == NULL)
9013 goto onError;
9014 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009015 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009016 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009017 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009018 Py_DECREF(repunicode);
9019 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009020 }
9021 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009022 Py_XDECREF(exc);
9023 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009024 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009025
Benjamin Peterson29060642009-01-31 22:14:21 +00009026 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009027 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009028 Py_XDECREF(exc);
9029 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009030 return NULL;
9031}
9032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009033/* Deprecated. Use PyUnicode_Translate instead. */
9034PyObject *
9035PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9036 Py_ssize_t size,
9037 PyObject *mapping,
9038 const char *errors)
9039{
Christian Heimes5f520f42012-09-11 14:03:25 +02009040 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009041 PyObject *unicode = PyUnicode_FromUnicode(p, size);
9042 if (!unicode)
9043 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009044 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9045 Py_DECREF(unicode);
9046 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047}
9048
Alexander Belopolsky40018472011-02-26 01:02:56 +00009049PyObject *
9050PyUnicode_Translate(PyObject *str,
9051 PyObject *mapping,
9052 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009053{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009054 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009055 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009056 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009057}
Tim Petersced69f82003-09-16 20:30:58 +00009058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009060fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009061{
9062 /* No need to call PyUnicode_READY(self) because this function is only
9063 called as a callback from fixup() which does it already. */
9064 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9065 const int kind = PyUnicode_KIND(self);
9066 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02009067 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009068 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009069 Py_ssize_t i;
9070
9071 for (i = 0; i < len; ++i) {
9072 ch = PyUnicode_READ(kind, data, i);
9073 fixed = 0;
9074 if (ch > 127) {
9075 if (Py_UNICODE_ISSPACE(ch))
9076 fixed = ' ';
9077 else {
9078 const int decimal = Py_UNICODE_TODECIMAL(ch);
9079 if (decimal >= 0)
9080 fixed = '0' + decimal;
9081 }
9082 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009083 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009084 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009085 PyUnicode_WRITE(kind, data, i, fixed);
9086 }
Victor Stinnere6abb482012-05-02 01:15:40 +02009087 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07009088 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009090 }
9091
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05009092 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009093}
9094
9095PyObject *
9096_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9097{
9098 if (!PyUnicode_Check(unicode)) {
9099 PyErr_BadInternalCall();
9100 return NULL;
9101 }
9102 if (PyUnicode_READY(unicode) == -1)
9103 return NULL;
9104 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
9105 /* If the string is already ASCII, just return the same string */
9106 Py_INCREF(unicode);
9107 return unicode;
9108 }
Victor Stinner9310abb2011-10-05 00:59:23 +02009109 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009110}
9111
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009112PyObject *
9113PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9114 Py_ssize_t length)
9115{
Victor Stinnerf0124502011-11-21 23:12:56 +01009116 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009117 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009118 Py_UCS4 maxchar;
9119 enum PyUnicode_Kind kind;
9120 void *data;
9121
Victor Stinner99d7ad02012-02-22 13:37:39 +01009122 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009123 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009124 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009125 if (ch > 127) {
9126 int decimal = Py_UNICODE_TODECIMAL(ch);
9127 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009128 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009129 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009130 }
9131 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009132
9133 /* Copy to a new string */
9134 decimal = PyUnicode_New(length, maxchar);
9135 if (decimal == NULL)
9136 return decimal;
9137 kind = PyUnicode_KIND(decimal);
9138 data = PyUnicode_DATA(decimal);
9139 /* Iterate over code points */
9140 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009141 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009142 if (ch > 127) {
9143 int decimal = Py_UNICODE_TODECIMAL(ch);
9144 if (decimal >= 0)
9145 ch = '0' + decimal;
9146 }
9147 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009148 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009149 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009150}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009151/* --- Decimal Encoder ---------------------------------------------------- */
9152
Alexander Belopolsky40018472011-02-26 01:02:56 +00009153int
9154PyUnicode_EncodeDecimal(Py_UNICODE *s,
9155 Py_ssize_t length,
9156 char *output,
9157 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009158{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009159 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009160 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009161 enum PyUnicode_Kind kind;
9162 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009163
9164 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009165 PyErr_BadArgument();
9166 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009167 }
9168
Victor Stinner42bf7752011-11-21 22:52:58 +01009169 unicode = PyUnicode_FromUnicode(s, length);
9170 if (unicode == NULL)
9171 return -1;
9172
Benjamin Petersonbac79492012-01-14 13:34:47 -05009173 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009174 Py_DECREF(unicode);
9175 return -1;
9176 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009177 kind = PyUnicode_KIND(unicode);
9178 data = PyUnicode_DATA(unicode);
9179
Victor Stinnerb84d7232011-11-22 01:50:07 +01009180 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009181 PyObject *exc;
9182 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009183 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009184 Py_ssize_t startpos;
9185
9186 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009187
Benjamin Peterson29060642009-01-31 22:14:21 +00009188 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009189 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009190 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009191 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009192 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009193 decimal = Py_UNICODE_TODECIMAL(ch);
9194 if (decimal >= 0) {
9195 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009196 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009197 continue;
9198 }
9199 if (0 < ch && ch < 256) {
9200 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009201 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009202 continue;
9203 }
Victor Stinner6345be92011-11-25 20:09:01 +01009204
Victor Stinner42bf7752011-11-21 22:52:58 +01009205 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009206 exc = NULL;
9207 raise_encode_exception(&exc, "decimal", unicode,
9208 startpos, startpos+1,
9209 "invalid decimal Unicode string");
9210 Py_XDECREF(exc);
9211 Py_DECREF(unicode);
9212 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009213 }
9214 /* 0-terminate the output string */
9215 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009216 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009217 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009218}
9219
Guido van Rossumd57fd912000-03-10 22:53:23 +00009220/* --- Helpers ------------------------------------------------------------ */
9221
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009222/* helper macro to fixup start/end slice values */
9223#define ADJUST_INDICES(start, end, len) \
9224 if (end > len) \
9225 end = len; \
9226 else if (end < 0) { \
9227 end += len; \
9228 if (end < 0) \
9229 end = 0; \
9230 } \
9231 if (start < 0) { \
9232 start += len; \
9233 if (start < 0) \
9234 start = 0; \
9235 }
9236
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009237static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009238any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009239 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009240 Py_ssize_t end,
9241 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009242{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009243 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009244 void *buf1, *buf2;
9245 Py_ssize_t len1, len2, result;
9246
9247 kind1 = PyUnicode_KIND(s1);
9248 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009249 if (kind1 < kind2)
9250 return -1;
9251
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009252 len1 = PyUnicode_GET_LENGTH(s1);
9253 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009254 ADJUST_INDICES(start, end, len1);
9255 if (end - start < len2)
9256 return -1;
9257
9258 buf1 = PyUnicode_DATA(s1);
9259 buf2 = PyUnicode_DATA(s2);
9260 if (len2 == 1) {
9261 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9262 result = findchar((const char *)buf1 + kind1*start,
9263 kind1, end - start, ch, direction);
9264 if (result == -1)
9265 return -1;
9266 else
9267 return start + result;
9268 }
9269
9270 if (kind2 != kind1) {
9271 buf2 = _PyUnicode_AsKind(s2, kind1);
9272 if (!buf2)
9273 return -2;
9274 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009275
Victor Stinner794d5672011-10-10 03:21:36 +02009276 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009277 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009278 case PyUnicode_1BYTE_KIND:
9279 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9280 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9281 else
9282 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9283 break;
9284 case PyUnicode_2BYTE_KIND:
9285 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9286 break;
9287 case PyUnicode_4BYTE_KIND:
9288 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9289 break;
9290 default:
9291 assert(0); result = -2;
9292 }
9293 }
9294 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009295 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009296 case PyUnicode_1BYTE_KIND:
9297 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9298 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9299 else
9300 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9301 break;
9302 case PyUnicode_2BYTE_KIND:
9303 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9304 break;
9305 case PyUnicode_4BYTE_KIND:
9306 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9307 break;
9308 default:
9309 assert(0); result = -2;
9310 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009311 }
9312
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009313 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009314 PyMem_Free(buf2);
9315
9316 return result;
9317}
9318
9319Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009320_PyUnicode_InsertThousandsGrouping(
9321 PyObject *unicode, Py_ssize_t index,
9322 Py_ssize_t n_buffer,
9323 void *digits, Py_ssize_t n_digits,
9324 Py_ssize_t min_width,
9325 const char *grouping, PyObject *thousands_sep,
9326 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327{
Victor Stinner41a863c2012-02-24 00:37:51 +01009328 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009329 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009330 Py_ssize_t thousands_sep_len;
9331 Py_ssize_t len;
9332
9333 if (unicode != NULL) {
9334 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009335 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009336 }
9337 else {
9338 kind = PyUnicode_1BYTE_KIND;
9339 data = NULL;
9340 }
9341 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9342 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9343 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9344 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009345 if (thousands_sep_kind < kind) {
9346 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9347 if (!thousands_sep_data)
9348 return -1;
9349 }
9350 else {
9351 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9352 if (!data)
9353 return -1;
9354 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009355 }
9356
Benjamin Petersonead6b532011-12-20 17:23:42 -06009357 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009358 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009359 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009360 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009361 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009362 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009363 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009364 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009365 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009366 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009367 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009368 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009369 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009371 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009372 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009373 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009374 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009375 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009377 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009378 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009379 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009380 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009381 break;
9382 default:
9383 assert(0);
9384 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009385 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009386 if (unicode != NULL && thousands_sep_kind != kind) {
9387 if (thousands_sep_kind < kind)
9388 PyMem_Free(thousands_sep_data);
9389 else
9390 PyMem_Free(data);
9391 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009392 if (unicode == NULL) {
9393 *maxchar = 127;
9394 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009395 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009396 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009397 }
9398 }
9399 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009400}
9401
9402
Alexander Belopolsky40018472011-02-26 01:02:56 +00009403Py_ssize_t
9404PyUnicode_Count(PyObject *str,
9405 PyObject *substr,
9406 Py_ssize_t start,
9407 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009408{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009409 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009410 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009411 void *buf1 = NULL, *buf2 = NULL;
9412 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009413
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009414 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009415 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009416
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009417 kind1 = PyUnicode_KIND(str);
9418 kind2 = PyUnicode_KIND(substr);
9419 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009420 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009421
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009422 len1 = PyUnicode_GET_LENGTH(str);
9423 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009424 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009425 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009426 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009427
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009428 buf1 = PyUnicode_DATA(str);
9429 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009430 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009431 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009432 if (!buf2)
9433 goto onError;
9434 }
9435
9436 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009438 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009439 result = asciilib_count(
9440 ((Py_UCS1*)buf1) + start, end - start,
9441 buf2, len2, PY_SSIZE_T_MAX
9442 );
9443 else
9444 result = ucs1lib_count(
9445 ((Py_UCS1*)buf1) + start, end - start,
9446 buf2, len2, PY_SSIZE_T_MAX
9447 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009448 break;
9449 case PyUnicode_2BYTE_KIND:
9450 result = ucs2lib_count(
9451 ((Py_UCS2*)buf1) + start, end - start,
9452 buf2, len2, PY_SSIZE_T_MAX
9453 );
9454 break;
9455 case PyUnicode_4BYTE_KIND:
9456 result = ucs4lib_count(
9457 ((Py_UCS4*)buf1) + start, end - start,
9458 buf2, len2, PY_SSIZE_T_MAX
9459 );
9460 break;
9461 default:
9462 assert(0); result = 0;
9463 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009464
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009465 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 PyMem_Free(buf2);
9467
Guido van Rossumd57fd912000-03-10 22:53:23 +00009468 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009469 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009470 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471 PyMem_Free(buf2);
9472 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009473}
9474
Alexander Belopolsky40018472011-02-26 01:02:56 +00009475Py_ssize_t
9476PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009477 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009478 Py_ssize_t start,
9479 Py_ssize_t end,
9480 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009481{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009482 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009483 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009484
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009485 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009486}
9487
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009488Py_ssize_t
9489PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9490 Py_ssize_t start, Py_ssize_t end,
9491 int direction)
9492{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009493 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009494 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495 if (PyUnicode_READY(str) == -1)
9496 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009497 if (start < 0 || end < 0) {
9498 PyErr_SetString(PyExc_IndexError, "string index out of range");
9499 return -2;
9500 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009501 if (end > PyUnicode_GET_LENGTH(str))
9502 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009503 if (start >= end)
9504 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009505 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009506 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9507 kind, end-start, ch, direction);
9508 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009509 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009510 else
9511 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512}
9513
Alexander Belopolsky40018472011-02-26 01:02:56 +00009514static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009515tailmatch(PyObject *self,
9516 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009517 Py_ssize_t start,
9518 Py_ssize_t end,
9519 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009520{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009521 int kind_self;
9522 int kind_sub;
9523 void *data_self;
9524 void *data_sub;
9525 Py_ssize_t offset;
9526 Py_ssize_t i;
9527 Py_ssize_t end_sub;
9528
9529 if (PyUnicode_READY(self) == -1 ||
9530 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009531 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009532
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009533 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9534 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009535 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009536 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009538 if (PyUnicode_GET_LENGTH(substring) == 0)
9539 return 1;
9540
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009541 kind_self = PyUnicode_KIND(self);
9542 data_self = PyUnicode_DATA(self);
9543 kind_sub = PyUnicode_KIND(substring);
9544 data_sub = PyUnicode_DATA(substring);
9545 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9546
9547 if (direction > 0)
9548 offset = end;
9549 else
9550 offset = start;
9551
9552 if (PyUnicode_READ(kind_self, data_self, offset) ==
9553 PyUnicode_READ(kind_sub, data_sub, 0) &&
9554 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9555 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9556 /* If both are of the same kind, memcmp is sufficient */
9557 if (kind_self == kind_sub) {
9558 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009559 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 data_sub,
9561 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009562 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009563 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009564 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 else {
9566 /* We do not need to compare 0 and len(substring)-1 because
9567 the if statement above ensured already that they are equal
9568 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569 for (i = 1; i < end_sub; ++i) {
9570 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9571 PyUnicode_READ(kind_sub, data_sub, i))
9572 return 0;
9573 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009574 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009575 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009576 }
9577
9578 return 0;
9579}
9580
Alexander Belopolsky40018472011-02-26 01:02:56 +00009581Py_ssize_t
9582PyUnicode_Tailmatch(PyObject *str,
9583 PyObject *substr,
9584 Py_ssize_t start,
9585 Py_ssize_t end,
9586 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009587{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009588 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009589 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009590
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009591 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009592}
9593
Guido van Rossumd57fd912000-03-10 22:53:23 +00009594/* Apply fixfct filter to the Unicode object self and return a
9595 reference to the modified object */
9596
Alexander Belopolsky40018472011-02-26 01:02:56 +00009597static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009598fixup(PyObject *self,
9599 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009600{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009601 PyObject *u;
9602 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009603 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009604
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009605 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009606 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009607 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009608 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009609
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009610 /* fix functions return the new maximum character in a string,
9611 if the kind of the resulting unicode object does not change,
9612 everything is fine. Otherwise we need to change the string kind
9613 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009614 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009615
9616 if (maxchar_new == 0) {
9617 /* no changes */;
9618 if (PyUnicode_CheckExact(self)) {
9619 Py_DECREF(u);
9620 Py_INCREF(self);
9621 return self;
9622 }
9623 else
9624 return u;
9625 }
9626
Victor Stinnere6abb482012-05-02 01:15:40 +02009627 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009628
Victor Stinnereaab6042011-12-11 22:22:39 +01009629 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009630 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009631
9632 /* In case the maximum character changed, we need to
9633 convert the string to the new category. */
9634 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9635 if (v == NULL) {
9636 Py_DECREF(u);
9637 return NULL;
9638 }
9639 if (maxchar_new > maxchar_old) {
9640 /* If the maxchar increased so that the kind changed, not all
9641 characters are representable anymore and we need to fix the
9642 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009643 _PyUnicode_FastCopyCharacters(v, 0,
9644 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009645 maxchar_old = fixfct(v);
9646 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009647 }
9648 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009649 _PyUnicode_FastCopyCharacters(v, 0,
9650 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009652 Py_DECREF(u);
9653 assert(_PyUnicode_CheckConsistency(v, 1));
9654 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009655}
9656
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009657static PyObject *
9658ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009659{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009660 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9661 char *resdata, *data = PyUnicode_DATA(self);
9662 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009663
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009664 res = PyUnicode_New(len, 127);
9665 if (res == NULL)
9666 return NULL;
9667 resdata = PyUnicode_DATA(res);
9668 if (lower)
9669 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009670 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009671 _Py_bytes_upper(resdata, data, len);
9672 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009673}
9674
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009675static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009676handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009677{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009678 Py_ssize_t j;
9679 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009680 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009681 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009682
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009683 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9684
9685 where ! is a negation and \p{xxx} is a character with property xxx.
9686 */
9687 for (j = i - 1; j >= 0; j--) {
9688 c = PyUnicode_READ(kind, data, j);
9689 if (!_PyUnicode_IsCaseIgnorable(c))
9690 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009691 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009692 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9693 if (final_sigma) {
9694 for (j = i + 1; j < length; j++) {
9695 c = PyUnicode_READ(kind, data, j);
9696 if (!_PyUnicode_IsCaseIgnorable(c))
9697 break;
9698 }
9699 final_sigma = j == length || !_PyUnicode_IsCased(c);
9700 }
9701 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009702}
9703
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009704static int
9705lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9706 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009707{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009708 /* Obscure special case. */
9709 if (c == 0x3A3) {
9710 mapped[0] = handle_capital_sigma(kind, data, length, i);
9711 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009712 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009713 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009714}
9715
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009716static Py_ssize_t
9717do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009718{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009719 Py_ssize_t i, k = 0;
9720 int n_res, j;
9721 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009722
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009723 c = PyUnicode_READ(kind, data, 0);
9724 n_res = _PyUnicode_ToUpperFull(c, mapped);
9725 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009726 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009727 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009728 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009729 for (i = 1; i < length; i++) {
9730 c = PyUnicode_READ(kind, data, i);
9731 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9732 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009733 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009734 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009735 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009736 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009737 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009738}
9739
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009740static Py_ssize_t
9741do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9742 Py_ssize_t i, k = 0;
9743
9744 for (i = 0; i < length; i++) {
9745 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9746 int n_res, j;
9747 if (Py_UNICODE_ISUPPER(c)) {
9748 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9749 }
9750 else if (Py_UNICODE_ISLOWER(c)) {
9751 n_res = _PyUnicode_ToUpperFull(c, mapped);
9752 }
9753 else {
9754 n_res = 1;
9755 mapped[0] = c;
9756 }
9757 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009758 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009759 res[k++] = mapped[j];
9760 }
9761 }
9762 return k;
9763}
9764
9765static Py_ssize_t
9766do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9767 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009768{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009769 Py_ssize_t i, k = 0;
9770
9771 for (i = 0; i < length; i++) {
9772 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9773 int n_res, j;
9774 if (lower)
9775 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9776 else
9777 n_res = _PyUnicode_ToUpperFull(c, mapped);
9778 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009779 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009780 res[k++] = mapped[j];
9781 }
9782 }
9783 return k;
9784}
9785
9786static Py_ssize_t
9787do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9788{
9789 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9790}
9791
9792static Py_ssize_t
9793do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9794{
9795 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9796}
9797
Benjamin Petersone51757f2012-01-12 21:10:29 -05009798static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009799do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9800{
9801 Py_ssize_t i, k = 0;
9802
9803 for (i = 0; i < length; i++) {
9804 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9805 Py_UCS4 mapped[3];
9806 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9807 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009808 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009809 res[k++] = mapped[j];
9810 }
9811 }
9812 return k;
9813}
9814
9815static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009816do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9817{
9818 Py_ssize_t i, k = 0;
9819 int previous_is_cased;
9820
9821 previous_is_cased = 0;
9822 for (i = 0; i < length; i++) {
9823 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9824 Py_UCS4 mapped[3];
9825 int n_res, j;
9826
9827 if (previous_is_cased)
9828 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9829 else
9830 n_res = _PyUnicode_ToTitleFull(c, mapped);
9831
9832 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009833 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009834 res[k++] = mapped[j];
9835 }
9836
9837 previous_is_cased = _PyUnicode_IsCased(c);
9838 }
9839 return k;
9840}
9841
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009842static PyObject *
9843case_operation(PyObject *self,
9844 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9845{
9846 PyObject *res = NULL;
9847 Py_ssize_t length, newlength = 0;
9848 int kind, outkind;
9849 void *data, *outdata;
9850 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9851
Benjamin Petersoneea48462012-01-16 14:28:50 -05009852 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009853
9854 kind = PyUnicode_KIND(self);
9855 data = PyUnicode_DATA(self);
9856 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009857 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009858 PyErr_SetString(PyExc_OverflowError, "string is too long");
9859 return NULL;
9860 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009861 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009862 if (tmp == NULL)
9863 return PyErr_NoMemory();
9864 newlength = perform(kind, data, length, tmp, &maxchar);
9865 res = PyUnicode_New(newlength, maxchar);
9866 if (res == NULL)
9867 goto leave;
9868 tmpend = tmp + newlength;
9869 outdata = PyUnicode_DATA(res);
9870 outkind = PyUnicode_KIND(res);
9871 switch (outkind) {
9872 case PyUnicode_1BYTE_KIND:
9873 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9874 break;
9875 case PyUnicode_2BYTE_KIND:
9876 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9877 break;
9878 case PyUnicode_4BYTE_KIND:
9879 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9880 break;
9881 default:
9882 assert(0);
9883 break;
9884 }
9885 leave:
9886 PyMem_FREE(tmp);
9887 return res;
9888}
9889
Tim Peters8ce9f162004-08-27 01:49:32 +00009890PyObject *
9891PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009892{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009893 PyObject *res;
9894 PyObject *fseq;
9895 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009896 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009897
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009898 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009899 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009900 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009901 }
9902
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009903 /* NOTE: the following code can't call back into Python code,
9904 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009905 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009906
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009907 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009908 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009909 res = _PyUnicode_JoinArray(separator, items, seqlen);
9910 Py_DECREF(fseq);
9911 return res;
9912}
9913
9914PyObject *
9915_PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen)
9916{
9917 PyObject *res = NULL; /* the result */
9918 PyObject *sep = NULL;
9919 Py_ssize_t seplen;
9920 PyObject *item;
9921 Py_ssize_t sz, i, res_offset;
9922 Py_UCS4 maxchar;
9923 Py_UCS4 item_maxchar;
9924 int use_memcpy;
9925 unsigned char *res_data = NULL, *sep_data = NULL;
9926 PyObject *last_obj;
9927 unsigned int kind = 0;
9928
Tim Peters05eba1f2004-08-27 21:32:02 +00009929 /* If empty sequence, return u"". */
9930 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009931 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009932 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009933
Tim Peters05eba1f2004-08-27 21:32:02 +00009934 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009935 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009936 if (seqlen == 1) {
9937 if (PyUnicode_CheckExact(items[0])) {
9938 res = items[0];
9939 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009940 return res;
9941 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009942 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009943 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009944 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009945 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009946 /* Set up sep and seplen */
9947 if (separator == NULL) {
9948 /* fall back to a blank space separator */
9949 sep = PyUnicode_FromOrdinal(' ');
9950 if (!sep)
9951 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009952 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009953 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009954 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009955 else {
9956 if (!PyUnicode_Check(separator)) {
9957 PyErr_Format(PyExc_TypeError,
9958 "separator: expected str instance,"
9959 " %.80s found",
9960 Py_TYPE(separator)->tp_name);
9961 goto onError;
9962 }
9963 if (PyUnicode_READY(separator))
9964 goto onError;
9965 sep = separator;
9966 seplen = PyUnicode_GET_LENGTH(separator);
9967 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9968 /* inc refcount to keep this code path symmetric with the
9969 above case of a blank separator */
9970 Py_INCREF(sep);
9971 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009972 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009973 }
9974
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009975 /* There are at least two things to join, or else we have a subclass
9976 * of str in the sequence.
9977 * Do a pre-pass to figure out the total amount of space we'll
9978 * need (sz), and see whether all argument are strings.
9979 */
9980 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009981#ifdef Py_DEBUG
9982 use_memcpy = 0;
9983#else
9984 use_memcpy = 1;
9985#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009986 for (i = 0; i < seqlen; i++) {
9987 const Py_ssize_t old_sz = sz;
9988 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009989 if (!PyUnicode_Check(item)) {
9990 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009991 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009992 " %.80s found",
9993 i, Py_TYPE(item)->tp_name);
9994 goto onError;
9995 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009996 if (PyUnicode_READY(item) == -1)
9997 goto onError;
9998 sz += PyUnicode_GET_LENGTH(item);
9999 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010000 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010001 if (i != 0)
10002 sz += seplen;
10003 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
10004 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010005 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010006 goto onError;
10007 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010008 if (use_memcpy && last_obj != NULL) {
10009 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10010 use_memcpy = 0;
10011 }
10012 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010013 }
Tim Petersced69f82003-09-16 20:30:58 +000010014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010016 if (res == NULL)
10017 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010018
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010019 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010020#ifdef Py_DEBUG
10021 use_memcpy = 0;
10022#else
10023 if (use_memcpy) {
10024 res_data = PyUnicode_1BYTE_DATA(res);
10025 kind = PyUnicode_KIND(res);
10026 if (seplen != 0)
10027 sep_data = PyUnicode_1BYTE_DATA(sep);
10028 }
10029#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010030 if (use_memcpy) {
10031 for (i = 0; i < seqlen; ++i) {
10032 Py_ssize_t itemlen;
10033 item = items[i];
10034
10035 /* Copy item, and maybe the separator. */
10036 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010037 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010038 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010039 kind * seplen);
10040 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010041 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010042
10043 itemlen = PyUnicode_GET_LENGTH(item);
10044 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010045 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010046 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010047 kind * itemlen);
10048 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010049 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010050 }
10051 assert(res_data == PyUnicode_1BYTE_DATA(res)
10052 + kind * PyUnicode_GET_LENGTH(res));
10053 }
10054 else {
10055 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10056 Py_ssize_t itemlen;
10057 item = items[i];
10058
10059 /* Copy item, and maybe the separator. */
10060 if (i && seplen != 0) {
10061 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10062 res_offset += seplen;
10063 }
10064
10065 itemlen = PyUnicode_GET_LENGTH(item);
10066 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010067 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010068 res_offset += itemlen;
10069 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010070 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010071 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010072 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010073
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010074 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010075 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010077
Benjamin Peterson29060642009-01-31 22:14:21 +000010078 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010079 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010080 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010081 return NULL;
10082}
10083
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084#define FILL(kind, data, value, start, length) \
10085 do { \
10086 Py_ssize_t i_ = 0; \
10087 assert(kind != PyUnicode_WCHAR_KIND); \
10088 switch ((kind)) { \
10089 case PyUnicode_1BYTE_KIND: { \
10090 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020010091 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 break; \
10093 } \
10094 case PyUnicode_2BYTE_KIND: { \
10095 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10096 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10097 break; \
10098 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010099 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010100 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10101 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10102 break; \
10103 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +020010104 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010105 } \
10106 } while (0)
10107
Victor Stinnerd3f08822012-05-29 12:57:52 +020010108void
10109_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10110 Py_UCS4 fill_char)
10111{
10112 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10113 const void *data = PyUnicode_DATA(unicode);
10114 assert(PyUnicode_IS_READY(unicode));
10115 assert(unicode_modifiable(unicode));
10116 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10117 assert(start >= 0);
10118 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
10119 FILL(kind, data, fill_char, start, length);
10120}
10121
Victor Stinner3fe55312012-01-04 00:33:50 +010010122Py_ssize_t
10123PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10124 Py_UCS4 fill_char)
10125{
10126 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010127
10128 if (!PyUnicode_Check(unicode)) {
10129 PyErr_BadInternalCall();
10130 return -1;
10131 }
10132 if (PyUnicode_READY(unicode) == -1)
10133 return -1;
10134 if (unicode_check_modifiable(unicode))
10135 return -1;
10136
Victor Stinnerd3f08822012-05-29 12:57:52 +020010137 if (start < 0) {
10138 PyErr_SetString(PyExc_IndexError, "string index out of range");
10139 return -1;
10140 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010141 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10142 PyErr_SetString(PyExc_ValueError,
10143 "fill character is bigger than "
10144 "the string maximum character");
10145 return -1;
10146 }
10147
10148 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10149 length = Py_MIN(maxlen, length);
10150 if (length <= 0)
10151 return 0;
10152
Victor Stinnerd3f08822012-05-29 12:57:52 +020010153 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010154 return length;
10155}
10156
Victor Stinner9310abb2011-10-05 00:59:23 +020010157static PyObject *
10158pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010159 Py_ssize_t left,
10160 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010162{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 PyObject *u;
10164 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010165 int kind;
10166 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010167
10168 if (left < 0)
10169 left = 0;
10170 if (right < 0)
10171 right = 0;
10172
Victor Stinnerc4b49542011-12-11 22:44:26 +010010173 if (left == 0 && right == 0)
10174 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10177 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010178 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10179 return NULL;
10180 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010182 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010184 if (!u)
10185 return NULL;
10186
10187 kind = PyUnicode_KIND(u);
10188 data = PyUnicode_DATA(u);
10189 if (left)
10190 FILL(kind, data, fill, 0, left);
10191 if (right)
10192 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010193 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010194 assert(_PyUnicode_CheckConsistency(u, 1));
10195 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010196}
10197
Alexander Belopolsky40018472011-02-26 01:02:56 +000010198PyObject *
10199PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010200{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010201 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010202
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010203 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010204 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010205
Benjamin Petersonead6b532011-12-20 17:23:42 -060010206 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010208 if (PyUnicode_IS_ASCII(string))
10209 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010210 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010211 PyUnicode_GET_LENGTH(string), keepends);
10212 else
10213 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010214 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010215 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 break;
10217 case PyUnicode_2BYTE_KIND:
10218 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010219 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 PyUnicode_GET_LENGTH(string), keepends);
10221 break;
10222 case PyUnicode_4BYTE_KIND:
10223 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010224 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225 PyUnicode_GET_LENGTH(string), keepends);
10226 break;
10227 default:
10228 assert(0);
10229 list = 0;
10230 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010231 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010232}
10233
Alexander Belopolsky40018472011-02-26 01:02:56 +000010234static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010235split(PyObject *self,
10236 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010237 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010238{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010239 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 void *buf1, *buf2;
10241 Py_ssize_t len1, len2;
10242 PyObject* out;
10243
Guido van Rossumd57fd912000-03-10 22:53:23 +000010244 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010245 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247 if (PyUnicode_READY(self) == -1)
10248 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010249
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010251 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010253 if (PyUnicode_IS_ASCII(self))
10254 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010255 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010256 PyUnicode_GET_LENGTH(self), maxcount
10257 );
10258 else
10259 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010260 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010261 PyUnicode_GET_LENGTH(self), maxcount
10262 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 case PyUnicode_2BYTE_KIND:
10264 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010265 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 PyUnicode_GET_LENGTH(self), maxcount
10267 );
10268 case PyUnicode_4BYTE_KIND:
10269 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010270 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 PyUnicode_GET_LENGTH(self), maxcount
10272 );
10273 default:
10274 assert(0);
10275 return NULL;
10276 }
10277
10278 if (PyUnicode_READY(substring) == -1)
10279 return NULL;
10280
10281 kind1 = PyUnicode_KIND(self);
10282 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 len1 = PyUnicode_GET_LENGTH(self);
10284 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010285 if (kind1 < kind2 || len1 < len2) {
10286 out = PyList_New(1);
10287 if (out == NULL)
10288 return NULL;
10289 Py_INCREF(self);
10290 PyList_SET_ITEM(out, 0, self);
10291 return out;
10292 }
10293 buf1 = PyUnicode_DATA(self);
10294 buf2 = PyUnicode_DATA(substring);
10295 if (kind2 != kind1) {
10296 buf2 = _PyUnicode_AsKind(substring, kind1);
10297 if (!buf2)
10298 return NULL;
10299 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010301 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010303 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10304 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010305 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010306 else
10307 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010308 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 break;
10310 case PyUnicode_2BYTE_KIND:
10311 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010312 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 break;
10314 case PyUnicode_4BYTE_KIND:
10315 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010316 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 break;
10318 default:
10319 out = NULL;
10320 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010321 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 PyMem_Free(buf2);
10323 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010324}
10325
Alexander Belopolsky40018472011-02-26 01:02:56 +000010326static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010327rsplit(PyObject *self,
10328 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010329 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010330{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010331 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 void *buf1, *buf2;
10333 Py_ssize_t len1, len2;
10334 PyObject* out;
10335
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010336 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010337 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 if (PyUnicode_READY(self) == -1)
10340 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010341
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010343 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010345 if (PyUnicode_IS_ASCII(self))
10346 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010347 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010348 PyUnicode_GET_LENGTH(self), maxcount
10349 );
10350 else
10351 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010352 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010353 PyUnicode_GET_LENGTH(self), maxcount
10354 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010355 case PyUnicode_2BYTE_KIND:
10356 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010357 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 PyUnicode_GET_LENGTH(self), maxcount
10359 );
10360 case PyUnicode_4BYTE_KIND:
10361 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010362 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 PyUnicode_GET_LENGTH(self), maxcount
10364 );
10365 default:
10366 assert(0);
10367 return NULL;
10368 }
10369
10370 if (PyUnicode_READY(substring) == -1)
10371 return NULL;
10372
10373 kind1 = PyUnicode_KIND(self);
10374 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 len1 = PyUnicode_GET_LENGTH(self);
10376 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010377 if (kind1 < kind2 || len1 < len2) {
10378 out = PyList_New(1);
10379 if (out == NULL)
10380 return NULL;
10381 Py_INCREF(self);
10382 PyList_SET_ITEM(out, 0, self);
10383 return out;
10384 }
10385 buf1 = PyUnicode_DATA(self);
10386 buf2 = PyUnicode_DATA(substring);
10387 if (kind2 != kind1) {
10388 buf2 = _PyUnicode_AsKind(substring, kind1);
10389 if (!buf2)
10390 return NULL;
10391 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010393 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010394 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010395 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10396 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010397 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010398 else
10399 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010400 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 break;
10402 case PyUnicode_2BYTE_KIND:
10403 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010404 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 break;
10406 case PyUnicode_4BYTE_KIND:
10407 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010408 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 break;
10410 default:
10411 out = NULL;
10412 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010413 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 PyMem_Free(buf2);
10415 return out;
10416}
10417
10418static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010419anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10420 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010422 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010424 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10425 return asciilib_find(buf1, len1, buf2, len2, offset);
10426 else
10427 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 case PyUnicode_2BYTE_KIND:
10429 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10430 case PyUnicode_4BYTE_KIND:
10431 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10432 }
10433 assert(0);
10434 return -1;
10435}
10436
10437static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010438anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10439 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010440{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010441 switch (kind) {
10442 case PyUnicode_1BYTE_KIND:
10443 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10444 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10445 else
10446 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10447 case PyUnicode_2BYTE_KIND:
10448 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10449 case PyUnicode_4BYTE_KIND:
10450 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10451 }
10452 assert(0);
10453 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010454}
10455
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010456static void
10457replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10458 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10459{
10460 int kind = PyUnicode_KIND(u);
10461 void *data = PyUnicode_DATA(u);
10462 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10463 if (kind == PyUnicode_1BYTE_KIND) {
10464 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10465 (Py_UCS1 *)data + len,
10466 u1, u2, maxcount);
10467 }
10468 else if (kind == PyUnicode_2BYTE_KIND) {
10469 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10470 (Py_UCS2 *)data + len,
10471 u1, u2, maxcount);
10472 }
10473 else {
10474 assert(kind == PyUnicode_4BYTE_KIND);
10475 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10476 (Py_UCS4 *)data + len,
10477 u1, u2, maxcount);
10478 }
10479}
10480
Alexander Belopolsky40018472011-02-26 01:02:56 +000010481static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482replace(PyObject *self, PyObject *str1,
10483 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010484{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 PyObject *u;
10486 char *sbuf = PyUnicode_DATA(self);
10487 char *buf1 = PyUnicode_DATA(str1);
10488 char *buf2 = PyUnicode_DATA(str2);
10489 int srelease = 0, release1 = 0, release2 = 0;
10490 int skind = PyUnicode_KIND(self);
10491 int kind1 = PyUnicode_KIND(str1);
10492 int kind2 = PyUnicode_KIND(str2);
10493 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10494 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10495 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010496 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010497 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010498
10499 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010500 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010502 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010503
Victor Stinner59de0ee2011-10-07 10:01:28 +020010504 if (str1 == str2)
10505 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506
Victor Stinner49a0a212011-10-12 23:46:10 +020010507 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010508 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10509 if (maxchar < maxchar_str1)
10510 /* substring too wide to be present */
10511 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010512 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10513 /* Replacing str1 with str2 may cause a maxchar reduction in the
10514 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010515 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010516 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010518 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010519 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010521 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010522 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010523 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010524 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010525 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010526
Victor Stinner69ed0f42013-04-09 21:48:24 +020010527 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010528 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010529 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010530 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010531 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010533 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010535
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010536 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10537 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010538 }
10539 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 int rkind = skind;
10541 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010542 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 if (kind1 < rkind) {
10545 /* widen substring */
10546 buf1 = _PyUnicode_AsKind(str1, rkind);
10547 if (!buf1) goto error;
10548 release1 = 1;
10549 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010550 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010551 if (i < 0)
10552 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 if (rkind > kind2) {
10554 /* widen replacement */
10555 buf2 = _PyUnicode_AsKind(str2, rkind);
10556 if (!buf2) goto error;
10557 release2 = 1;
10558 }
10559 else if (rkind < kind2) {
10560 /* widen self and buf1 */
10561 rkind = kind2;
10562 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010563 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564 sbuf = _PyUnicode_AsKind(self, rkind);
10565 if (!sbuf) goto error;
10566 srelease = 1;
10567 buf1 = _PyUnicode_AsKind(str1, rkind);
10568 if (!buf1) goto error;
10569 release1 = 1;
10570 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010571 u = PyUnicode_New(slen, maxchar);
10572 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010574 assert(PyUnicode_KIND(u) == rkind);
10575 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010576
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010577 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010578 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010579 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010581 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010583
10584 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010585 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010586 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010587 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010588 if (i == -1)
10589 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010590 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010592 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010594 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010595 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010596 }
10597 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010599 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 int rkind = skind;
10601 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010602
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010604 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 buf1 = _PyUnicode_AsKind(str1, rkind);
10606 if (!buf1) goto error;
10607 release1 = 1;
10608 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010609 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010610 if (n == 0)
10611 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010613 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 buf2 = _PyUnicode_AsKind(str2, rkind);
10615 if (!buf2) goto error;
10616 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010619 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010620 rkind = kind2;
10621 sbuf = _PyUnicode_AsKind(self, rkind);
10622 if (!sbuf) goto error;
10623 srelease = 1;
10624 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010625 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010626 buf1 = _PyUnicode_AsKind(str1, rkind);
10627 if (!buf1) goto error;
10628 release1 = 1;
10629 }
10630 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10631 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010632 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633 PyErr_SetString(PyExc_OverflowError,
10634 "replace string is too long");
10635 goto error;
10636 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010637 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010638 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010639 _Py_INCREF_UNICODE_EMPTY();
10640 if (!unicode_empty)
10641 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010642 u = unicode_empty;
10643 goto done;
10644 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010645 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 PyErr_SetString(PyExc_OverflowError,
10647 "replace string is too long");
10648 goto error;
10649 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010650 u = PyUnicode_New(new_size, maxchar);
10651 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010653 assert(PyUnicode_KIND(u) == rkind);
10654 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 ires = i = 0;
10656 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010657 while (n-- > 0) {
10658 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010659 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010660 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010661 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010662 if (j == -1)
10663 break;
10664 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010665 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010666 memcpy(res + rkind * ires,
10667 sbuf + rkind * i,
10668 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010670 }
10671 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010673 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010674 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010675 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010677 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010679 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010681 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010682 memcpy(res + rkind * ires,
10683 sbuf + rkind * i,
10684 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010685 }
10686 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010687 /* interleave */
10688 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010689 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010690 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010691 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010692 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010693 if (--n <= 0)
10694 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010695 memcpy(res + rkind * ires,
10696 sbuf + rkind * i,
10697 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 ires++;
10699 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010700 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010701 memcpy(res + rkind * ires,
10702 sbuf + rkind * i,
10703 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010704 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010705 }
10706
10707 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010708 unicode_adjust_maxchar(&u);
10709 if (u == NULL)
10710 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010711 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010712
10713 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010714 if (srelease)
10715 PyMem_FREE(sbuf);
10716 if (release1)
10717 PyMem_FREE(buf1);
10718 if (release2)
10719 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010720 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010721 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010722
Benjamin Peterson29060642009-01-31 22:14:21 +000010723 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010724 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010725 if (srelease)
10726 PyMem_FREE(sbuf);
10727 if (release1)
10728 PyMem_FREE(buf1);
10729 if (release2)
10730 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010731 return unicode_result_unchanged(self);
10732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010733 error:
10734 if (srelease && sbuf)
10735 PyMem_FREE(sbuf);
10736 if (release1 && buf1)
10737 PyMem_FREE(buf1);
10738 if (release2 && buf2)
10739 PyMem_FREE(buf2);
10740 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010741}
10742
10743/* --- Unicode Object Methods --------------------------------------------- */
10744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010745PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010746 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010747\n\
10748Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010749characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750
10751static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010752unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010753{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010754 if (PyUnicode_READY(self) == -1)
10755 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010756 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010757}
10758
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010759PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010760 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010761\n\
10762Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010763have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764
10765static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010766unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010768 if (PyUnicode_READY(self) == -1)
10769 return NULL;
10770 if (PyUnicode_GET_LENGTH(self) == 0)
10771 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010772 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773}
10774
Benjamin Petersond5890c82012-01-14 13:23:30 -050010775PyDoc_STRVAR(casefold__doc__,
10776 "S.casefold() -> str\n\
10777\n\
10778Return a version of S suitable for caseless comparisons.");
10779
10780static PyObject *
10781unicode_casefold(PyObject *self)
10782{
10783 if (PyUnicode_READY(self) == -1)
10784 return NULL;
10785 if (PyUnicode_IS_ASCII(self))
10786 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010787 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010788}
10789
10790
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010791/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010792
10793static int
10794convert_uc(PyObject *obj, void *addr)
10795{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010796 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010797
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010798 if (!PyUnicode_Check(obj)) {
10799 PyErr_Format(PyExc_TypeError,
10800 "The fill character must be a unicode character, "
10801 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010802 return 0;
10803 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010804 if (PyUnicode_READY(obj) < 0)
10805 return 0;
10806 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010807 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010808 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010809 return 0;
10810 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010811 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010812 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010813}
10814
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010815PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010816 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010817\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010818Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010819done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010820
10821static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010822unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010823{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010824 Py_ssize_t marg, left;
10825 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010826 Py_UCS4 fillchar = ' ';
10827
Victor Stinnere9a29352011-10-01 02:14:59 +020010828 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010829 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830
Benjamin Petersonbac79492012-01-14 13:34:47 -050010831 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010832 return NULL;
10833
Victor Stinnerc4b49542011-12-11 22:44:26 +010010834 if (PyUnicode_GET_LENGTH(self) >= width)
10835 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010836
Victor Stinnerc4b49542011-12-11 22:44:26 +010010837 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838 left = marg / 2 + (marg & width & 1);
10839
Victor Stinner9310abb2011-10-05 00:59:23 +020010840 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010841}
10842
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010843/* This function assumes that str1 and str2 are readied by the caller. */
10844
Marc-André Lemburge5034372000-08-08 08:04:29 +000010845static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010846unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010847{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010848#define COMPARE(TYPE1, TYPE2) \
10849 do { \
10850 TYPE1* p1 = (TYPE1 *)data1; \
10851 TYPE2* p2 = (TYPE2 *)data2; \
10852 TYPE1* end = p1 + len; \
10853 Py_UCS4 c1, c2; \
10854 for (; p1 != end; p1++, p2++) { \
10855 c1 = *p1; \
10856 c2 = *p2; \
10857 if (c1 != c2) \
10858 return (c1 < c2) ? -1 : 1; \
10859 } \
10860 } \
10861 while (0)
10862
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010863 int kind1, kind2;
10864 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010865 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010866
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010867 kind1 = PyUnicode_KIND(str1);
10868 kind2 = PyUnicode_KIND(str2);
10869 data1 = PyUnicode_DATA(str1);
10870 data2 = PyUnicode_DATA(str2);
10871 len1 = PyUnicode_GET_LENGTH(str1);
10872 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010873 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010874
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010875 switch(kind1) {
10876 case PyUnicode_1BYTE_KIND:
10877 {
10878 switch(kind2) {
10879 case PyUnicode_1BYTE_KIND:
10880 {
10881 int cmp = memcmp(data1, data2, len);
10882 /* normalize result of memcmp() into the range [-1; 1] */
10883 if (cmp < 0)
10884 return -1;
10885 if (cmp > 0)
10886 return 1;
10887 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010888 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010889 case PyUnicode_2BYTE_KIND:
10890 COMPARE(Py_UCS1, Py_UCS2);
10891 break;
10892 case PyUnicode_4BYTE_KIND:
10893 COMPARE(Py_UCS1, Py_UCS4);
10894 break;
10895 default:
10896 assert(0);
10897 }
10898 break;
10899 }
10900 case PyUnicode_2BYTE_KIND:
10901 {
10902 switch(kind2) {
10903 case PyUnicode_1BYTE_KIND:
10904 COMPARE(Py_UCS2, Py_UCS1);
10905 break;
10906 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010907 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010908 COMPARE(Py_UCS2, Py_UCS2);
10909 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010910 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010911 case PyUnicode_4BYTE_KIND:
10912 COMPARE(Py_UCS2, Py_UCS4);
10913 break;
10914 default:
10915 assert(0);
10916 }
10917 break;
10918 }
10919 case PyUnicode_4BYTE_KIND:
10920 {
10921 switch(kind2) {
10922 case PyUnicode_1BYTE_KIND:
10923 COMPARE(Py_UCS4, Py_UCS1);
10924 break;
10925 case PyUnicode_2BYTE_KIND:
10926 COMPARE(Py_UCS4, Py_UCS2);
10927 break;
10928 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010929 {
10930#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10931 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10932 /* normalize result of wmemcmp() into the range [-1; 1] */
10933 if (cmp < 0)
10934 return -1;
10935 if (cmp > 0)
10936 return 1;
10937#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010938 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010939#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010940 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010941 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010942 default:
10943 assert(0);
10944 }
10945 break;
10946 }
10947 default:
10948 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010949 }
10950
Victor Stinner770e19e2012-10-04 22:59:45 +020010951 if (len1 == len2)
10952 return 0;
10953 if (len1 < len2)
10954 return -1;
10955 else
10956 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010957
10958#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010959}
10960
Benjamin Peterson621b4302016-09-09 13:54:34 -070010961static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010962unicode_compare_eq(PyObject *str1, PyObject *str2)
10963{
10964 int kind;
10965 void *data1, *data2;
10966 Py_ssize_t len;
10967 int cmp;
10968
Victor Stinnere5567ad2012-10-23 02:48:49 +020010969 len = PyUnicode_GET_LENGTH(str1);
10970 if (PyUnicode_GET_LENGTH(str2) != len)
10971 return 0;
10972 kind = PyUnicode_KIND(str1);
10973 if (PyUnicode_KIND(str2) != kind)
10974 return 0;
10975 data1 = PyUnicode_DATA(str1);
10976 data2 = PyUnicode_DATA(str2);
10977
10978 cmp = memcmp(data1, data2, len * kind);
10979 return (cmp == 0);
10980}
10981
10982
Alexander Belopolsky40018472011-02-26 01:02:56 +000010983int
10984PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010986 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10987 if (PyUnicode_READY(left) == -1 ||
10988 PyUnicode_READY(right) == -1)
10989 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010990
10991 /* a string is equal to itself */
10992 if (left == right)
10993 return 0;
10994
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010995 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010997 PyErr_Format(PyExc_TypeError,
10998 "Can't compare %.100s and %.100s",
10999 left->ob_type->tp_name,
11000 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011001 return -1;
11002}
11003
Martin v. Löwis5b222132007-06-10 09:51:05 +000011004int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010011005_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
11006{
11007 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
11008 if (right_str == NULL)
11009 return -1;
11010 return PyUnicode_Compare(left, right_str);
11011}
11012
11013int
Martin v. Löwis5b222132007-06-10 09:51:05 +000011014PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11015{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016 Py_ssize_t i;
11017 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011018 Py_UCS4 chr;
11019
Victor Stinner910337b2011-10-03 03:20:16 +020011020 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011021 if (PyUnicode_READY(uni) == -1)
11022 return -1;
11023 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011024 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011025 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011026 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011027 size_t len, len2 = strlen(str);
11028 int cmp;
11029
11030 len = Py_MIN(len1, len2);
11031 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011032 if (cmp != 0) {
11033 if (cmp < 0)
11034 return -1;
11035 else
11036 return 1;
11037 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011038 if (len1 > len2)
11039 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011040 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011041 return -1; /* str is longer */
11042 return 0;
11043 }
11044 else {
11045 void *data = PyUnicode_DATA(uni);
11046 /* Compare Unicode string and source character set string */
11047 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011048 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011049 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11050 /* This check keeps Python strings that end in '\0' from comparing equal
11051 to C strings identical up to that point. */
11052 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11053 return 1; /* uni is longer */
11054 if (str[i])
11055 return -1; /* str is longer */
11056 return 0;
11057 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011058}
11059
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011060
Benjamin Peterson29060642009-01-31 22:14:21 +000011061#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000011062 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011063
Alexander Belopolsky40018472011-02-26 01:02:56 +000011064PyObject *
11065PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011066{
11067 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011068 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011069
Victor Stinnere5567ad2012-10-23 02:48:49 +020011070 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11071 Py_RETURN_NOTIMPLEMENTED;
11072
11073 if (PyUnicode_READY(left) == -1 ||
11074 PyUnicode_READY(right) == -1)
11075 return NULL;
11076
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011077 if (left == right) {
11078 switch (op) {
11079 case Py_EQ:
11080 case Py_LE:
11081 case Py_GE:
11082 /* a string is equal to itself */
11083 v = Py_True;
11084 break;
11085 case Py_NE:
11086 case Py_LT:
11087 case Py_GT:
11088 v = Py_False;
11089 break;
11090 default:
11091 PyErr_BadArgument();
11092 return NULL;
11093 }
11094 }
11095 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011096 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011097 result ^= (op == Py_NE);
11098 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011099 }
11100 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011101 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011102
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011103 /* Convert the return value to a Boolean */
11104 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011105 case Py_LE:
11106 v = TEST_COND(result <= 0);
11107 break;
11108 case Py_GE:
11109 v = TEST_COND(result >= 0);
11110 break;
11111 case Py_LT:
11112 v = TEST_COND(result == -1);
11113 break;
11114 case Py_GT:
11115 v = TEST_COND(result == 1);
11116 break;
11117 default:
11118 PyErr_BadArgument();
11119 return NULL;
11120 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011121 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020011122 Py_INCREF(v);
11123 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011124}
11125
Alexander Belopolsky40018472011-02-26 01:02:56 +000011126int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011127_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11128{
11129 return unicode_eq(aa, bb);
11130}
11131
11132int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011133PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011134{
Victor Stinner77282cb2013-04-14 19:22:47 +020011135 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136 void *buf1, *buf2;
11137 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011138 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011139
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011140 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011141 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011142 "'in <string>' requires string as left operand, not %.100s",
11143 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011144 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011145 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011146 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011147 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011148 if (ensure_unicode(str) < 0)
11149 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011150
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011152 kind2 = PyUnicode_KIND(substr);
11153 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011154 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011155 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011156 len2 = PyUnicode_GET_LENGTH(substr);
11157 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011158 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011159 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011160 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011161 if (len2 == 1) {
11162 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11163 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011164 return result;
11165 }
11166 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011167 buf2 = _PyUnicode_AsKind(substr, kind1);
11168 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011169 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011170 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171
Victor Stinner77282cb2013-04-14 19:22:47 +020011172 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011173 case PyUnicode_1BYTE_KIND:
11174 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11175 break;
11176 case PyUnicode_2BYTE_KIND:
11177 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11178 break;
11179 case PyUnicode_4BYTE_KIND:
11180 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11181 break;
11182 default:
11183 result = -1;
11184 assert(0);
11185 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011186
Victor Stinner77282cb2013-04-14 19:22:47 +020011187 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011188 PyMem_Free(buf2);
11189
Guido van Rossum403d68b2000-03-13 15:55:09 +000011190 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011191}
11192
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193/* Concat to string or Unicode object giving a new Unicode object. */
11194
Alexander Belopolsky40018472011-02-26 01:02:56 +000011195PyObject *
11196PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011198 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011199 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011200 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011202 if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0)
11203 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204
11205 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011206 if (left == unicode_empty)
11207 return PyUnicode_FromObject(right);
11208 if (right == unicode_empty)
11209 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011211 left_len = PyUnicode_GET_LENGTH(left);
11212 right_len = PyUnicode_GET_LENGTH(right);
11213 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011214 PyErr_SetString(PyExc_OverflowError,
11215 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011216 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011217 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011218 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011219
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011220 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11221 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011222 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011223
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011225 result = PyUnicode_New(new_len, maxchar);
11226 if (result == NULL)
11227 return NULL;
11228 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11229 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11230 assert(_PyUnicode_CheckConsistency(result, 1));
11231 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232}
11233
Walter Dörwald1ab83302007-05-18 17:15:44 +000011234void
Victor Stinner23e56682011-10-03 03:54:37 +020011235PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011236{
Victor Stinner23e56682011-10-03 03:54:37 +020011237 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011238 Py_UCS4 maxchar, maxchar2;
11239 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011240
11241 if (p_left == NULL) {
11242 if (!PyErr_Occurred())
11243 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011244 return;
11245 }
Victor Stinner23e56682011-10-03 03:54:37 +020011246 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011247 if (right == NULL || left == NULL
11248 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011249 if (!PyErr_Occurred())
11250 PyErr_BadInternalCall();
11251 goto error;
11252 }
11253
Benjamin Petersonbac79492012-01-14 13:34:47 -050011254 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011255 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011256 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011257 goto error;
11258
Victor Stinner488fa492011-12-12 00:01:39 +010011259 /* Shortcuts */
11260 if (left == unicode_empty) {
11261 Py_DECREF(left);
11262 Py_INCREF(right);
11263 *p_left = right;
11264 return;
11265 }
11266 if (right == unicode_empty)
11267 return;
11268
11269 left_len = PyUnicode_GET_LENGTH(left);
11270 right_len = PyUnicode_GET_LENGTH(right);
11271 if (left_len > PY_SSIZE_T_MAX - right_len) {
11272 PyErr_SetString(PyExc_OverflowError,
11273 "strings are too large to concat");
11274 goto error;
11275 }
11276 new_len = left_len + right_len;
11277
11278 if (unicode_modifiable(left)
11279 && PyUnicode_CheckExact(right)
11280 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011281 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11282 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011283 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011284 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011285 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11286 {
11287 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011288 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011289 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011290
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011291 /* copy 'right' into the newly allocated area of 'left' */
11292 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011293 }
Victor Stinner488fa492011-12-12 00:01:39 +010011294 else {
11295 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11296 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011297 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011298
Victor Stinner488fa492011-12-12 00:01:39 +010011299 /* Concat the two Unicode strings */
11300 res = PyUnicode_New(new_len, maxchar);
11301 if (res == NULL)
11302 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011303 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11304 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011305 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011306 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011307 }
11308 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011309 return;
11310
11311error:
Victor Stinner488fa492011-12-12 00:01:39 +010011312 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011313}
11314
11315void
11316PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11317{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011318 PyUnicode_Append(pleft, right);
11319 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011320}
11321
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011322/*
11323Wraps stringlib_parse_args_finds() and additionally ensures that the
11324first argument is a unicode object.
11325*/
11326
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011327static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011328parse_args_finds_unicode(const char * function_name, PyObject *args,
11329 PyObject **substring,
11330 Py_ssize_t *start, Py_ssize_t *end)
11331{
11332 if(stringlib_parse_args_finds(function_name, args, substring,
11333 start, end)) {
11334 if (ensure_unicode(*substring) < 0)
11335 return 0;
11336 return 1;
11337 }
11338 return 0;
11339}
11340
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011341PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011342 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011344Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011345string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011346interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347
11348static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011349unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011351 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011352 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011353 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011355 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 void *buf1, *buf2;
11357 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011359 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011360 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011361
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011362 kind1 = PyUnicode_KIND(self);
11363 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011364 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011365 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011366
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011367 len1 = PyUnicode_GET_LENGTH(self);
11368 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011369 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011370 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011371 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011372
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011373 buf1 = PyUnicode_DATA(self);
11374 buf2 = PyUnicode_DATA(substring);
11375 if (kind2 != kind1) {
11376 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011377 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011378 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011379 }
11380 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011381 case PyUnicode_1BYTE_KIND:
11382 iresult = ucs1lib_count(
11383 ((Py_UCS1*)buf1) + start, end - start,
11384 buf2, len2, PY_SSIZE_T_MAX
11385 );
11386 break;
11387 case PyUnicode_2BYTE_KIND:
11388 iresult = ucs2lib_count(
11389 ((Py_UCS2*)buf1) + start, end - start,
11390 buf2, len2, PY_SSIZE_T_MAX
11391 );
11392 break;
11393 case PyUnicode_4BYTE_KIND:
11394 iresult = ucs4lib_count(
11395 ((Py_UCS4*)buf1) + start, end - start,
11396 buf2, len2, PY_SSIZE_T_MAX
11397 );
11398 break;
11399 default:
11400 assert(0); iresult = 0;
11401 }
11402
11403 result = PyLong_FromSsize_t(iresult);
11404
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011405 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011406 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408 return result;
11409}
11410
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011411PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011412 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011414Encode S using the codec registered for encoding. Default encoding\n\
11415is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011416handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011417a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11418'xmlcharrefreplace' as well as any other name registered with\n\
11419codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
11421static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011422unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011424 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425 char *encoding = NULL;
11426 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011427
Benjamin Peterson308d6372009-09-18 21:42:35 +000011428 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11429 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011431 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011432}
11433
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011434PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011435 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436\n\
11437Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011438If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439
11440static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011441unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011443 Py_ssize_t i, j, line_pos, src_len, incr;
11444 Py_UCS4 ch;
11445 PyObject *u;
11446 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011447 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011448 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011449 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011450 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011451
Ezio Melotti745d54d2013-11-16 19:10:57 +020011452 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11453 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011454 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455
Antoine Pitrou22425222011-10-04 19:10:51 +020011456 if (PyUnicode_READY(self) == -1)
11457 return NULL;
11458
Thomas Wouters7e474022000-07-16 12:04:32 +000011459 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011460 src_len = PyUnicode_GET_LENGTH(self);
11461 i = j = line_pos = 0;
11462 kind = PyUnicode_KIND(self);
11463 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011464 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011465 for (; i < src_len; i++) {
11466 ch = PyUnicode_READ(kind, src_data, i);
11467 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011468 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011470 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011471 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011472 goto overflow;
11473 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011474 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011475 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011476 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011479 goto overflow;
11480 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011482 if (ch == '\n' || ch == '\r')
11483 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011485 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011486 if (!found)
11487 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011488
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011490 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 if (!u)
11492 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011493 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494
Antoine Pitroue71d5742011-10-04 15:55:09 +020011495 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496
Antoine Pitroue71d5742011-10-04 15:55:09 +020011497 for (; i < src_len; i++) {
11498 ch = PyUnicode_READ(kind, src_data, i);
11499 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011500 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011501 incr = tabsize - (line_pos % tabsize);
11502 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011503 FILL(kind, dest_data, ' ', j, incr);
11504 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011505 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011506 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011507 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011508 line_pos++;
11509 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011510 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011511 if (ch == '\n' || ch == '\r')
11512 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011514 }
11515 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011516 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011517
Antoine Pitroue71d5742011-10-04 15:55:09 +020011518 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011519 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11520 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521}
11522
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011523PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011524 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525\n\
11526Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011527such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528arguments start and end are interpreted as in slice notation.\n\
11529\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011530Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531
11532static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011535 /* initialize variables to prevent gcc warning */
11536 PyObject *substring = NULL;
11537 Py_ssize_t start = 0;
11538 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011539 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011541 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011542 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011544 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011545 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011546
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011547 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 if (result == -2)
11550 return NULL;
11551
Christian Heimes217cfd12007-12-02 14:31:20 +000011552 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553}
11554
11555static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011556unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011558 void *data;
11559 enum PyUnicode_Kind kind;
11560 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011561
11562 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11563 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011564 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011565 }
11566 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11567 PyErr_SetString(PyExc_IndexError, "string index out of range");
11568 return NULL;
11569 }
11570 kind = PyUnicode_KIND(self);
11571 data = PyUnicode_DATA(self);
11572 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011573 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574}
11575
Guido van Rossumc2504932007-09-18 19:42:40 +000011576/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011577 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011578static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011579unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580{
Guido van Rossumc2504932007-09-18 19:42:40 +000011581 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011582 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011583
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011584#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011585 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011586#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011587 if (_PyUnicode_HASH(self) != -1)
11588 return _PyUnicode_HASH(self);
11589 if (PyUnicode_READY(self) == -1)
11590 return -1;
11591 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011592 /*
11593 We make the hash of the empty string be 0, rather than using
11594 (prefix ^ suffix), since this slightly obfuscates the hash secret
11595 */
11596 if (len == 0) {
11597 _PyUnicode_HASH(self) = 0;
11598 return 0;
11599 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011600 x = _Py_HashBytes(PyUnicode_DATA(self),
11601 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011602 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011603 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604}
11605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011606PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011609Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
11611static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011614 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011615 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011616 PyObject *substring = NULL;
11617 Py_ssize_t start = 0;
11618 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011620 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011623 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011624 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011625
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011626 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011627
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628 if (result == -2)
11629 return NULL;
11630
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631 if (result < 0) {
11632 PyErr_SetString(PyExc_ValueError, "substring not found");
11633 return NULL;
11634 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011635
Christian Heimes217cfd12007-12-02 14:31:20 +000011636 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011637}
11638
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011639PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011640 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011642Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011643at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644
11645static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011646unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 Py_ssize_t i, length;
11649 int kind;
11650 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651 int cased;
11652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 if (PyUnicode_READY(self) == -1)
11654 return NULL;
11655 length = PyUnicode_GET_LENGTH(self);
11656 kind = PyUnicode_KIND(self);
11657 data = PyUnicode_DATA(self);
11658
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011660 if (length == 1)
11661 return PyBool_FromLong(
11662 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011663
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011664 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011665 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011666 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011667
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669 for (i = 0; i < length; i++) {
11670 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011671
Benjamin Peterson29060642009-01-31 22:14:21 +000011672 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11673 return PyBool_FromLong(0);
11674 else if (!cased && Py_UNICODE_ISLOWER(ch))
11675 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011677 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678}
11679
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011680PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011681 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011682\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011683Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011684at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011685
11686static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011687unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689 Py_ssize_t i, length;
11690 int kind;
11691 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692 int cased;
11693
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694 if (PyUnicode_READY(self) == -1)
11695 return NULL;
11696 length = PyUnicode_GET_LENGTH(self);
11697 kind = PyUnicode_KIND(self);
11698 data = PyUnicode_DATA(self);
11699
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011701 if (length == 1)
11702 return PyBool_FromLong(
11703 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011705 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011707 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011708
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 for (i = 0; i < length; i++) {
11711 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011712
Benjamin Peterson29060642009-01-31 22:14:21 +000011713 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11714 return PyBool_FromLong(0);
11715 else if (!cased && Py_UNICODE_ISUPPER(ch))
11716 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011718 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719}
11720
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011721PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011722 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011724Return True if S is a titlecased string and there is at least one\n\
11725character in S, i.e. upper- and titlecase characters may only\n\
11726follow uncased characters and lowercase characters only cased ones.\n\
11727Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728
11729static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011730unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011732 Py_ssize_t i, length;
11733 int kind;
11734 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735 int cased, previous_is_cased;
11736
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011737 if (PyUnicode_READY(self) == -1)
11738 return NULL;
11739 length = PyUnicode_GET_LENGTH(self);
11740 kind = PyUnicode_KIND(self);
11741 data = PyUnicode_DATA(self);
11742
Guido van Rossumd57fd912000-03-10 22:53:23 +000011743 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011744 if (length == 1) {
11745 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11746 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11747 (Py_UNICODE_ISUPPER(ch) != 0));
11748 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011750 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011752 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011753
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754 cased = 0;
11755 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 for (i = 0; i < length; i++) {
11757 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011758
Benjamin Peterson29060642009-01-31 22:14:21 +000011759 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11760 if (previous_is_cased)
11761 return PyBool_FromLong(0);
11762 previous_is_cased = 1;
11763 cased = 1;
11764 }
11765 else if (Py_UNICODE_ISLOWER(ch)) {
11766 if (!previous_is_cased)
11767 return PyBool_FromLong(0);
11768 previous_is_cased = 1;
11769 cased = 1;
11770 }
11771 else
11772 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011774 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775}
11776
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011777PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011778 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011780Return True if all characters in S are whitespace\n\
11781and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782
11783static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011784unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011786 Py_ssize_t i, length;
11787 int kind;
11788 void *data;
11789
11790 if (PyUnicode_READY(self) == -1)
11791 return NULL;
11792 length = PyUnicode_GET_LENGTH(self);
11793 kind = PyUnicode_KIND(self);
11794 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011797 if (length == 1)
11798 return PyBool_FromLong(
11799 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011801 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011802 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011803 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805 for (i = 0; i < length; i++) {
11806 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011807 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011808 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011810 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011811}
11812
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011813PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011814 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011815\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011816Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011817and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011818
11819static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011820unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011821{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011822 Py_ssize_t i, length;
11823 int kind;
11824 void *data;
11825
11826 if (PyUnicode_READY(self) == -1)
11827 return NULL;
11828 length = PyUnicode_GET_LENGTH(self);
11829 kind = PyUnicode_KIND(self);
11830 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011831
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011832 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011833 if (length == 1)
11834 return PyBool_FromLong(
11835 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011836
11837 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011838 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011839 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011841 for (i = 0; i < length; i++) {
11842 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011843 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011844 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011845 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011846}
11847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011848PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011849 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011850\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011851Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011852and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011853
11854static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011855unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011856{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 int kind;
11858 void *data;
11859 Py_ssize_t len, i;
11860
11861 if (PyUnicode_READY(self) == -1)
11862 return NULL;
11863
11864 kind = PyUnicode_KIND(self);
11865 data = PyUnicode_DATA(self);
11866 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011867
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011868 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011869 if (len == 1) {
11870 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11871 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11872 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011873
11874 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011876 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011877
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011878 for (i = 0; i < len; i++) {
11879 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011880 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011881 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011882 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011883 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011884}
11885
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011886PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011887 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011889Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011890False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891
11892static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011893unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011895 Py_ssize_t i, length;
11896 int kind;
11897 void *data;
11898
11899 if (PyUnicode_READY(self) == -1)
11900 return NULL;
11901 length = PyUnicode_GET_LENGTH(self);
11902 kind = PyUnicode_KIND(self);
11903 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906 if (length == 1)
11907 return PyBool_FromLong(
11908 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011910 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011911 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011912 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011913
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011914 for (i = 0; i < length; i++) {
11915 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011916 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011918 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919}
11920
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011921PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011922 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011924Return True if all characters in S are digits\n\
11925and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011926
11927static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011928unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011929{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011930 Py_ssize_t i, length;
11931 int kind;
11932 void *data;
11933
11934 if (PyUnicode_READY(self) == -1)
11935 return NULL;
11936 length = PyUnicode_GET_LENGTH(self);
11937 kind = PyUnicode_KIND(self);
11938 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011941 if (length == 1) {
11942 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11943 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11944 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011946 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011948 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011950 for (i = 0; i < length; i++) {
11951 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011952 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011954 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955}
11956
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011957PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011958 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011960Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011961False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011962
11963static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011964unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011965{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011966 Py_ssize_t i, length;
11967 int kind;
11968 void *data;
11969
11970 if (PyUnicode_READY(self) == -1)
11971 return NULL;
11972 length = PyUnicode_GET_LENGTH(self);
11973 kind = PyUnicode_KIND(self);
11974 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011975
Guido van Rossumd57fd912000-03-10 22:53:23 +000011976 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011977 if (length == 1)
11978 return PyBool_FromLong(
11979 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011980
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011981 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011982 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011983 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011984
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985 for (i = 0; i < length; i++) {
11986 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011987 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011988 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011989 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011990}
11991
Martin v. Löwis47383402007-08-15 07:32:56 +000011992int
11993PyUnicode_IsIdentifier(PyObject *self)
11994{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011995 int kind;
11996 void *data;
11997 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011998 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012000 if (PyUnicode_READY(self) == -1) {
12001 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012003 }
12004
12005 /* Special case for empty strings */
12006 if (PyUnicode_GET_LENGTH(self) == 0)
12007 return 0;
12008 kind = PyUnicode_KIND(self);
12009 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012010
12011 /* PEP 3131 says that the first character must be in
12012 XID_Start and subsequent characters in XID_Continue,
12013 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012014 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012015 letters, digits, underscore). However, given the current
12016 definition of XID_Start and XID_Continue, it is sufficient
12017 to check just for these, except that _ must be allowed
12018 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012020 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012021 return 0;
12022
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012023 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012025 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012026 return 1;
12027}
12028
12029PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012030 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000012031\n\
12032Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070012033to the language definition.\n\
12034\n\
12035Use keyword.iskeyword() to test for reserved identifiers\n\
12036such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000012037
12038static PyObject*
12039unicode_isidentifier(PyObject *self)
12040{
12041 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12042}
12043
Georg Brandl559e5d72008-06-11 18:37:52 +000012044PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012045 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000012046\n\
12047Return True if all characters in S are considered\n\
12048printable in repr() or S is empty, False otherwise.");
12049
12050static PyObject*
12051unicode_isprintable(PyObject *self)
12052{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012053 Py_ssize_t i, length;
12054 int kind;
12055 void *data;
12056
12057 if (PyUnicode_READY(self) == -1)
12058 return NULL;
12059 length = PyUnicode_GET_LENGTH(self);
12060 kind = PyUnicode_KIND(self);
12061 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012062
12063 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012064 if (length == 1)
12065 return PyBool_FromLong(
12066 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 for (i = 0; i < length; i++) {
12069 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012070 Py_RETURN_FALSE;
12071 }
12072 }
12073 Py_RETURN_TRUE;
12074}
12075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012076PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000012077 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012078\n\
12079Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000012080iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012081
12082static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012083unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012084{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012085 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012086}
12087
Martin v. Löwis18e16552006-02-15 17:27:45 +000012088static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012089unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012091 if (PyUnicode_READY(self) == -1)
12092 return -1;
12093 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012094}
12095
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012096PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012097 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012099Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012100done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101
12102static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012103unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012105 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012106 Py_UCS4 fillchar = ' ';
12107
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012108 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109 return NULL;
12110
Benjamin Petersonbac79492012-01-14 13:34:47 -050012111 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012112 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113
Victor Stinnerc4b49542011-12-11 22:44:26 +010012114 if (PyUnicode_GET_LENGTH(self) >= width)
12115 return unicode_result_unchanged(self);
12116
12117 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012118}
12119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012120PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012121 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012122\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012123Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124
12125static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012126unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012128 if (PyUnicode_READY(self) == -1)
12129 return NULL;
12130 if (PyUnicode_IS_ASCII(self))
12131 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012132 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133}
12134
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012135#define LEFTSTRIP 0
12136#define RIGHTSTRIP 1
12137#define BOTHSTRIP 2
12138
12139/* Arrays indexed by above */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012140static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012141
12142#define STRIPNAME(i) (stripformat[i]+3)
12143
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012144/* externally visible for str.strip(unicode) */
12145PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012146_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012147{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012148 void *data;
12149 int kind;
12150 Py_ssize_t i, j, len;
12151 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012152 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012153
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012154 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12155 return NULL;
12156
12157 kind = PyUnicode_KIND(self);
12158 data = PyUnicode_DATA(self);
12159 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012160 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012161 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12162 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012163 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012164
Benjamin Peterson14339b62009-01-31 16:36:08 +000012165 i = 0;
12166 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012167 while (i < len) {
12168 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12169 if (!BLOOM(sepmask, ch))
12170 break;
12171 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12172 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012173 i++;
12174 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012175 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012176
Benjamin Peterson14339b62009-01-31 16:36:08 +000012177 j = len;
12178 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012179 j--;
12180 while (j >= i) {
12181 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12182 if (!BLOOM(sepmask, ch))
12183 break;
12184 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12185 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012186 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012187 }
12188
Benjamin Peterson29060642009-01-31 22:14:21 +000012189 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012190 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012191
Victor Stinner7931d9a2011-11-04 00:22:48 +010012192 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012193}
12194
12195PyObject*
12196PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12197{
12198 unsigned char *data;
12199 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012200 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012201
Victor Stinnerde636f32011-10-01 03:55:54 +020012202 if (PyUnicode_READY(self) == -1)
12203 return NULL;
12204
Victor Stinner684d5fd2012-05-03 02:32:34 +020012205 length = PyUnicode_GET_LENGTH(self);
12206 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012207
Victor Stinner684d5fd2012-05-03 02:32:34 +020012208 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012209 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012210
Victor Stinnerde636f32011-10-01 03:55:54 +020012211 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012212 PyErr_SetString(PyExc_IndexError, "string index out of range");
12213 return NULL;
12214 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012215 if (start >= length || end < start)
12216 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012217
Victor Stinner684d5fd2012-05-03 02:32:34 +020012218 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012219 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012220 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012221 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012222 }
12223 else {
12224 kind = PyUnicode_KIND(self);
12225 data = PyUnicode_1BYTE_DATA(self);
12226 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012227 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012228 length);
12229 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231
12232static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012233do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235 Py_ssize_t len, i, j;
12236
12237 if (PyUnicode_READY(self) == -1)
12238 return NULL;
12239
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012240 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012241
Victor Stinnercc7af722013-04-09 22:39:24 +020012242 if (PyUnicode_IS_ASCII(self)) {
12243 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12244
12245 i = 0;
12246 if (striptype != RIGHTSTRIP) {
12247 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012248 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012249 if (!_Py_ascii_whitespace[ch])
12250 break;
12251 i++;
12252 }
12253 }
12254
12255 j = len;
12256 if (striptype != LEFTSTRIP) {
12257 j--;
12258 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012259 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012260 if (!_Py_ascii_whitespace[ch])
12261 break;
12262 j--;
12263 }
12264 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012265 }
12266 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012267 else {
12268 int kind = PyUnicode_KIND(self);
12269 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012270
Victor Stinnercc7af722013-04-09 22:39:24 +020012271 i = 0;
12272 if (striptype != RIGHTSTRIP) {
12273 while (i < len) {
12274 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12275 if (!Py_UNICODE_ISSPACE(ch))
12276 break;
12277 i++;
12278 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012279 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012280
12281 j = len;
12282 if (striptype != LEFTSTRIP) {
12283 j--;
12284 while (j >= i) {
12285 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12286 if (!Py_UNICODE_ISSPACE(ch))
12287 break;
12288 j--;
12289 }
12290 j++;
12291 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012292 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012293
Victor Stinner7931d9a2011-11-04 00:22:48 +010012294 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295}
12296
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012297
12298static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012299do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012300{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012301 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012302
Serhiy Storchakac6792272013-10-19 21:03:34 +030012303 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012304 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012305
Benjamin Peterson14339b62009-01-31 16:36:08 +000012306 if (sep != NULL && sep != Py_None) {
12307 if (PyUnicode_Check(sep))
12308 return _PyUnicode_XStrip(self, striptype, sep);
12309 else {
12310 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012311 "%s arg must be None or str",
12312 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012313 return NULL;
12314 }
12315 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012316
Benjamin Peterson14339b62009-01-31 16:36:08 +000012317 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012318}
12319
12320
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012321PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012322 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012323\n\
12324Return a copy of the string S with leading and trailing\n\
12325whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012326If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012327
12328static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012329unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012330{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012331 if (PyTuple_GET_SIZE(args) == 0)
12332 return do_strip(self, BOTHSTRIP); /* Common case */
12333 else
12334 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012335}
12336
12337
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012338PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012339 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012340\n\
12341Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012342If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012343
12344static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012345unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012346{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012347 if (PyTuple_GET_SIZE(args) == 0)
12348 return do_strip(self, LEFTSTRIP); /* Common case */
12349 else
12350 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012351}
12352
12353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012354PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012355 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012356\n\
12357Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012358If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012359
12360static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012361unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012362{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012363 if (PyTuple_GET_SIZE(args) == 0)
12364 return do_strip(self, RIGHTSTRIP); /* Common case */
12365 else
12366 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012367}
12368
12369
Guido van Rossumd57fd912000-03-10 22:53:23 +000012370static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012371unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012373 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012374 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012375
Serhiy Storchaka05997252013-01-26 12:14:02 +020012376 if (len < 1)
12377 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012378
Victor Stinnerc4b49542011-12-11 22:44:26 +010012379 /* no repeat, return original string */
12380 if (len == 1)
12381 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012382
Benjamin Petersonbac79492012-01-14 13:34:47 -050012383 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012384 return NULL;
12385
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012386 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012387 PyErr_SetString(PyExc_OverflowError,
12388 "repeated string is too long");
12389 return NULL;
12390 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012391 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012392
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012393 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012394 if (!u)
12395 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012396 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012398 if (PyUnicode_GET_LENGTH(str) == 1) {
12399 const int kind = PyUnicode_KIND(str);
12400 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012401 if (kind == PyUnicode_1BYTE_KIND) {
12402 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012403 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012404 }
12405 else if (kind == PyUnicode_2BYTE_KIND) {
12406 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012407 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012408 ucs2[n] = fill_char;
12409 } else {
12410 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12411 assert(kind == PyUnicode_4BYTE_KIND);
12412 for (n = 0; n < len; ++n)
12413 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012414 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012415 }
12416 else {
12417 /* number of characters copied this far */
12418 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012419 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012421 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012423 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012424 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012425 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012426 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012427 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012428 }
12429
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012430 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012431 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012432}
12433
Alexander Belopolsky40018472011-02-26 01:02:56 +000012434PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012435PyUnicode_Replace(PyObject *str,
12436 PyObject *substr,
12437 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012438 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012439{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012440 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12441 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012442 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012443 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012444}
12445
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012446PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012447 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012448\n\
12449Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012450old replaced by new. If the optional argument count is\n\
12451given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012452
12453static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012454unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012455{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 PyObject *str1;
12457 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012458 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012460 if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012461 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012462 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012463 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012464 return replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012465}
12466
Alexander Belopolsky40018472011-02-26 01:02:56 +000012467static PyObject *
12468unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012470 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012471 Py_ssize_t isize;
12472 Py_ssize_t osize, squote, dquote, i, o;
12473 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012474 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012475 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012476
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012477 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012478 return NULL;
12479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480 isize = PyUnicode_GET_LENGTH(unicode);
12481 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012482
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012483 /* Compute length of output, quote characters, and
12484 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012485 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486 max = 127;
12487 squote = dquote = 0;
12488 ikind = PyUnicode_KIND(unicode);
12489 for (i = 0; i < isize; i++) {
12490 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012491 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012492 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012493 case '\'': squote++; break;
12494 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012495 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012496 incr = 2;
12497 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012498 default:
12499 /* Fast-path ASCII */
12500 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012501 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012502 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012503 ;
12504 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012505 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012507 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012508 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012509 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012510 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012511 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012512 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012513 if (osize > PY_SSIZE_T_MAX - incr) {
12514 PyErr_SetString(PyExc_OverflowError,
12515 "string is too long to generate repr");
12516 return NULL;
12517 }
12518 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012519 }
12520
12521 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012522 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012523 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012524 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012525 if (dquote)
12526 /* Both squote and dquote present. Use squote,
12527 and escape them */
12528 osize += squote;
12529 else
12530 quote = '"';
12531 }
Victor Stinner55c08782013-04-14 18:45:39 +020012532 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012533
12534 repr = PyUnicode_New(osize, max);
12535 if (repr == NULL)
12536 return NULL;
12537 okind = PyUnicode_KIND(repr);
12538 odata = PyUnicode_DATA(repr);
12539
12540 PyUnicode_WRITE(okind, odata, 0, quote);
12541 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012542 if (unchanged) {
12543 _PyUnicode_FastCopyCharacters(repr, 1,
12544 unicode, 0,
12545 isize);
12546 }
12547 else {
12548 for (i = 0, o = 1; i < isize; i++) {
12549 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550
Victor Stinner55c08782013-04-14 18:45:39 +020012551 /* Escape quotes and backslashes */
12552 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012553 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012554 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012555 continue;
12556 }
12557
12558 /* Map special whitespace to '\t', \n', '\r' */
12559 if (ch == '\t') {
12560 PyUnicode_WRITE(okind, odata, o++, '\\');
12561 PyUnicode_WRITE(okind, odata, o++, 't');
12562 }
12563 else if (ch == '\n') {
12564 PyUnicode_WRITE(okind, odata, o++, '\\');
12565 PyUnicode_WRITE(okind, odata, o++, 'n');
12566 }
12567 else if (ch == '\r') {
12568 PyUnicode_WRITE(okind, odata, o++, '\\');
12569 PyUnicode_WRITE(okind, odata, o++, 'r');
12570 }
12571
12572 /* Map non-printable US ASCII to '\xhh' */
12573 else if (ch < ' ' || ch == 0x7F) {
12574 PyUnicode_WRITE(okind, odata, o++, '\\');
12575 PyUnicode_WRITE(okind, odata, o++, 'x');
12576 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12577 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12578 }
12579
12580 /* Copy ASCII characters as-is */
12581 else if (ch < 0x7F) {
12582 PyUnicode_WRITE(okind, odata, o++, ch);
12583 }
12584
12585 /* Non-ASCII characters */
12586 else {
12587 /* Map Unicode whitespace and control characters
12588 (categories Z* and C* except ASCII space)
12589 */
12590 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12591 PyUnicode_WRITE(okind, odata, o++, '\\');
12592 /* Map 8-bit characters to '\xhh' */
12593 if (ch <= 0xff) {
12594 PyUnicode_WRITE(okind, odata, o++, 'x');
12595 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12596 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12597 }
12598 /* Map 16-bit characters to '\uxxxx' */
12599 else if (ch <= 0xffff) {
12600 PyUnicode_WRITE(okind, odata, o++, 'u');
12601 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12602 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12603 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12604 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12605 }
12606 /* Map 21-bit characters to '\U00xxxxxx' */
12607 else {
12608 PyUnicode_WRITE(okind, odata, o++, 'U');
12609 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12610 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12611 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12612 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12613 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12614 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12615 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12616 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12617 }
12618 }
12619 /* Copy characters as-is */
12620 else {
12621 PyUnicode_WRITE(okind, odata, o++, ch);
12622 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012623 }
12624 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012625 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012626 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012627 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012628 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629}
12630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012631PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012632 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633\n\
12634Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012635such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636arguments start and end are interpreted as in slice notation.\n\
12637\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012638Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012639
12640static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012641unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012643 /* initialize variables to prevent gcc warning */
12644 PyObject *substring = NULL;
12645 Py_ssize_t start = 0;
12646 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012647 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012649 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012650 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012651
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012652 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012654
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012655 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012656
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012657 if (result == -2)
12658 return NULL;
12659
Christian Heimes217cfd12007-12-02 14:31:20 +000012660 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012661}
12662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012663PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012664 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012666Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667
12668static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012669unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012671 /* initialize variables to prevent gcc warning */
12672 PyObject *substring = NULL;
12673 Py_ssize_t start = 0;
12674 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012675 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012677 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012678 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012679
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012680 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012681 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012682
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012683 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012684
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012685 if (result == -2)
12686 return NULL;
12687
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688 if (result < 0) {
12689 PyErr_SetString(PyExc_ValueError, "substring not found");
12690 return NULL;
12691 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692
Christian Heimes217cfd12007-12-02 14:31:20 +000012693 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694}
12695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012696PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012697 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012699Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012700done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701
12702static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012703unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012704{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012705 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012706 Py_UCS4 fillchar = ' ';
12707
Victor Stinnere9a29352011-10-01 02:14:59 +020012708 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012709 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012710
Benjamin Petersonbac79492012-01-14 13:34:47 -050012711 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712 return NULL;
12713
Victor Stinnerc4b49542011-12-11 22:44:26 +010012714 if (PyUnicode_GET_LENGTH(self) >= width)
12715 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012716
Victor Stinnerc4b49542011-12-11 22:44:26 +010012717 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718}
12719
Alexander Belopolsky40018472011-02-26 01:02:56 +000012720PyObject *
12721PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012723 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012724 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012726 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012727}
12728
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012729PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012730 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731\n\
12732Return a list of the words in S, using sep as the\n\
12733delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012734splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012735whitespace string is a separator and empty strings are\n\
12736removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012737
12738static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012739unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012741 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012742 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012743 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012744
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012745 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12746 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747 return NULL;
12748
12749 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012750 return split(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012751
12752 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012753 return split(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012754
12755 PyErr_Format(PyExc_TypeError,
12756 "must be str or None, not %.100s",
12757 Py_TYPE(substring)->tp_name);
12758 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012759}
12760
Thomas Wouters477c8d52006-05-27 19:21:47 +000012761PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012762PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012763{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012764 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012765 int kind1, kind2;
12766 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012767 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012768
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012769 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012770 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012771
Victor Stinner14f8f022011-10-05 20:58:25 +020012772 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012773 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012774 len1 = PyUnicode_GET_LENGTH(str_obj);
12775 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012776 if (kind1 < kind2 || len1 < len2) {
12777 _Py_INCREF_UNICODE_EMPTY();
12778 if (!unicode_empty)
12779 out = NULL;
12780 else {
12781 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12782 Py_DECREF(unicode_empty);
12783 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012784 return out;
12785 }
12786 buf1 = PyUnicode_DATA(str_obj);
12787 buf2 = PyUnicode_DATA(sep_obj);
12788 if (kind2 != kind1) {
12789 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12790 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012791 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012792 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012793
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012794 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012795 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012796 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12797 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12798 else
12799 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012800 break;
12801 case PyUnicode_2BYTE_KIND:
12802 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12803 break;
12804 case PyUnicode_4BYTE_KIND:
12805 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12806 break;
12807 default:
12808 assert(0);
12809 out = 0;
12810 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012811
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012812 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012813 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012814
12815 return out;
12816}
12817
12818
12819PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012820PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012821{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012822 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012823 int kind1, kind2;
12824 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012825 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012826
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012827 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012828 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012829
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012830 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012831 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012832 len1 = PyUnicode_GET_LENGTH(str_obj);
12833 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012834 if (kind1 < kind2 || len1 < len2) {
12835 _Py_INCREF_UNICODE_EMPTY();
12836 if (!unicode_empty)
12837 out = NULL;
12838 else {
12839 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12840 Py_DECREF(unicode_empty);
12841 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012842 return out;
12843 }
12844 buf1 = PyUnicode_DATA(str_obj);
12845 buf2 = PyUnicode_DATA(sep_obj);
12846 if (kind2 != kind1) {
12847 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12848 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012849 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012850 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012851
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012852 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012853 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012854 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12855 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12856 else
12857 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012858 break;
12859 case PyUnicode_2BYTE_KIND:
12860 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12861 break;
12862 case PyUnicode_4BYTE_KIND:
12863 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12864 break;
12865 default:
12866 assert(0);
12867 out = 0;
12868 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012869
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012870 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012871 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012872
12873 return out;
12874}
12875
12876PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012877 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012878\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012879Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012880the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012881found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012882
12883static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012884unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012885{
Victor Stinner9310abb2011-10-05 00:59:23 +020012886 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012887}
12888
12889PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012890 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012891\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012892Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012893the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012894separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012895
12896static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012897unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012898{
Victor Stinner9310abb2011-10-05 00:59:23 +020012899 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012900}
12901
Alexander Belopolsky40018472011-02-26 01:02:56 +000012902PyObject *
12903PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012904{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012905 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012906 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012907
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012908 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012909}
12910
12911PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012912 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012913\n\
12914Return a list of the words in S, using sep as the\n\
12915delimiter string, starting at the end of the string and\n\
12916working to the front. If maxsplit is given, at most maxsplit\n\
12917splits are done. If sep is not specified, any whitespace string\n\
12918is a separator.");
12919
12920static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012921unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012922{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012923 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012924 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012925 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012926
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012927 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12928 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012929 return NULL;
12930
12931 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012932 return rsplit(self, NULL, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012933
12934 if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012935 return rsplit(self, substring, maxcount);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012936
12937 PyErr_Format(PyExc_TypeError,
12938 "must be str or None, not %.100s",
12939 Py_TYPE(substring)->tp_name);
12940 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012941}
12942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012943PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012944 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012945\n\
12946Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012947Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012948is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012949
12950static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012951unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012952{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012953 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012954 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012955
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012956 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12957 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012958 return NULL;
12959
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012960 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012961}
12962
12963static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012964PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012965{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012966 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012967}
12968
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012969PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012970 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012971\n\
12972Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012973and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012974
12975static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012976unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012977{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012978 if (PyUnicode_READY(self) == -1)
12979 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012980 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012981}
12982
Larry Hastings61272b72014-01-07 12:41:53 -080012983/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012984
Larry Hastings31826802013-10-19 00:09:25 -070012985@staticmethod
12986str.maketrans as unicode_maketrans
12987
12988 x: object
12989
12990 y: unicode=NULL
12991
12992 z: unicode=NULL
12993
12994 /
12995
12996Return a translation table usable for str.translate().
12997
12998If there is only one argument, it must be a dictionary mapping Unicode
12999ordinals (integers) or characters to Unicode ordinals, strings or None.
13000Character keys will be then converted to ordinals.
13001If there are two arguments, they must be strings of equal length, and
13002in the resulting dictionary, each character in x will be mapped to the
13003character at the same position in y. If there is a third argument, it
13004must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013005[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013006
Larry Hastings31826802013-10-19 00:09:25 -070013007static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013008unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013009/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013010{
Georg Brandlceee0772007-11-27 23:48:05 +000013011 PyObject *new = NULL, *key, *value;
13012 Py_ssize_t i = 0;
13013 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013014
Georg Brandlceee0772007-11-27 23:48:05 +000013015 new = PyDict_New();
13016 if (!new)
13017 return NULL;
13018 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013019 int x_kind, y_kind, z_kind;
13020 void *x_data, *y_data, *z_data;
13021
Georg Brandlceee0772007-11-27 23:48:05 +000013022 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013023 if (!PyUnicode_Check(x)) {
13024 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13025 "be a string if there is a second argument");
13026 goto err;
13027 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013028 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013029 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13030 "arguments must have equal length");
13031 goto err;
13032 }
13033 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013034 x_kind = PyUnicode_KIND(x);
13035 y_kind = PyUnicode_KIND(y);
13036 x_data = PyUnicode_DATA(x);
13037 y_data = PyUnicode_DATA(y);
13038 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13039 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013040 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013041 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013042 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013043 if (!value) {
13044 Py_DECREF(key);
13045 goto err;
13046 }
Georg Brandlceee0772007-11-27 23:48:05 +000013047 res = PyDict_SetItem(new, key, value);
13048 Py_DECREF(key);
13049 Py_DECREF(value);
13050 if (res < 0)
13051 goto err;
13052 }
13053 /* create entries for deleting chars in z */
13054 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013055 z_kind = PyUnicode_KIND(z);
13056 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013057 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013058 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013059 if (!key)
13060 goto err;
13061 res = PyDict_SetItem(new, key, Py_None);
13062 Py_DECREF(key);
13063 if (res < 0)
13064 goto err;
13065 }
13066 }
13067 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013068 int kind;
13069 void *data;
13070
Georg Brandlceee0772007-11-27 23:48:05 +000013071 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013072 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013073 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13074 "to maketrans it must be a dict");
13075 goto err;
13076 }
13077 /* copy entries into the new dict, converting string keys to int keys */
13078 while (PyDict_Next(x, &i, &key, &value)) {
13079 if (PyUnicode_Check(key)) {
13080 /* convert string keys to integer keys */
13081 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013082 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013083 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13084 "table must be of length 1");
13085 goto err;
13086 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013087 kind = PyUnicode_KIND(key);
13088 data = PyUnicode_DATA(key);
13089 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013090 if (!newkey)
13091 goto err;
13092 res = PyDict_SetItem(new, newkey, value);
13093 Py_DECREF(newkey);
13094 if (res < 0)
13095 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013096 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013097 /* just keep integer keys */
13098 if (PyDict_SetItem(new, key, value) < 0)
13099 goto err;
13100 } else {
13101 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13102 "be strings or integers");
13103 goto err;
13104 }
13105 }
13106 }
13107 return new;
13108 err:
13109 Py_DECREF(new);
13110 return NULL;
13111}
13112
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013113PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013114 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013116Return a copy of the string S in which each character has been mapped\n\
13117through the given translation table. The table must implement\n\
13118lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13119mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13120this operation raises LookupError, the character is left untouched.\n\
13121Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122
13123static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013124unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013125{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013126 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127}
13128
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013129PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013130 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013131\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013132Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013133
13134static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013135unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013136{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013137 if (PyUnicode_READY(self) == -1)
13138 return NULL;
13139 if (PyUnicode_IS_ASCII(self))
13140 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013141 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013142}
13143
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013144PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013145 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013146\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013147Pad a numeric string S with zeros on the left, to fill a field\n\
13148of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013149
13150static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013151unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013153 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013154 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013155 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013156 int kind;
13157 void *data;
13158 Py_UCS4 chr;
13159
Martin v. Löwis18e16552006-02-15 17:27:45 +000013160 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013161 return NULL;
13162
Benjamin Petersonbac79492012-01-14 13:34:47 -050013163 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013164 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013165
Victor Stinnerc4b49542011-12-11 22:44:26 +010013166 if (PyUnicode_GET_LENGTH(self) >= width)
13167 return unicode_result_unchanged(self);
13168
13169 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013170
13171 u = pad(self, fill, 0, '0');
13172
Walter Dörwald068325e2002-04-15 13:36:47 +000013173 if (u == NULL)
13174 return NULL;
13175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013176 kind = PyUnicode_KIND(u);
13177 data = PyUnicode_DATA(u);
13178 chr = PyUnicode_READ(kind, data, fill);
13179
13180 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013181 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013182 PyUnicode_WRITE(kind, data, 0, chr);
13183 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184 }
13185
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013186 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013187 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013189
13190#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013191static PyObject *
13192unicode__decimal2ascii(PyObject *self)
13193{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013194 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013195}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013196#endif
13197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013198PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013199 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013200\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013201Return True if S starts with the specified prefix, False otherwise.\n\
13202With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013203With optional end, stop comparing S at that position.\n\
13204prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205
13206static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013207unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013208 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013210 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013211 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013212 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013213 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013214 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215
Jesus Ceaac451502011-04-20 17:09:23 +020013216 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013217 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013218 if (PyTuple_Check(subobj)) {
13219 Py_ssize_t i;
13220 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013221 substring = PyTuple_GET_ITEM(subobj, i);
13222 if (!PyUnicode_Check(substring)) {
13223 PyErr_Format(PyExc_TypeError,
13224 "tuple for startswith must only contain str, "
13225 "not %.100s",
13226 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013227 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013228 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013229 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013230 if (result == -1)
13231 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013232 if (result) {
13233 Py_RETURN_TRUE;
13234 }
13235 }
13236 /* nothing matched */
13237 Py_RETURN_FALSE;
13238 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013239 if (!PyUnicode_Check(subobj)) {
13240 PyErr_Format(PyExc_TypeError,
13241 "startswith first arg must be str or "
13242 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013243 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013244 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013245 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013246 if (result == -1)
13247 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013248 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013249}
13250
13251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013252PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013253 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013254\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013255Return True if S ends with the specified suffix, False otherwise.\n\
13256With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013257With optional end, stop comparing S at that position.\n\
13258suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013259
13260static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013261unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013262 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013263{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013264 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013265 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013266 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013267 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013268 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013269
Jesus Ceaac451502011-04-20 17:09:23 +020013270 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013271 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013272 if (PyTuple_Check(subobj)) {
13273 Py_ssize_t i;
13274 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013275 substring = PyTuple_GET_ITEM(subobj, i);
13276 if (!PyUnicode_Check(substring)) {
13277 PyErr_Format(PyExc_TypeError,
13278 "tuple for endswith must only contain str, "
13279 "not %.100s",
13280 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013281 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013282 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013283 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013284 if (result == -1)
13285 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013286 if (result) {
13287 Py_RETURN_TRUE;
13288 }
13289 }
13290 Py_RETURN_FALSE;
13291 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013292 if (!PyUnicode_Check(subobj)) {
13293 PyErr_Format(PyExc_TypeError,
13294 "endswith first arg must be str or "
13295 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013296 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013297 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013298 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013299 if (result == -1)
13300 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013301 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013302}
13303
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013304static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013305_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013306{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013307 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13308 writer->data = PyUnicode_DATA(writer->buffer);
13309
13310 if (!writer->readonly) {
13311 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013312 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013313 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013314 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013315 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13316 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13317 writer->kind = PyUnicode_WCHAR_KIND;
13318 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13319
Victor Stinner8f674cc2013-04-17 23:02:17 +020013320 /* Copy-on-write mode: set buffer size to 0 so
13321 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13322 * next write. */
13323 writer->size = 0;
13324 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013325}
13326
Victor Stinnerd3f08822012-05-29 12:57:52 +020013327void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013328_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013329{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013330 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013331
13332 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013333 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013334
13335 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13336 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13337 writer->kind = PyUnicode_WCHAR_KIND;
13338 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013339}
13340
Victor Stinnerd3f08822012-05-29 12:57:52 +020013341int
13342_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13343 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013344{
13345 Py_ssize_t newlen;
13346 PyObject *newbuffer;
13347
Victor Stinner2740e462016-09-06 16:58:36 -070013348 assert(maxchar <= MAX_UNICODE);
13349
Victor Stinnerca9381e2015-09-22 00:58:32 +020013350 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013351 assert((maxchar > writer->maxchar && length >= 0)
13352 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013353
Victor Stinner202fdca2012-05-07 12:47:02 +020013354 if (length > PY_SSIZE_T_MAX - writer->pos) {
13355 PyErr_NoMemory();
13356 return -1;
13357 }
13358 newlen = writer->pos + length;
13359
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013360 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013361
Victor Stinnerd3f08822012-05-29 12:57:52 +020013362 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013363 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013364 if (writer->overallocate
13365 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13366 /* overallocate to limit the number of realloc() */
13367 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013368 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013369 if (newlen < writer->min_length)
13370 newlen = writer->min_length;
13371
Victor Stinnerd3f08822012-05-29 12:57:52 +020013372 writer->buffer = PyUnicode_New(newlen, maxchar);
13373 if (writer->buffer == NULL)
13374 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013375 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013376 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013377 if (writer->overallocate
13378 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13379 /* overallocate to limit the number of realloc() */
13380 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013381 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013382 if (newlen < writer->min_length)
13383 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013384
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013385 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013386 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013387 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013388 newbuffer = PyUnicode_New(newlen, maxchar);
13389 if (newbuffer == NULL)
13390 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013391 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13392 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013393 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013394 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013395 }
13396 else {
13397 newbuffer = resize_compact(writer->buffer, newlen);
13398 if (newbuffer == NULL)
13399 return -1;
13400 }
13401 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013402 }
13403 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013404 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013405 newbuffer = PyUnicode_New(writer->size, maxchar);
13406 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013407 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013408 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13409 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013410 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013411 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013412 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013413 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013414
13415#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013416}
13417
Victor Stinnerca9381e2015-09-22 00:58:32 +020013418int
13419_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13420 enum PyUnicode_Kind kind)
13421{
13422 Py_UCS4 maxchar;
13423
13424 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13425 assert(writer->kind < kind);
13426
13427 switch (kind)
13428 {
13429 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13430 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13431 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13432 default:
13433 assert(0 && "invalid kind");
13434 return -1;
13435 }
13436
13437 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13438}
13439
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013440static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013441_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013442{
Victor Stinner2740e462016-09-06 16:58:36 -070013443 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013444 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13445 return -1;
13446 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13447 writer->pos++;
13448 return 0;
13449}
13450
13451int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013452_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13453{
13454 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13455}
13456
13457int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013458_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13459{
13460 Py_UCS4 maxchar;
13461 Py_ssize_t len;
13462
13463 if (PyUnicode_READY(str) == -1)
13464 return -1;
13465 len = PyUnicode_GET_LENGTH(str);
13466 if (len == 0)
13467 return 0;
13468 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13469 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013470 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013471 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013472 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013473 Py_INCREF(str);
13474 writer->buffer = str;
13475 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013476 writer->pos += len;
13477 return 0;
13478 }
13479 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13480 return -1;
13481 }
13482 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13483 str, 0, len);
13484 writer->pos += len;
13485 return 0;
13486}
13487
Victor Stinnere215d962012-10-06 23:03:36 +020013488int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013489_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13490 Py_ssize_t start, Py_ssize_t end)
13491{
13492 Py_UCS4 maxchar;
13493 Py_ssize_t len;
13494
13495 if (PyUnicode_READY(str) == -1)
13496 return -1;
13497
13498 assert(0 <= start);
13499 assert(end <= PyUnicode_GET_LENGTH(str));
13500 assert(start <= end);
13501
13502 if (end == 0)
13503 return 0;
13504
13505 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13506 return _PyUnicodeWriter_WriteStr(writer, str);
13507
13508 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13509 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13510 else
13511 maxchar = writer->maxchar;
13512 len = end - start;
13513
13514 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13515 return -1;
13516
13517 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13518 str, start, len);
13519 writer->pos += len;
13520 return 0;
13521}
13522
13523int
Victor Stinner4a587072013-11-19 12:54:53 +010013524_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13525 const char *ascii, Py_ssize_t len)
13526{
13527 if (len == -1)
13528 len = strlen(ascii);
13529
13530 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13531
13532 if (writer->buffer == NULL && !writer->overallocate) {
13533 PyObject *str;
13534
13535 str = _PyUnicode_FromASCII(ascii, len);
13536 if (str == NULL)
13537 return -1;
13538
13539 writer->readonly = 1;
13540 writer->buffer = str;
13541 _PyUnicodeWriter_Update(writer);
13542 writer->pos += len;
13543 return 0;
13544 }
13545
13546 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13547 return -1;
13548
13549 switch (writer->kind)
13550 {
13551 case PyUnicode_1BYTE_KIND:
13552 {
13553 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13554 Py_UCS1 *data = writer->data;
13555
Christian Heimesf051e432016-09-13 20:22:02 +020013556 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013557 break;
13558 }
13559 case PyUnicode_2BYTE_KIND:
13560 {
13561 _PyUnicode_CONVERT_BYTES(
13562 Py_UCS1, Py_UCS2,
13563 ascii, ascii + len,
13564 (Py_UCS2 *)writer->data + writer->pos);
13565 break;
13566 }
13567 case PyUnicode_4BYTE_KIND:
13568 {
13569 _PyUnicode_CONVERT_BYTES(
13570 Py_UCS1, Py_UCS4,
13571 ascii, ascii + len,
13572 (Py_UCS4 *)writer->data + writer->pos);
13573 break;
13574 }
13575 default:
13576 assert(0);
13577 }
13578
13579 writer->pos += len;
13580 return 0;
13581}
13582
13583int
13584_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13585 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013586{
13587 Py_UCS4 maxchar;
13588
13589 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13590 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13591 return -1;
13592 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13593 writer->pos += len;
13594 return 0;
13595}
13596
Victor Stinnerd3f08822012-05-29 12:57:52 +020013597PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013598_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013599{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013600 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013601
Victor Stinnerd3f08822012-05-29 12:57:52 +020013602 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013603 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013604 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013605 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013606
13607 str = writer->buffer;
13608 writer->buffer = NULL;
13609
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013610 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013611 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13612 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013613 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013614
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013615 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13616 PyObject *str2;
13617 str2 = resize_compact(str, writer->pos);
13618 if (str2 == NULL) {
13619 Py_DECREF(str);
13620 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013621 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013622 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013623 }
13624
Victor Stinner15a0bd32013-07-08 22:29:55 +020013625 assert(_PyUnicode_CheckConsistency(str, 1));
13626 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013627}
13628
Victor Stinnerd3f08822012-05-29 12:57:52 +020013629void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013630_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013631{
13632 Py_CLEAR(writer->buffer);
13633}
13634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013635#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013636
13637PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013638 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013639\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013640Return a formatted version of S, using substitutions from args and kwargs.\n\
13641The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013642
Eric Smith27bbca62010-11-04 17:06:58 +000013643PyDoc_STRVAR(format_map__doc__,
13644 "S.format_map(mapping) -> str\n\
13645\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013646Return a formatted version of S, using substitutions from mapping.\n\
13647The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013648
Eric Smith4a7d76d2008-05-30 18:10:19 +000013649static PyObject *
13650unicode__format__(PyObject* self, PyObject* args)
13651{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013652 PyObject *format_spec;
13653 _PyUnicodeWriter writer;
13654 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013655
13656 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13657 return NULL;
13658
Victor Stinnerd3f08822012-05-29 12:57:52 +020013659 if (PyUnicode_READY(self) == -1)
13660 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013661 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013662 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13663 self, format_spec, 0,
13664 PyUnicode_GET_LENGTH(format_spec));
13665 if (ret == -1) {
13666 _PyUnicodeWriter_Dealloc(&writer);
13667 return NULL;
13668 }
13669 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013670}
13671
Eric Smith8c663262007-08-25 02:26:07 +000013672PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013673 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013674\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013675Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013676
13677static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013678unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013679{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013680 Py_ssize_t size;
13681
13682 /* If it's a compact object, account for base structure +
13683 character data. */
13684 if (PyUnicode_IS_COMPACT_ASCII(v))
13685 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13686 else if (PyUnicode_IS_COMPACT(v))
13687 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013688 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013689 else {
13690 /* If it is a two-block object, account for base object, and
13691 for character block if present. */
13692 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013693 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013694 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013695 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013696 }
13697 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013698 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013699 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013700 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013701 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013702 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013703
13704 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013705}
13706
13707PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013708 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013709
13710static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013711unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013712{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013713 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013714 if (!copy)
13715 return NULL;
13716 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013717}
13718
Guido van Rossumd57fd912000-03-10 22:53:23 +000013719static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013720 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013721 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013722 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13723 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013724 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13725 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013726 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013727 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13728 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13729 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013730 {"expandtabs", (PyCFunction) unicode_expandtabs,
13731 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013732 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013733 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013734 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13735 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13736 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013737 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013738 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13739 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13740 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013741 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013742 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013743 {"splitlines", (PyCFunction) unicode_splitlines,
13744 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013745 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013746 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13747 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13748 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13749 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13750 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13751 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13752 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13753 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13754 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13755 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13756 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13757 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13758 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13759 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013760 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013761 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013762 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013763 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013764 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013765 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013766 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013767 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013768#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013769 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013770 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013771#endif
13772
Benjamin Peterson14339b62009-01-31 16:36:08 +000013773 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013774 {NULL, NULL}
13775};
13776
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013777static PyObject *
13778unicode_mod(PyObject *v, PyObject *w)
13779{
Brian Curtindfc80e32011-08-10 20:28:54 -050013780 if (!PyUnicode_Check(v))
13781 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013782 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013783}
13784
13785static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013786 0, /*nb_add*/
13787 0, /*nb_subtract*/
13788 0, /*nb_multiply*/
13789 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013790};
13791
Guido van Rossumd57fd912000-03-10 22:53:23 +000013792static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013793 (lenfunc) unicode_length, /* sq_length */
13794 PyUnicode_Concat, /* sq_concat */
13795 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13796 (ssizeargfunc) unicode_getitem, /* sq_item */
13797 0, /* sq_slice */
13798 0, /* sq_ass_item */
13799 0, /* sq_ass_slice */
13800 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013801};
13802
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013803static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013804unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013805{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013806 if (PyUnicode_READY(self) == -1)
13807 return NULL;
13808
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013809 if (PyIndex_Check(item)) {
13810 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013811 if (i == -1 && PyErr_Occurred())
13812 return NULL;
13813 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013814 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013815 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013816 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013817 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013818 PyObject *result;
13819 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013820 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013821 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013823 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013824 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013825 return NULL;
13826 }
13827
13828 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013829 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013830 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013831 slicelength == PyUnicode_GET_LENGTH(self)) {
13832 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013833 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013834 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013835 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013836 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013837 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013838 src_kind = PyUnicode_KIND(self);
13839 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013840 if (!PyUnicode_IS_ASCII(self)) {
13841 kind_limit = kind_maxchar_limit(src_kind);
13842 max_char = 0;
13843 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13844 ch = PyUnicode_READ(src_kind, src_data, cur);
13845 if (ch > max_char) {
13846 max_char = ch;
13847 if (max_char >= kind_limit)
13848 break;
13849 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013850 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013851 }
Victor Stinner55c99112011-10-13 01:17:06 +020013852 else
13853 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013854 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013855 if (result == NULL)
13856 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013857 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013858 dest_data = PyUnicode_DATA(result);
13859
13860 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013861 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13862 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013863 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013864 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013865 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013866 } else {
13867 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13868 return NULL;
13869 }
13870}
13871
13872static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013873 (lenfunc)unicode_length, /* mp_length */
13874 (binaryfunc)unicode_subscript, /* mp_subscript */
13875 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013876};
13877
Guido van Rossumd57fd912000-03-10 22:53:23 +000013878
Guido van Rossumd57fd912000-03-10 22:53:23 +000013879/* Helpers for PyUnicode_Format() */
13880
Victor Stinnera47082312012-10-04 02:19:54 +020013881struct unicode_formatter_t {
13882 PyObject *args;
13883 int args_owned;
13884 Py_ssize_t arglen, argidx;
13885 PyObject *dict;
13886
13887 enum PyUnicode_Kind fmtkind;
13888 Py_ssize_t fmtcnt, fmtpos;
13889 void *fmtdata;
13890 PyObject *fmtstr;
13891
13892 _PyUnicodeWriter writer;
13893};
13894
13895struct unicode_format_arg_t {
13896 Py_UCS4 ch;
13897 int flags;
13898 Py_ssize_t width;
13899 int prec;
13900 int sign;
13901};
13902
Guido van Rossumd57fd912000-03-10 22:53:23 +000013903static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013904unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013905{
Victor Stinnera47082312012-10-04 02:19:54 +020013906 Py_ssize_t argidx = ctx->argidx;
13907
13908 if (argidx < ctx->arglen) {
13909 ctx->argidx++;
13910 if (ctx->arglen < 0)
13911 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013912 else
Victor Stinnera47082312012-10-04 02:19:54 +020013913 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013914 }
13915 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013916 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013917 return NULL;
13918}
13919
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013920/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013921
Victor Stinnera47082312012-10-04 02:19:54 +020013922/* Format a float into the writer if the writer is not NULL, or into *p_output
13923 otherwise.
13924
13925 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013926static int
Victor Stinnera47082312012-10-04 02:19:54 +020013927formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13928 PyObject **p_output,
13929 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013930{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013931 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013932 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013933 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013934 int prec;
13935 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013936
Guido van Rossumd57fd912000-03-10 22:53:23 +000013937 x = PyFloat_AsDouble(v);
13938 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013939 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013940
Victor Stinnera47082312012-10-04 02:19:54 +020013941 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013942 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013943 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013944
Victor Stinnera47082312012-10-04 02:19:54 +020013945 if (arg->flags & F_ALT)
13946 dtoa_flags = Py_DTSF_ALT;
13947 else
13948 dtoa_flags = 0;
13949 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013950 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013951 return -1;
13952 len = strlen(p);
13953 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013954 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013955 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013956 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013957 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013958 }
13959 else
13960 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013961 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013962 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013963}
13964
Victor Stinnerd0880d52012-04-27 23:40:13 +020013965/* formatlong() emulates the format codes d, u, o, x and X, and
13966 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13967 * Python's regular ints.
13968 * Return value: a new PyUnicodeObject*, or NULL if error.
13969 * The output string is of the form
13970 * "-"? ("0x" | "0X")? digit+
13971 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13972 * set in flags. The case of hex digits will be correct,
13973 * There will be at least prec digits, zero-filled on the left if
13974 * necessary to get that many.
13975 * val object to be converted
13976 * flags bitmask of format flags; only F_ALT is looked at
13977 * prec minimum number of digits; 0-fill on left if needed
13978 * type a character in [duoxX]; u acts the same as d
13979 *
13980 * CAUTION: o, x and X conversions on regular ints can never
13981 * produce a '-' sign, but can for Python's unbounded ints.
13982 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013983PyObject *
13984_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013985{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013986 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013987 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013988 Py_ssize_t i;
13989 int sign; /* 1 if '-', else 0 */
13990 int len; /* number of characters */
13991 Py_ssize_t llen;
13992 int numdigits; /* len == numnondigits + numdigits */
13993 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013994
Victor Stinnerd0880d52012-04-27 23:40:13 +020013995 /* Avoid exceeding SSIZE_T_MAX */
13996 if (prec > INT_MAX-3) {
13997 PyErr_SetString(PyExc_OverflowError,
13998 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013999 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014000 }
14001
14002 assert(PyLong_Check(val));
14003
14004 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014005 default:
14006 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014007 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014008 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014009 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014010 /* int and int subclasses should print numerically when a numeric */
14011 /* format code is used (see issue18780) */
14012 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014013 break;
14014 case 'o':
14015 numnondigits = 2;
14016 result = PyNumber_ToBase(val, 8);
14017 break;
14018 case 'x':
14019 case 'X':
14020 numnondigits = 2;
14021 result = PyNumber_ToBase(val, 16);
14022 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014023 }
14024 if (!result)
14025 return NULL;
14026
14027 assert(unicode_modifiable(result));
14028 assert(PyUnicode_IS_READY(result));
14029 assert(PyUnicode_IS_ASCII(result));
14030
14031 /* To modify the string in-place, there can only be one reference. */
14032 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014033 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014034 PyErr_BadInternalCall();
14035 return NULL;
14036 }
14037 buf = PyUnicode_DATA(result);
14038 llen = PyUnicode_GET_LENGTH(result);
14039 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014040 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014041 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014042 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014043 return NULL;
14044 }
14045 len = (int)llen;
14046 sign = buf[0] == '-';
14047 numnondigits += sign;
14048 numdigits = len - numnondigits;
14049 assert(numdigits > 0);
14050
14051 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014052 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014053 (type == 'o' || type == 'x' || type == 'X'))) {
14054 assert(buf[sign] == '0');
14055 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14056 buf[sign+1] == 'o');
14057 numnondigits -= 2;
14058 buf += 2;
14059 len -= 2;
14060 if (sign)
14061 buf[0] = '-';
14062 assert(len == numnondigits + numdigits);
14063 assert(numdigits > 0);
14064 }
14065
14066 /* Fill with leading zeroes to meet minimum width. */
14067 if (prec > numdigits) {
14068 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14069 numnondigits + prec);
14070 char *b1;
14071 if (!r1) {
14072 Py_DECREF(result);
14073 return NULL;
14074 }
14075 b1 = PyBytes_AS_STRING(r1);
14076 for (i = 0; i < numnondigits; ++i)
14077 *b1++ = *buf++;
14078 for (i = 0; i < prec - numdigits; i++)
14079 *b1++ = '0';
14080 for (i = 0; i < numdigits; i++)
14081 *b1++ = *buf++;
14082 *b1 = '\0';
14083 Py_DECREF(result);
14084 result = r1;
14085 buf = PyBytes_AS_STRING(result);
14086 len = numnondigits + prec;
14087 }
14088
14089 /* Fix up case for hex conversions. */
14090 if (type == 'X') {
14091 /* Need to convert all lower case letters to upper case.
14092 and need to convert 0x to 0X (and -0x to -0X). */
14093 for (i = 0; i < len; i++)
14094 if (buf[i] >= 'a' && buf[i] <= 'x')
14095 buf[i] -= 'a'-'A';
14096 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014097 if (!PyUnicode_Check(result)
14098 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014099 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014100 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014101 Py_DECREF(result);
14102 result = unicode;
14103 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014104 else if (len != PyUnicode_GET_LENGTH(result)) {
14105 if (PyUnicode_Resize(&result, len) < 0)
14106 Py_CLEAR(result);
14107 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014108 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014109}
14110
Ethan Furmandf3ed242014-01-05 06:50:30 -080014111/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014112 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014113 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014114 * -1 and raise an exception on error */
14115static int
Victor Stinnera47082312012-10-04 02:19:54 +020014116mainformatlong(PyObject *v,
14117 struct unicode_format_arg_t *arg,
14118 PyObject **p_output,
14119 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014120{
14121 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014122 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014123
14124 if (!PyNumber_Check(v))
14125 goto wrongtype;
14126
Ethan Furman9ab74802014-03-21 06:38:46 -070014127 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014128 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014129 if (type == 'o' || type == 'x' || type == 'X') {
14130 iobj = PyNumber_Index(v);
14131 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014132 if (PyErr_ExceptionMatches(PyExc_TypeError))
14133 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014134 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014135 }
14136 }
14137 else {
14138 iobj = PyNumber_Long(v);
14139 if (iobj == NULL ) {
14140 if (PyErr_ExceptionMatches(PyExc_TypeError))
14141 goto wrongtype;
14142 return -1;
14143 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014144 }
14145 assert(PyLong_Check(iobj));
14146 }
14147 else {
14148 iobj = v;
14149 Py_INCREF(iobj);
14150 }
14151
14152 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014153 && arg->width == -1 && arg->prec == -1
14154 && !(arg->flags & (F_SIGN | F_BLANK))
14155 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014156 {
14157 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014158 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014159 int base;
14160
Victor Stinnera47082312012-10-04 02:19:54 +020014161 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014162 {
14163 default:
14164 assert(0 && "'type' not in [diuoxX]");
14165 case 'd':
14166 case 'i':
14167 case 'u':
14168 base = 10;
14169 break;
14170 case 'o':
14171 base = 8;
14172 break;
14173 case 'x':
14174 case 'X':
14175 base = 16;
14176 break;
14177 }
14178
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014179 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14180 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014181 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014182 }
14183 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014184 return 1;
14185 }
14186
Ethan Furmanb95b5612015-01-23 20:05:18 -080014187 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014188 Py_DECREF(iobj);
14189 if (res == NULL)
14190 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014191 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014192 return 0;
14193
14194wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014195 switch(type)
14196 {
14197 case 'o':
14198 case 'x':
14199 case 'X':
14200 PyErr_Format(PyExc_TypeError,
14201 "%%%c format: an integer is required, "
14202 "not %.200s",
14203 type, Py_TYPE(v)->tp_name);
14204 break;
14205 default:
14206 PyErr_Format(PyExc_TypeError,
14207 "%%%c format: a number is required, "
14208 "not %.200s",
14209 type, Py_TYPE(v)->tp_name);
14210 break;
14211 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014212 return -1;
14213}
14214
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014215static Py_UCS4
14216formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014217{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014218 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014219 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014220 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014221 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014222 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014223 goto onError;
14224 }
14225 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014226 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014227 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014228 /* make sure number is a type of integer */
14229 if (!PyLong_Check(v)) {
14230 iobj = PyNumber_Index(v);
14231 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014232 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014233 }
14234 v = iobj;
14235 Py_DECREF(iobj);
14236 }
14237 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014238 x = PyLong_AsLong(v);
14239 if (x == -1 && PyErr_Occurred())
14240 goto onError;
14241
Victor Stinner8faf8212011-12-08 22:14:11 +010014242 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014243 PyErr_SetString(PyExc_OverflowError,
14244 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014245 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014246 }
14247
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014248 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014249 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014250
Benjamin Peterson29060642009-01-31 22:14:21 +000014251 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014252 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014253 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014254 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014255}
14256
Victor Stinnera47082312012-10-04 02:19:54 +020014257/* Parse options of an argument: flags, width, precision.
14258 Handle also "%(name)" syntax.
14259
14260 Return 0 if the argument has been formatted into arg->str.
14261 Return 1 if the argument has been written into ctx->writer,
14262 Raise an exception and return -1 on error. */
14263static int
14264unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14265 struct unicode_format_arg_t *arg)
14266{
14267#define FORMAT_READ(ctx) \
14268 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14269
14270 PyObject *v;
14271
Victor Stinnera47082312012-10-04 02:19:54 +020014272 if (arg->ch == '(') {
14273 /* Get argument value from a dictionary. Example: "%(name)s". */
14274 Py_ssize_t keystart;
14275 Py_ssize_t keylen;
14276 PyObject *key;
14277 int pcount = 1;
14278
14279 if (ctx->dict == NULL) {
14280 PyErr_SetString(PyExc_TypeError,
14281 "format requires a mapping");
14282 return -1;
14283 }
14284 ++ctx->fmtpos;
14285 --ctx->fmtcnt;
14286 keystart = ctx->fmtpos;
14287 /* Skip over balanced parentheses */
14288 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14289 arg->ch = FORMAT_READ(ctx);
14290 if (arg->ch == ')')
14291 --pcount;
14292 else if (arg->ch == '(')
14293 ++pcount;
14294 ctx->fmtpos++;
14295 }
14296 keylen = ctx->fmtpos - keystart - 1;
14297 if (ctx->fmtcnt < 0 || pcount > 0) {
14298 PyErr_SetString(PyExc_ValueError,
14299 "incomplete format key");
14300 return -1;
14301 }
14302 key = PyUnicode_Substring(ctx->fmtstr,
14303 keystart, keystart + keylen);
14304 if (key == NULL)
14305 return -1;
14306 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014307 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014308 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014309 }
14310 ctx->args = PyObject_GetItem(ctx->dict, key);
14311 Py_DECREF(key);
14312 if (ctx->args == NULL)
14313 return -1;
14314 ctx->args_owned = 1;
14315 ctx->arglen = -1;
14316 ctx->argidx = -2;
14317 }
14318
14319 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014320 while (--ctx->fmtcnt >= 0) {
14321 arg->ch = FORMAT_READ(ctx);
14322 ctx->fmtpos++;
14323 switch (arg->ch) {
14324 case '-': arg->flags |= F_LJUST; continue;
14325 case '+': arg->flags |= F_SIGN; continue;
14326 case ' ': arg->flags |= F_BLANK; continue;
14327 case '#': arg->flags |= F_ALT; continue;
14328 case '0': arg->flags |= F_ZERO; continue;
14329 }
14330 break;
14331 }
14332
14333 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014334 if (arg->ch == '*') {
14335 v = unicode_format_getnextarg(ctx);
14336 if (v == NULL)
14337 return -1;
14338 if (!PyLong_Check(v)) {
14339 PyErr_SetString(PyExc_TypeError,
14340 "* wants int");
14341 return -1;
14342 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014343 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014344 if (arg->width == -1 && PyErr_Occurred())
14345 return -1;
14346 if (arg->width < 0) {
14347 arg->flags |= F_LJUST;
14348 arg->width = -arg->width;
14349 }
14350 if (--ctx->fmtcnt >= 0) {
14351 arg->ch = FORMAT_READ(ctx);
14352 ctx->fmtpos++;
14353 }
14354 }
14355 else if (arg->ch >= '0' && arg->ch <= '9') {
14356 arg->width = arg->ch - '0';
14357 while (--ctx->fmtcnt >= 0) {
14358 arg->ch = FORMAT_READ(ctx);
14359 ctx->fmtpos++;
14360 if (arg->ch < '0' || arg->ch > '9')
14361 break;
14362 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14363 mixing signed and unsigned comparison. Since arg->ch is between
14364 '0' and '9', casting to int is safe. */
14365 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14366 PyErr_SetString(PyExc_ValueError,
14367 "width too big");
14368 return -1;
14369 }
14370 arg->width = arg->width*10 + (arg->ch - '0');
14371 }
14372 }
14373
14374 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014375 if (arg->ch == '.') {
14376 arg->prec = 0;
14377 if (--ctx->fmtcnt >= 0) {
14378 arg->ch = FORMAT_READ(ctx);
14379 ctx->fmtpos++;
14380 }
14381 if (arg->ch == '*') {
14382 v = unicode_format_getnextarg(ctx);
14383 if (v == NULL)
14384 return -1;
14385 if (!PyLong_Check(v)) {
14386 PyErr_SetString(PyExc_TypeError,
14387 "* wants int");
14388 return -1;
14389 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014390 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014391 if (arg->prec == -1 && PyErr_Occurred())
14392 return -1;
14393 if (arg->prec < 0)
14394 arg->prec = 0;
14395 if (--ctx->fmtcnt >= 0) {
14396 arg->ch = FORMAT_READ(ctx);
14397 ctx->fmtpos++;
14398 }
14399 }
14400 else if (arg->ch >= '0' && arg->ch <= '9') {
14401 arg->prec = arg->ch - '0';
14402 while (--ctx->fmtcnt >= 0) {
14403 arg->ch = FORMAT_READ(ctx);
14404 ctx->fmtpos++;
14405 if (arg->ch < '0' || arg->ch > '9')
14406 break;
14407 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14408 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014409 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014410 return -1;
14411 }
14412 arg->prec = arg->prec*10 + (arg->ch - '0');
14413 }
14414 }
14415 }
14416
14417 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14418 if (ctx->fmtcnt >= 0) {
14419 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14420 if (--ctx->fmtcnt >= 0) {
14421 arg->ch = FORMAT_READ(ctx);
14422 ctx->fmtpos++;
14423 }
14424 }
14425 }
14426 if (ctx->fmtcnt < 0) {
14427 PyErr_SetString(PyExc_ValueError,
14428 "incomplete format");
14429 return -1;
14430 }
14431 return 0;
14432
14433#undef FORMAT_READ
14434}
14435
14436/* Format one argument. Supported conversion specifiers:
14437
14438 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014439 - "i", "d", "u": int or float
14440 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014441 - "e", "E", "f", "F", "g", "G": float
14442 - "c": int or str (1 character)
14443
Victor Stinner8dbd4212012-12-04 09:30:24 +010014444 When possible, the output is written directly into the Unicode writer
14445 (ctx->writer). A string is created when padding is required.
14446
Victor Stinnera47082312012-10-04 02:19:54 +020014447 Return 0 if the argument has been formatted into *p_str,
14448 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014449 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014450static int
14451unicode_format_arg_format(struct unicode_formatter_t *ctx,
14452 struct unicode_format_arg_t *arg,
14453 PyObject **p_str)
14454{
14455 PyObject *v;
14456 _PyUnicodeWriter *writer = &ctx->writer;
14457
14458 if (ctx->fmtcnt == 0)
14459 ctx->writer.overallocate = 0;
14460
14461 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014462 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014463 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014464 return 1;
14465 }
14466
14467 v = unicode_format_getnextarg(ctx);
14468 if (v == NULL)
14469 return -1;
14470
Victor Stinnera47082312012-10-04 02:19:54 +020014471
14472 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014473 case 's':
14474 case 'r':
14475 case 'a':
14476 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14477 /* Fast path */
14478 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14479 return -1;
14480 return 1;
14481 }
14482
14483 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14484 *p_str = v;
14485 Py_INCREF(*p_str);
14486 }
14487 else {
14488 if (arg->ch == 's')
14489 *p_str = PyObject_Str(v);
14490 else if (arg->ch == 'r')
14491 *p_str = PyObject_Repr(v);
14492 else
14493 *p_str = PyObject_ASCII(v);
14494 }
14495 break;
14496
14497 case 'i':
14498 case 'd':
14499 case 'u':
14500 case 'o':
14501 case 'x':
14502 case 'X':
14503 {
14504 int ret = mainformatlong(v, arg, p_str, writer);
14505 if (ret != 0)
14506 return ret;
14507 arg->sign = 1;
14508 break;
14509 }
14510
14511 case 'e':
14512 case 'E':
14513 case 'f':
14514 case 'F':
14515 case 'g':
14516 case 'G':
14517 if (arg->width == -1 && arg->prec == -1
14518 && !(arg->flags & (F_SIGN | F_BLANK)))
14519 {
14520 /* Fast path */
14521 if (formatfloat(v, arg, NULL, writer) == -1)
14522 return -1;
14523 return 1;
14524 }
14525
14526 arg->sign = 1;
14527 if (formatfloat(v, arg, p_str, NULL) == -1)
14528 return -1;
14529 break;
14530
14531 case 'c':
14532 {
14533 Py_UCS4 ch = formatchar(v);
14534 if (ch == (Py_UCS4) -1)
14535 return -1;
14536 if (arg->width == -1 && arg->prec == -1) {
14537 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014538 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014539 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014540 return 1;
14541 }
14542 *p_str = PyUnicode_FromOrdinal(ch);
14543 break;
14544 }
14545
14546 default:
14547 PyErr_Format(PyExc_ValueError,
14548 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014549 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014550 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14551 (int)arg->ch,
14552 ctx->fmtpos - 1);
14553 return -1;
14554 }
14555 if (*p_str == NULL)
14556 return -1;
14557 assert (PyUnicode_Check(*p_str));
14558 return 0;
14559}
14560
14561static int
14562unicode_format_arg_output(struct unicode_formatter_t *ctx,
14563 struct unicode_format_arg_t *arg,
14564 PyObject *str)
14565{
14566 Py_ssize_t len;
14567 enum PyUnicode_Kind kind;
14568 void *pbuf;
14569 Py_ssize_t pindex;
14570 Py_UCS4 signchar;
14571 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014572 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014573 Py_ssize_t sublen;
14574 _PyUnicodeWriter *writer = &ctx->writer;
14575 Py_UCS4 fill;
14576
14577 fill = ' ';
14578 if (arg->sign && arg->flags & F_ZERO)
14579 fill = '0';
14580
14581 if (PyUnicode_READY(str) == -1)
14582 return -1;
14583
14584 len = PyUnicode_GET_LENGTH(str);
14585 if ((arg->width == -1 || arg->width <= len)
14586 && (arg->prec == -1 || arg->prec >= len)
14587 && !(arg->flags & (F_SIGN | F_BLANK)))
14588 {
14589 /* Fast path */
14590 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14591 return -1;
14592 return 0;
14593 }
14594
14595 /* Truncate the string for "s", "r" and "a" formats
14596 if the precision is set */
14597 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14598 if (arg->prec >= 0 && len > arg->prec)
14599 len = arg->prec;
14600 }
14601
14602 /* Adjust sign and width */
14603 kind = PyUnicode_KIND(str);
14604 pbuf = PyUnicode_DATA(str);
14605 pindex = 0;
14606 signchar = '\0';
14607 if (arg->sign) {
14608 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14609 if (ch == '-' || ch == '+') {
14610 signchar = ch;
14611 len--;
14612 pindex++;
14613 }
14614 else if (arg->flags & F_SIGN)
14615 signchar = '+';
14616 else if (arg->flags & F_BLANK)
14617 signchar = ' ';
14618 else
14619 arg->sign = 0;
14620 }
14621 if (arg->width < len)
14622 arg->width = len;
14623
14624 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014625 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014626 if (!(arg->flags & F_LJUST)) {
14627 if (arg->sign) {
14628 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014629 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014630 }
14631 else {
14632 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014633 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014634 }
14635 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014636 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14637 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014638 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014639 }
14640
Victor Stinnera47082312012-10-04 02:19:54 +020014641 buflen = arg->width;
14642 if (arg->sign && len == arg->width)
14643 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014644 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014645 return -1;
14646
14647 /* Write the sign if needed */
14648 if (arg->sign) {
14649 if (fill != ' ') {
14650 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14651 writer->pos += 1;
14652 }
14653 if (arg->width > len)
14654 arg->width--;
14655 }
14656
14657 /* Write the numeric prefix for "x", "X" and "o" formats
14658 if the alternate form is used.
14659 For example, write "0x" for the "%#x" format. */
14660 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14661 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14662 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14663 if (fill != ' ') {
14664 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14665 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14666 writer->pos += 2;
14667 pindex += 2;
14668 }
14669 arg->width -= 2;
14670 if (arg->width < 0)
14671 arg->width = 0;
14672 len -= 2;
14673 }
14674
14675 /* Pad left with the fill character if needed */
14676 if (arg->width > len && !(arg->flags & F_LJUST)) {
14677 sublen = arg->width - len;
14678 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14679 writer->pos += sublen;
14680 arg->width = len;
14681 }
14682
14683 /* If padding with spaces: write sign if needed and/or numeric prefix if
14684 the alternate form is used */
14685 if (fill == ' ') {
14686 if (arg->sign) {
14687 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14688 writer->pos += 1;
14689 }
14690 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14691 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14692 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14693 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14694 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14695 writer->pos += 2;
14696 pindex += 2;
14697 }
14698 }
14699
14700 /* Write characters */
14701 if (len) {
14702 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14703 str, pindex, len);
14704 writer->pos += len;
14705 }
14706
14707 /* Pad right with the fill character if needed */
14708 if (arg->width > len) {
14709 sublen = arg->width - len;
14710 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14711 writer->pos += sublen;
14712 }
14713 return 0;
14714}
14715
14716/* Helper of PyUnicode_Format(): format one arg.
14717 Return 0 on success, raise an exception and return -1 on error. */
14718static int
14719unicode_format_arg(struct unicode_formatter_t *ctx)
14720{
14721 struct unicode_format_arg_t arg;
14722 PyObject *str;
14723 int ret;
14724
Victor Stinner8dbd4212012-12-04 09:30:24 +010014725 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14726 arg.flags = 0;
14727 arg.width = -1;
14728 arg.prec = -1;
14729 arg.sign = 0;
14730 str = NULL;
14731
Victor Stinnera47082312012-10-04 02:19:54 +020014732 ret = unicode_format_arg_parse(ctx, &arg);
14733 if (ret == -1)
14734 return -1;
14735
14736 ret = unicode_format_arg_format(ctx, &arg, &str);
14737 if (ret == -1)
14738 return -1;
14739
14740 if (ret != 1) {
14741 ret = unicode_format_arg_output(ctx, &arg, str);
14742 Py_DECREF(str);
14743 if (ret == -1)
14744 return -1;
14745 }
14746
14747 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14748 PyErr_SetString(PyExc_TypeError,
14749 "not all arguments converted during string formatting");
14750 return -1;
14751 }
14752 return 0;
14753}
14754
Alexander Belopolsky40018472011-02-26 01:02:56 +000014755PyObject *
14756PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014757{
Victor Stinnera47082312012-10-04 02:19:54 +020014758 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014759
Guido van Rossumd57fd912000-03-10 22:53:23 +000014760 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014761 PyErr_BadInternalCall();
14762 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014763 }
Victor Stinnera47082312012-10-04 02:19:54 +020014764
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014765 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014766 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014767
14768 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014769 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14770 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14771 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14772 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014773
Victor Stinner8f674cc2013-04-17 23:02:17 +020014774 _PyUnicodeWriter_Init(&ctx.writer);
14775 ctx.writer.min_length = ctx.fmtcnt + 100;
14776 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014777
Guido van Rossumd57fd912000-03-10 22:53:23 +000014778 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014779 ctx.arglen = PyTuple_Size(args);
14780 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014781 }
14782 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014783 ctx.arglen = -1;
14784 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014785 }
Victor Stinnera47082312012-10-04 02:19:54 +020014786 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014787 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014788 ctx.dict = args;
14789 else
14790 ctx.dict = NULL;
14791 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014792
Victor Stinnera47082312012-10-04 02:19:54 +020014793 while (--ctx.fmtcnt >= 0) {
14794 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014795 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014796
14797 nonfmtpos = ctx.fmtpos++;
14798 while (ctx.fmtcnt >= 0 &&
14799 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14800 ctx.fmtpos++;
14801 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014802 }
Victor Stinnera47082312012-10-04 02:19:54 +020014803 if (ctx.fmtcnt < 0) {
14804 ctx.fmtpos--;
14805 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014806 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014807
Victor Stinnercfc4c132013-04-03 01:48:39 +020014808 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14809 nonfmtpos, ctx.fmtpos) < 0)
14810 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014811 }
14812 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014813 ctx.fmtpos++;
14814 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014815 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014816 }
14817 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014818
Victor Stinnera47082312012-10-04 02:19:54 +020014819 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014820 PyErr_SetString(PyExc_TypeError,
14821 "not all arguments converted during string formatting");
14822 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014823 }
14824
Victor Stinnera47082312012-10-04 02:19:54 +020014825 if (ctx.args_owned) {
14826 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014827 }
Victor Stinnera47082312012-10-04 02:19:54 +020014828 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014829
Benjamin Peterson29060642009-01-31 22:14:21 +000014830 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014831 _PyUnicodeWriter_Dealloc(&ctx.writer);
14832 if (ctx.args_owned) {
14833 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014834 }
14835 return NULL;
14836}
14837
Jeremy Hylton938ace62002-07-17 16:30:39 +000014838static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014839unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14840
Tim Peters6d6c1a32001-08-02 04:15:00 +000014841static PyObject *
14842unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14843{
Benjamin Peterson29060642009-01-31 22:14:21 +000014844 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014845 static char *kwlist[] = {"object", "encoding", "errors", 0};
14846 char *encoding = NULL;
14847 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014848
Benjamin Peterson14339b62009-01-31 16:36:08 +000014849 if (type != &PyUnicode_Type)
14850 return unicode_subtype_new(type, args, kwds);
14851 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014852 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014853 return NULL;
14854 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014855 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014856 if (encoding == NULL && errors == NULL)
14857 return PyObject_Str(x);
14858 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014859 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014860}
14861
Guido van Rossume023fe02001-08-30 03:12:59 +000014862static PyObject *
14863unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14864{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014865 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014866 Py_ssize_t length, char_size;
14867 int share_wstr, share_utf8;
14868 unsigned int kind;
14869 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014870
Benjamin Peterson14339b62009-01-31 16:36:08 +000014871 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014872
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014873 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014874 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014875 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014876 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014877 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014878 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014879 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014880 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014881
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014882 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014883 if (self == NULL) {
14884 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014885 return NULL;
14886 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014887 kind = PyUnicode_KIND(unicode);
14888 length = PyUnicode_GET_LENGTH(unicode);
14889
14890 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014891#ifdef Py_DEBUG
14892 _PyUnicode_HASH(self) = -1;
14893#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014894 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014895#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014896 _PyUnicode_STATE(self).interned = 0;
14897 _PyUnicode_STATE(self).kind = kind;
14898 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014899 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014900 _PyUnicode_STATE(self).ready = 1;
14901 _PyUnicode_WSTR(self) = NULL;
14902 _PyUnicode_UTF8_LENGTH(self) = 0;
14903 _PyUnicode_UTF8(self) = NULL;
14904 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014905 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014906
14907 share_utf8 = 0;
14908 share_wstr = 0;
14909 if (kind == PyUnicode_1BYTE_KIND) {
14910 char_size = 1;
14911 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14912 share_utf8 = 1;
14913 }
14914 else if (kind == PyUnicode_2BYTE_KIND) {
14915 char_size = 2;
14916 if (sizeof(wchar_t) == 2)
14917 share_wstr = 1;
14918 }
14919 else {
14920 assert(kind == PyUnicode_4BYTE_KIND);
14921 char_size = 4;
14922 if (sizeof(wchar_t) == 4)
14923 share_wstr = 1;
14924 }
14925
14926 /* Ensure we won't overflow the length. */
14927 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14928 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014929 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014930 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014931 data = PyObject_MALLOC((length + 1) * char_size);
14932 if (data == NULL) {
14933 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014934 goto onError;
14935 }
14936
Victor Stinnerc3c74152011-10-02 20:39:55 +020014937 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014938 if (share_utf8) {
14939 _PyUnicode_UTF8_LENGTH(self) = length;
14940 _PyUnicode_UTF8(self) = data;
14941 }
14942 if (share_wstr) {
14943 _PyUnicode_WSTR_LENGTH(self) = length;
14944 _PyUnicode_WSTR(self) = (wchar_t *)data;
14945 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014946
Christian Heimesf051e432016-09-13 20:22:02 +020014947 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014948 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014949 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014950#ifdef Py_DEBUG
14951 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14952#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014953 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014954 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014955
14956onError:
14957 Py_DECREF(unicode);
14958 Py_DECREF(self);
14959 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014960}
14961
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014962PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014963"str(object='') -> str\n\
14964str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014965\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014966Create a new string object from the given object. If encoding or\n\
14967errors is specified, then the object must expose a data buffer\n\
14968that will be decoded using the given encoding and error handler.\n\
14969Otherwise, returns the result of object.__str__() (if defined)\n\
14970or repr(object).\n\
14971encoding defaults to sys.getdefaultencoding().\n\
14972errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014973
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014974static PyObject *unicode_iter(PyObject *seq);
14975
Guido van Rossumd57fd912000-03-10 22:53:23 +000014976PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014977 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014978 "str", /* tp_name */
14979 sizeof(PyUnicodeObject), /* tp_size */
14980 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014981 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014982 (destructor)unicode_dealloc, /* tp_dealloc */
14983 0, /* tp_print */
14984 0, /* tp_getattr */
14985 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014986 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014987 unicode_repr, /* tp_repr */
14988 &unicode_as_number, /* tp_as_number */
14989 &unicode_as_sequence, /* tp_as_sequence */
14990 &unicode_as_mapping, /* tp_as_mapping */
14991 (hashfunc) unicode_hash, /* tp_hash*/
14992 0, /* tp_call*/
14993 (reprfunc) unicode_str, /* tp_str */
14994 PyObject_GenericGetAttr, /* tp_getattro */
14995 0, /* tp_setattro */
14996 0, /* tp_as_buffer */
14997 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014998 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014999 unicode_doc, /* tp_doc */
15000 0, /* tp_traverse */
15001 0, /* tp_clear */
15002 PyUnicode_RichCompare, /* tp_richcompare */
15003 0, /* tp_weaklistoffset */
15004 unicode_iter, /* tp_iter */
15005 0, /* tp_iternext */
15006 unicode_methods, /* tp_methods */
15007 0, /* tp_members */
15008 0, /* tp_getset */
15009 &PyBaseObject_Type, /* tp_base */
15010 0, /* tp_dict */
15011 0, /* tp_descr_get */
15012 0, /* tp_descr_set */
15013 0, /* tp_dictoffset */
15014 0, /* tp_init */
15015 0, /* tp_alloc */
15016 unicode_new, /* tp_new */
15017 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015018};
15019
15020/* Initialize the Unicode implementation */
15021
Victor Stinner3a50e702011-10-18 21:21:00 +020015022int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015023{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015024 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015025 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015026 0x000A, /* LINE FEED */
15027 0x000D, /* CARRIAGE RETURN */
15028 0x001C, /* FILE SEPARATOR */
15029 0x001D, /* GROUP SEPARATOR */
15030 0x001E, /* RECORD SEPARATOR */
15031 0x0085, /* NEXT LINE */
15032 0x2028, /* LINE SEPARATOR */
15033 0x2029, /* PARAGRAPH SEPARATOR */
15034 };
15035
Fred Drakee4315f52000-05-09 19:53:39 +000015036 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015037 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015038 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015039 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015040 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015041
Guido van Rossumcacfc072002-05-24 19:01:59 +000015042 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015043 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015044
15045 /* initialize the linebreak bloom filter */
15046 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015047 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015048 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015049
Christian Heimes26532f72013-07-20 14:57:16 +020015050 if (PyType_Ready(&EncodingMapType) < 0)
15051 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015052
Benjamin Petersonc4311282012-10-30 23:21:10 -040015053 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15054 Py_FatalError("Can't initialize field name iterator type");
15055
15056 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15057 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015058
Victor Stinner3a50e702011-10-18 21:21:00 +020015059 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015060}
15061
15062/* Finalize the Unicode implementation */
15063
Christian Heimesa156e092008-02-16 07:38:31 +000015064int
15065PyUnicode_ClearFreeList(void)
15066{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015067 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015068}
15069
Guido van Rossumd57fd912000-03-10 22:53:23 +000015070void
Thomas Wouters78890102000-07-22 19:25:51 +000015071_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015072{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015073 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015074
Serhiy Storchaka05997252013-01-26 12:14:02 +020015075 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015076
Serhiy Storchaka05997252013-01-26 12:14:02 +020015077 for (i = 0; i < 256; i++)
15078 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015079 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015080 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015081}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015082
Walter Dörwald16807132007-05-25 13:52:07 +000015083void
15084PyUnicode_InternInPlace(PyObject **p)
15085{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015086 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015087 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015088#ifdef Py_DEBUG
15089 assert(s != NULL);
15090 assert(_PyUnicode_CHECK(s));
15091#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015092 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015093 return;
15094#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015095 /* If it's a subclass, we don't really know what putting
15096 it in the interned dict might do. */
15097 if (!PyUnicode_CheckExact(s))
15098 return;
15099 if (PyUnicode_CHECK_INTERNED(s))
15100 return;
15101 if (interned == NULL) {
15102 interned = PyDict_New();
15103 if (interned == NULL) {
15104 PyErr_Clear(); /* Don't leave an exception */
15105 return;
15106 }
15107 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015108 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015109 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015110 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015111 if (t == NULL) {
15112 PyErr_Clear();
15113 return;
15114 }
15115 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015116 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015117 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015118 return;
15119 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015120 /* The two references in interned are not counted by refcnt.
15121 The deallocator will take care of this */
15122 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015123 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015124}
15125
15126void
15127PyUnicode_InternImmortal(PyObject **p)
15128{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015129 PyUnicode_InternInPlace(p);
15130 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015131 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015132 Py_INCREF(*p);
15133 }
Walter Dörwald16807132007-05-25 13:52:07 +000015134}
15135
15136PyObject *
15137PyUnicode_InternFromString(const char *cp)
15138{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015139 PyObject *s = PyUnicode_FromString(cp);
15140 if (s == NULL)
15141 return NULL;
15142 PyUnicode_InternInPlace(&s);
15143 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015144}
15145
Alexander Belopolsky40018472011-02-26 01:02:56 +000015146void
15147_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015148{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015149 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015150 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015151 Py_ssize_t i, n;
15152 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015153
Benjamin Peterson14339b62009-01-31 16:36:08 +000015154 if (interned == NULL || !PyDict_Check(interned))
15155 return;
15156 keys = PyDict_Keys(interned);
15157 if (keys == NULL || !PyList_Check(keys)) {
15158 PyErr_Clear();
15159 return;
15160 }
Walter Dörwald16807132007-05-25 13:52:07 +000015161
Benjamin Peterson14339b62009-01-31 16:36:08 +000015162 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15163 detector, interned unicode strings are not forcibly deallocated;
15164 rather, we give them their stolen references back, and then clear
15165 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015166
Benjamin Peterson14339b62009-01-31 16:36:08 +000015167 n = PyList_GET_SIZE(keys);
15168 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015169 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015170 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015171 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015172 if (PyUnicode_READY(s) == -1) {
15173 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015174 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015175 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015176 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015177 case SSTATE_NOT_INTERNED:
15178 /* XXX Shouldn't happen */
15179 break;
15180 case SSTATE_INTERNED_IMMORTAL:
15181 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015182 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015183 break;
15184 case SSTATE_INTERNED_MORTAL:
15185 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015186 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015187 break;
15188 default:
15189 Py_FatalError("Inconsistent interned string state.");
15190 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015191 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015192 }
15193 fprintf(stderr, "total size of all interned strings: "
15194 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15195 "mortal/immortal\n", mortal_size, immortal_size);
15196 Py_DECREF(keys);
15197 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015198 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015199}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015200
15201
15202/********************* Unicode Iterator **************************/
15203
15204typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015205 PyObject_HEAD
15206 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015207 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015208} unicodeiterobject;
15209
15210static void
15211unicodeiter_dealloc(unicodeiterobject *it)
15212{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015213 _PyObject_GC_UNTRACK(it);
15214 Py_XDECREF(it->it_seq);
15215 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015216}
15217
15218static int
15219unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15220{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015221 Py_VISIT(it->it_seq);
15222 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015223}
15224
15225static PyObject *
15226unicodeiter_next(unicodeiterobject *it)
15227{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015228 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015229
Benjamin Peterson14339b62009-01-31 16:36:08 +000015230 assert(it != NULL);
15231 seq = it->it_seq;
15232 if (seq == NULL)
15233 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015234 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015235
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015236 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15237 int kind = PyUnicode_KIND(seq);
15238 void *data = PyUnicode_DATA(seq);
15239 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15240 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015241 if (item != NULL)
15242 ++it->it_index;
15243 return item;
15244 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015245
Benjamin Peterson14339b62009-01-31 16:36:08 +000015246 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015247 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015248 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015249}
15250
15251static PyObject *
15252unicodeiter_len(unicodeiterobject *it)
15253{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015254 Py_ssize_t len = 0;
15255 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015256 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015257 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015258}
15259
15260PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15261
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015262static PyObject *
15263unicodeiter_reduce(unicodeiterobject *it)
15264{
15265 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015266 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015267 it->it_seq, it->it_index);
15268 } else {
15269 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15270 if (u == NULL)
15271 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015272 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015273 }
15274}
15275
15276PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15277
15278static PyObject *
15279unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15280{
15281 Py_ssize_t index = PyLong_AsSsize_t(state);
15282 if (index == -1 && PyErr_Occurred())
15283 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015284 if (it->it_seq != NULL) {
15285 if (index < 0)
15286 index = 0;
15287 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15288 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15289 it->it_index = index;
15290 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015291 Py_RETURN_NONE;
15292}
15293
15294PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15295
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015296static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015297 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015298 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015299 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15300 reduce_doc},
15301 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15302 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015303 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015304};
15305
15306PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015307 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15308 "str_iterator", /* tp_name */
15309 sizeof(unicodeiterobject), /* tp_basicsize */
15310 0, /* tp_itemsize */
15311 /* methods */
15312 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15313 0, /* tp_print */
15314 0, /* tp_getattr */
15315 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015316 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015317 0, /* tp_repr */
15318 0, /* tp_as_number */
15319 0, /* tp_as_sequence */
15320 0, /* tp_as_mapping */
15321 0, /* tp_hash */
15322 0, /* tp_call */
15323 0, /* tp_str */
15324 PyObject_GenericGetAttr, /* tp_getattro */
15325 0, /* tp_setattro */
15326 0, /* tp_as_buffer */
15327 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15328 0, /* tp_doc */
15329 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15330 0, /* tp_clear */
15331 0, /* tp_richcompare */
15332 0, /* tp_weaklistoffset */
15333 PyObject_SelfIter, /* tp_iter */
15334 (iternextfunc)unicodeiter_next, /* tp_iternext */
15335 unicodeiter_methods, /* tp_methods */
15336 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015337};
15338
15339static PyObject *
15340unicode_iter(PyObject *seq)
15341{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015342 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015343
Benjamin Peterson14339b62009-01-31 16:36:08 +000015344 if (!PyUnicode_Check(seq)) {
15345 PyErr_BadInternalCall();
15346 return NULL;
15347 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015348 if (PyUnicode_READY(seq) == -1)
15349 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015350 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15351 if (it == NULL)
15352 return NULL;
15353 it->it_index = 0;
15354 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015355 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015356 _PyObject_GC_TRACK(it);
15357 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015358}
15359
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015360
15361size_t
15362Py_UNICODE_strlen(const Py_UNICODE *u)
15363{
15364 int res = 0;
15365 while(*u++)
15366 res++;
15367 return res;
15368}
15369
15370Py_UNICODE*
15371Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15372{
15373 Py_UNICODE *u = s1;
15374 while ((*u++ = *s2++));
15375 return s1;
15376}
15377
15378Py_UNICODE*
15379Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15380{
15381 Py_UNICODE *u = s1;
15382 while ((*u++ = *s2++))
15383 if (n-- == 0)
15384 break;
15385 return s1;
15386}
15387
15388Py_UNICODE*
15389Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15390{
15391 Py_UNICODE *u1 = s1;
15392 u1 += Py_UNICODE_strlen(u1);
15393 Py_UNICODE_strcpy(u1, s2);
15394 return s1;
15395}
15396
15397int
15398Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15399{
15400 while (*s1 && *s2 && *s1 == *s2)
15401 s1++, s2++;
15402 if (*s1 && *s2)
15403 return (*s1 < *s2) ? -1 : +1;
15404 if (*s1)
15405 return 1;
15406 if (*s2)
15407 return -1;
15408 return 0;
15409}
15410
15411int
15412Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15413{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015414 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015415 for (; n != 0; n--) {
15416 u1 = *s1;
15417 u2 = *s2;
15418 if (u1 != u2)
15419 return (u1 < u2) ? -1 : +1;
15420 if (u1 == '\0')
15421 return 0;
15422 s1++;
15423 s2++;
15424 }
15425 return 0;
15426}
15427
15428Py_UNICODE*
15429Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15430{
15431 const Py_UNICODE *p;
15432 for (p = s; *p; p++)
15433 if (*p == c)
15434 return (Py_UNICODE*)p;
15435 return NULL;
15436}
15437
15438Py_UNICODE*
15439Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15440{
15441 const Py_UNICODE *p;
15442 p = s + Py_UNICODE_strlen(s);
15443 while (p != s) {
15444 p--;
15445 if (*p == c)
15446 return (Py_UNICODE*)p;
15447 }
15448 return NULL;
15449}
Victor Stinner331ea922010-08-10 16:37:20 +000015450
Victor Stinner71133ff2010-09-01 23:43:53 +000015451Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015452PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015453{
Victor Stinner577db2c2011-10-11 22:12:48 +020015454 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015455 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015457 if (!PyUnicode_Check(unicode)) {
15458 PyErr_BadArgument();
15459 return NULL;
15460 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015461 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015462 if (u == NULL)
15463 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015464 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015465 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015466 PyErr_NoMemory();
15467 return NULL;
15468 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015469 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015470 size *= sizeof(Py_UNICODE);
15471 copy = PyMem_Malloc(size);
15472 if (copy == NULL) {
15473 PyErr_NoMemory();
15474 return NULL;
15475 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015476 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015477 return copy;
15478}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015479
Georg Brandl66c221e2010-10-14 07:04:07 +000015480/* A _string module, to export formatter_parser and formatter_field_name_split
15481 to the string.Formatter class implemented in Python. */
15482
15483static PyMethodDef _string_methods[] = {
15484 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15485 METH_O, PyDoc_STR("split the argument as a field name")},
15486 {"formatter_parser", (PyCFunction) formatter_parser,
15487 METH_O, PyDoc_STR("parse the argument as a format string")},
15488 {NULL, NULL}
15489};
15490
15491static struct PyModuleDef _string_module = {
15492 PyModuleDef_HEAD_INIT,
15493 "_string",
15494 PyDoc_STR("string helper module"),
15495 0,
15496 _string_methods,
15497 NULL,
15498 NULL,
15499 NULL,
15500 NULL
15501};
15502
15503PyMODINIT_FUNC
15504PyInit__string(void)
15505{
15506 return PyModule_Create(&_string_module);
15507}
15508
15509
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015510#ifdef __cplusplus
15511}
15512#endif